Compare commits

..
52 Commits
Author SHA1 Message Date
fyears 8cca96e138 0.2.5 2021-12-12 01:21:17 +08:00
fyears 804afabdeb rm some webdav logs 2021-12-12 01:20:38 +08:00
fyears 2576354269 clean desc 2021-12-12 00:56:40 +08:00
fyears 122fec1d75 no need for code mirror here 2021-12-12 00:04:00 +08:00
fyears 27477f8d97 fix typo 2021-12-12 00:02:41 +08:00
fyears e9890c3c79 0.2.4 2021-12-12 00:01:27 +08:00
fyears 44480be707 webdav also sync in vault folder 2021-12-11 23:55:12 +08:00
fyears 437e041e71 fix var in dropbox 2021-12-11 23:52:32 +08:00
fyears 9e4fed4504 tell users vault name is not encrypted 2021-12-11 23:13:55 +08:00
fyears 70e2884f89 scan qr code readme 2021-12-11 23:10:30 +08:00
fyears fb63a38fa0 add draft logo 2021-12-11 22:47:44 +08:00
fyears d21d90868a lfs track more imgs 2021-12-11 22:47:16 +08:00
fyears e6591721e2 prepare to import svg 2021-12-11 22:45:21 +08:00
fyears b6bae792c6 0.2.3 2021-12-11 17:34:45 +08:00
fyears 8624141780 add qrcode export import 2021-12-11 17:33:55 +08:00
fyears 563c2c3ff6 readme 2021-12-10 01:34:19 +08:00
fyears 9a72ac8d66 0.2.2 2021-12-10 01:14:12 +08:00
fyears d980bcbc1b rename titles 2021-12-10 01:12:31 +08:00
fyears 6ebe1a8966 no support digest webdav now 2021-12-10 01:10:38 +08:00
fyears d0ab1d8abe remove webdav hide 2021-12-10 01:09:51 +08:00
fyears b86d116830 add desc for webdav readme 2021-12-10 01:05:47 +08:00
fyears 7d5eaad36f remove unnecessary log 2021-12-10 00:40:54 +08:00
fyears 7a13f4566c full word 2021-12-10 00:18:26 +08:00
fyears d355f72b7a update to 0.2.1 2021-12-10 00:17:31 +08:00
fyears 9b1eebdf90 standarized codes 2021-12-10 00:16:28 +08:00
fyears 2ce461ed6a allow multi pages in dropbox 2021-12-10 00:11:53 +08:00
fyears 3aa91a2a1e add env to build 2021-12-04 01:46:40 +08:00
fyears 2a3e0524c5 fix terrible typo 2021-12-04 01:21:37 +08:00
fyears 2f20ca61ce rebranding 2021-12-04 01:21:15 +08:00
fyears 68ec8b5454 bump version and update name 2021-12-04 01:18:20 +08:00
fyears 2bbbd569c5 fix typo 2021-12-04 01:11:17 +08:00
fyears 62936c4473 attempt to reduce size and use native crypto 2021-12-04 00:55:31 +08:00
fyears 789d07261e 0.1.10 2021-12-01 10:11:20 +08:00
fyears ccd3b49b4b inject env var in webpack 2021-12-01 10:10:39 +08:00
fyears 2930fe5350 0.1.9 2021-12-01 01:50:00 +08:00
fyears a9abf6d834 webpack is slow but works 2021-12-01 01:49:29 +08:00
fyears bdf09e24c3 remove assert 2021-12-01 01:49:07 +08:00
fyears 8dc4b835c9 0.1.8 2021-12-01 00:34:02 +08:00
fyears 2e800af4f8 dropbox should use sub folder 2021-12-01 00:33:24 +08:00
fyears e9e9e2b6eb fix typo 2021-11-30 00:44:26 +08:00
fyears 274e0b8b28 bump to 0.1.7 2021-11-30 00:42:05 +08:00
fyears 2147332cf4 more about dropbox 2021-11-30 00:41:41 +08:00
fyears 262bb9a1fe more disclaimer 2021-11-30 00:32:43 +08:00
fyears 2669a3e8ad fix auth dropbox 2021-11-30 00:21:15 +08:00
fyears bdac16ee24 define clientID or AppKey by env var 2021-11-29 01:03:17 +08:00
fyears 0a7de6588a ugly way to refresh token 2021-11-29 00:04:24 +08:00
fyears 1effcdd7f7 basic dropbox auth flow 2021-11-28 16:28:52 +08:00
fyears 00c840a758 basically working dropbox 2021-11-28 12:20:38 +08:00
fyears 2eb1545f9d more misc 2021-11-28 12:18:44 +08:00
fyears 0d75ea92b1 polish get parent folder 2021-11-28 10:45:46 +08:00
fyears d6cbf4260a esbuild is way faster 2021-11-27 14:49:07 +08:00
fyears 9389039c7a avoid using for await 2021-11-27 14:43:19 +08:00
23 changed files with 1644 additions and 229 deletions
+2
View File
@@ -3,3 +3,5 @@
*.jpeg filter=lfs diff=lfs merge=lfs -text
*.pdf filter=lfs diff=lfs merge=lfs -text
*.enc filter=lfs diff=lfs merge=lfs -text
*.svg filter=lfs diff=lfs merge=lfs -text
*.excalidraw filter=lfs diff=lfs merge=lfs -text
+2
View File
@@ -13,6 +13,8 @@ jobs:
build:
runs-on: ubuntu-latest
environment: env-for-buildci
strategy:
matrix:
node-version: [16.x]
+51 -11
View File
@@ -4,15 +4,18 @@ This is yet another unofficial sync plugin for Obsidian.
## Disclaimer
- **This is NOT the [official sync service](https://github.com/fyears/obsidian-remotely-save.git) provided by Obsidian.**
- **This is NOT the [official sync service](https://obsidian.md/sync) provided by Obsidian.**
## !!!Caution!!!
As of November 2021, the plugin is considered in BETA stage. **DO NOT USE IT for any serious vaults.** **Backup your vault before using this plugin.** Don't be surprise to data loss!
As of Dec 2021, the plugin is considered in BETA stage. **DO NOT USE IT for any serious vaults.** **ALWAYS, ALWAYS, backup your vault before using this plugin.**
## Features
- **Amazon S3 or S3-compatible services are supported.** Webdav supports on the half way.
- Supports:
- Amazon S3 or S3-compatible
- Dropbox
- Webdav
- **Obsidiain Mobile supported.** Vaults can be synced across mobile and desktop devices with the cloud service as the "broker".
- **[End-to-end encryption](./docs/encryption.md) supported.** Files would be encrypted using openssl format before being sent to the cloud **if** user specify a password.
- **[Minimal Intrusive](./docs/minimal_intrusive_design.md).**
@@ -27,26 +30,63 @@ As of November 2021, the plugin is considered in BETA stage. **DO NOT USE IT for
- **Cloud services cost you money.** Always be aware of the costs and pricing.
- **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.
## 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:
- Questions: [GitHub repo Discussions](https://github.com/fyears/remotely-save/discussions)
- Suggestions: also in [GitHub repo Discussions](https://github.com/fyears/remotely-save/discussions)
- Bugs: [GitHub repo Issues](https://github.com/fyears/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.
## Download and Install
- Option #1: [![BuildCI](https://github.com/fyears/obsidian-remotely-save/actions/workflows/auto-build.yml/badge.svg)](https://github.com/fyears/obsidian-remotely-save/actions/workflows/auto-build.yml) Every artifacts are placed in the "Summary" under every successful builds.
- Option #2: Besides manually downloading the files, you can also use [Obsidian42 - BRAT](https://github.com/TfTHacker/obsidian42-brat) to install this plugin.
- Option #3: The pluin would be submitted to the official "community plugin list" in near future.
- Option #1: You can search, download, and install the plugin in official "community plugin list".
- Option #2: [![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.
- Option #3: Besides manually downloading the files, you can also use [Obsidian42 - BRAT](https://github.com/TfTHacker/obsidian42-brat) to install this plugin.
## Usage
### s3
### S3
- Prepare your S3 (-compatible) service information: [endpoint, region](https://docs.aws.amazon.com/general/latest/gr/s3.html), [access key id, secret access key](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-your-credentials.html), bucket name. The bucket should be empty and solely for syncing a vault.
- Configure (enable) [CORS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enabling-cors-examples.html) for requests from `app://obsidian.md` and `capacitor://localhost` and `http://localhost`. It's unfortunately required, because the plugin sends requests from a browser-like envirement. And those addresses are tested and found on desktop and ios and android.
- Download and enable this plugin.
- Enter your infomation to the settings of this plugin.
- Enter your information to the settings of this plugin.
- If you want to enable end-to-end encryption, also set a password in settings. If you do not specify a password, the files and folders are synced in plain, original content to the cloud.
- Click the new "switch" icon on the ribbon (the left sidebar), **every time** you want to sync your vault between local and remote. (No "auto sync" yet.)
- **Be patient while syncing.** Especially in the first-time sync.
### Dropbox
- **This plugin's function for Dropbox is not as mature as functions for S3.**
- **This plugin is NOT an official Dropbox product.** The plugin just uses Dropbox's public API.
- After the authorization, the plugin can read your name and email (which cannot be unselected on Dropbox api), and read and write files in your Dropbox's `/Apps/remotely-save/${vaultName}` folder.
- If you decide to authorize this plugin to connect to Dropbox, please go to plugin's settings, and choose Dropbox 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**.
### webdav
- **webdav support is buggy (as of now, 20211122) and considered experimental, so it's hidden by default.** Highly recommend to use the more stable s3.
- If you decide to give it a try, open settings, and click "Choose service" area five times, then a Notice should show up. Close and open settings again then you will be able to select webdav.
- Currently webdav server should enable CORS for requests, because of technical limitations of mobile.
- **webdav support is considered experimental.**
- Currently only supports BASIC authorization method.
- Currently webdav server has to be enabled CORS for requests from `app://obsidian.md` and `capacitor://localhost` and `http://localhost`, **AND** all webdav HTTP methods, **AND** all webdav headers. These are required, because Obsidian mobile works like a browser and mobile plugins are limited by CORS policies.
- Popular software NextCloud and OwnCloud do **NOT** enable CORS by default. If you are using any of them, you should evaluate the risk, and find a way to enable CORS, before using this plugin.
- The plugin is tested successfully under python package [`wsgidav` (version 4.0)](https://github.com/mar10/wsgidav). See [this issue](https://github.com/mar10/wsgidav/issues/239) for some details.
- 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**.
## Import And Export Plugin Settings By QR Code
It's often verbose / inconvenient to input credentials on mobile. (On different desktop computers, it's trivial to copy and paste `data.json` across different devices.)
So this plugin has a helper function to export settings as a QR code, then you could use mobile device's camera to import the settings.
Steps:
1. Configure the plugin settings on one device, and make sure the sync functions work. (E.g, you could sync notes using S3 credentials.)
2. Open plugin settings page. Then scroll down the page, until the section "Import and Export Settings". Click the button "Get QR Code". A new modal should show up and you should see a QR code.
3. On a second device, make sure the vault name is the same as the first device's.
4. On that second device, use its camera app, or any apps that support scanning QR codes, to scan the QR code from the first device. (On latest iOS, the system's built in camera app should work. On Android, at least one open source app [Binary Eye](https://github.com/markusfisch/BinaryEye) is tested to be working.)
5. A link / url / address should be identified in the scan-QR-code app, and you could follow the instruction in the app, and then you should be redirected to open the Obsidian app.
6. And finally, there should be a new notice in the Obsidian app saying the settings are successfully imported. Otherwise please check the error message in the notice.
+3
View File
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:6b33b2a71f2d91988416c17015b59ef205dbf6a8c704ecac1cc95ed03ccc2c8e
size 16537
+3
View File
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:98358aa726dcb5565164ff260634f5c527223d1f2ec1d0410b400625c8dad704
size 14082
+3
View File
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:02a5057ebe38e4c3835c8354f53aca01c4c2335d8a0435e22f509b4ca4a73ca4
size 12889
+45
View File
@@ -0,0 +1,45 @@
import dotenv from "dotenv/config";
import esbuild from "esbuild";
import process from "process";
// import builtins from 'builtin-modules'
const banner = `/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;
const prod = process.argv[2] === "production";
const DEFAULT_DROPBOX_APP_KEY = process.env.DROPBOX_APP_KEY || "";
esbuild
.build({
banner: {
js: banner,
},
loader: {
".svg": "text",
},
entryPoints: ["./src/main.ts"],
bundle: true,
external: [
"obsidian",
"electron",
"fs",
"crypto",
// ...builtins
],
format: "cjs",
watch: !prod,
target: "es2016",
logLevel: "info",
sourcemap: prod ? false : "inline",
treeShaking: true,
minify: prod,
outfile: "main.js",
define: {
"process.env.DEFAULT_DROPBOX_APP_KEY": `"${DEFAULT_DROPBOX_APP_KEY}"`,
},
})
.catch(() => process.exit(1));
+3 -3
View File
@@ -1,9 +1,9 @@
{
"id": "obsidian-remotely-save",
"id": "remotely-save",
"name": "Remotely Save",
"version": "0.1.6",
"version": "0.2.5",
"minAppVersion": "0.12.15",
"description": "Yet another unofficial plugin allowing users to sync 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",
"authorUrl": "https://github.com/fyears",
"isDesktopOnly": false
+21 -5
View File
@@ -1,14 +1,20 @@
{
"name": "obsidian-remotely-save",
"version": "0.1.6",
"name": "remotely-save",
"version": "0.2.5",
"description": "This is yet another sync plugin for Obsidian app.",
"scripts": {
"dev": "webpack --mode development --watch",
"dev": "node esbuild.config.mjs",
"build2": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"build": "webpack --mode production",
"format": "npx prettier --write .",
"clean": "npx rimraf main.js",
"test": "cross-env TS_NODE_COMPILER_OPTIONS={\\\"module\\\":\\\"commonjs\\\"} mocha -r ts-node/register 'tests/**/*.ts'"
},
"browser": {
"path": "path-browserify",
"process": "process/browser",
"stream": "stream-browserify"
},
"source": "main.ts",
"keywords": [],
"author": "",
@@ -16,21 +22,26 @@
"devDependencies": {
"@types/chai": "^4.2.22",
"@types/chai-as-promised": "^7.1.4",
"@types/jsdom": "^16.2.13",
"@types/mime-types": "^2.1.1",
"@types/mocha": "^9.0.0",
"@types/node": "^14.14.37",
"@types/qrcode": "^1.4.1",
"builtin-modules": "^3.2.0",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"cross-env": "^7.0.3",
"dotenv": "^10.0.0",
"esbuild": "^0.14.0",
"jsdom": "^19.0.0",
"mocha": "^9.1.3",
"prettier": "^2.4.1",
"terser-webpack-plugin": "^5.2.4",
"ts-loader": "^9.2.6",
"ts-node": "^10.4.0",
"tslib": "^2.2.0",
"typescript": "^4.4.4",
"webdav-server": "^2.6.2",
"webpack": "^5.58.2",
"webpack": "^5.64.4",
"webpack-cli": "^4.9.1"
},
"dependencies": {
@@ -38,17 +49,22 @@
"@aws-sdk/lib-storage": "^3.40.1",
"@aws-sdk/signature-v4-crt": "^3.37.0",
"acorn": "^8.5.0",
"assert": "^2.0.0",
"aws-crt": "^1.10.1",
"buffer": "^6.0.3",
"codemirror": "^5.63.1",
"crypto-browserify": "^3.12.0",
"dropbox": "^10.22.0",
"localforage": "^1.10.0",
"mime-types": "^2.1.33",
"obsidian": "^0.12.0",
"path-browserify": "^1.0.1",
"process": "^0.11.10",
"qrcode": "^1.5.0",
"rfc4648": "^1.5.0",
"rimraf": "^3.0.2",
"stream-browserify": "^3.0.0",
"util": "^0.12.4",
"webdav": "^4.7.0",
"webdav-fs": "^4.0.0",
"xregexp": "^5.1.0"
+47 -1
View File
@@ -1,8 +1,44 @@
/**
* Only type defs here.
* To avoid circular dependency.
*/
export type SUPPORTED_SERVICES_TYPE = "s3" | "webdav";
export type SUPPORTED_SERVICES_TYPE = "s3" | "webdav" | "dropbox";
export interface S3Config {
s3Endpoint: string;
s3Region: string;
s3AccessKeyID: string;
s3SecretAccessKey: string;
s3BucketName: string;
}
export interface DropboxConfig {
accessToken: string;
clientID: string;
refreshToken: string;
accessTokenExpiresInSeconds: number;
accessTokenExpiresAtTime: number;
accountID: string;
username: string;
}
export type WebdavAuthType = "digest" | "basic";
export interface WebdavConfig {
address: string;
username: string;
password: string;
authType: WebdavAuthType;
}
export interface RemotelySavePluginSettings {
s3: S3Config;
webdav: WebdavConfig;
dropbox: DropboxConfig;
password: string;
serviceType: SUPPORTED_SERVICES_TYPE;
}
export interface RemoteItem {
key: string;
@@ -11,3 +47,13 @@ export interface RemoteItem {
remoteType: SUPPORTED_SERVICES_TYPE;
etag?: string;
}
export const COMMAND_URI = "remotely-save";
export const COMMAND_CALLBACK = "remotely-save-cb";
export interface UriParams {
func?: string;
vault?: string;
ver?: string;
data?: string;
}
+76
View File
@@ -0,0 +1,76 @@
import QRCode from "qrcode";
import {
COMMAND_URI,
UriParams,
RemotelySavePluginSettings,
} from "./baseTypes";
export const exportQrCodeUri = async (
settings: RemotelySavePluginSettings,
currentVaultName: string,
pluginVersion: string
) => {
const data = encodeURIComponent(JSON.stringify(settings));
const vault = encodeURIComponent(currentVaultName);
const version = encodeURIComponent(pluginVersion);
const rawUri = `obsidian://${COMMAND_URI}?func=settings&version=${version}&vault=${vault}&data=${data}`;
// console.log(uri)
const imgUri = await QRCode.toDataURL(rawUri);
return {
rawUri,
imgUri,
};
};
export interface ProcessQrCodeResultType {
status: "error" | "ok";
message: string;
result?: RemotelySavePluginSettings;
}
export const importQrCodeUri = (
inputParams: any,
currentVaultName: string
): ProcessQrCodeResultType => {
let params = inputParams as UriParams;
if (
params.func === undefined ||
params.func !== "settings" ||
params.vault === undefined ||
params.data === undefined
) {
return {
status: "error",
message: `the uri is not for exporting/importing settings: ${JSON.stringify(
inputParams
)}`,
};
}
if (params.vault !== currentVaultName) {
return {
status: "error",
message: `the target vault is ${
params.vault
} but you are currently in ${currentVaultName}: ${JSON.stringify(
inputParams
)}`,
};
}
let settings = {} as RemotelySavePluginSettings;
try {
settings = JSON.parse(params.data);
} catch (e) {
return {
status: "error",
message: `errors while parsing settings: ${JSON.stringify(inputParams)}`,
};
}
return {
status: "ok",
message: "ok",
result: settings,
};
};
+407 -101
View File
@@ -11,6 +11,7 @@ import {
TFolder,
} from "obsidian";
import * as CodeMirror from "codemirror";
import process from "process";
import {
prepareDBs,
destroyDBs,
@@ -25,36 +26,46 @@ import type { InternalDBs } from "./localdb";
import type { SyncStatusType, PasswordCheckType } from "./sync";
import { isPasswordOk, getSyncPlan, doActualSync } from "./sync";
import { S3Config, DEFAULT_S3_CONFIG } from "./s3";
import { WebdavConfig, DEFAULT_WEBDAV_CONFIG, WebdavAuthType } from "./webdav";
import { DEFAULT_S3_CONFIG } from "./remoteForS3";
import { DEFAULT_WEBDAV_CONFIG } from "./remoteForWebdav";
import {
DEFAULT_DROPBOX_CONFIG,
getAuthUrlAndVerifier,
sendAuthReq,
setConfigBySuccessfullAuthInplace,
} from "./remoteForDropbox";
import { RemoteClient } from "./remote";
import { exportSyncPlansToFiles } from "./debugMode";
import { SUPPORTED_SERVICES_TYPE } from "./baseTypes";
interface RemotelySavePluginSettings {
s3: S3Config;
webdav: WebdavConfig;
password: string;
serviceType: SUPPORTED_SERVICES_TYPE;
enableExperimentService: boolean;
}
import { COMMAND_URI, COMMAND_CALLBACK } from "./baseTypes";
import type {
SUPPORTED_SERVICES_TYPE,
S3Config,
DropboxConfig,
WebdavAuthType,
WebdavConfig,
RemotelySavePluginSettings,
} from "./baseTypes";
import type { ProcessQrCodeResultType } from "./importExport";
import { exportQrCodeUri, importQrCodeUri } from "./importExport";
const DEFAULT_SETTINGS: RemotelySavePluginSettings = {
s3: DEFAULT_S3_CONFIG,
webdav: DEFAULT_WEBDAV_CONFIG,
dropbox: DEFAULT_DROPBOX_CONFIG,
password: "",
serviceType: "s3",
enableExperimentService: false,
};
export default class RemotelySavePlugin extends Plugin {
settings: RemotelySavePluginSettings;
cm: CodeMirror.Editor;
// cm: CodeMirror.Editor;
db: InternalDBs;
syncStatus: SyncStatusType;
async onload() {
console.log("loading plugin obsidian-remotely-save");
console.log(`loading plugin ${this.manifest.id}`);
await this.loadSettings();
@@ -74,6 +85,32 @@ export default class RemotelySavePlugin extends Plugin {
})
);
this.registerObsidianProtocolHandler(COMMAND_URI, async (inputParams) => {
const parsed = importQrCodeUri(inputParams, this.app.vault.getName());
if (parsed.status === "error") {
new Notice(parsed.message);
} else {
const copied = JSON.parse(JSON.stringify(parsed.result));
// new Notice(JSON.stringify(copied))
this.settings = copied;
this.saveSettings();
new Notice(
`New settings for ${this.manifest.name} saved. Reopen the plugin Settings to the effect.`
);
}
});
this.registerObsidianProtocolHandler(
COMMAND_CALLBACK,
async (inputParams) => {
new Notice(
`Your uri call a callback that's not supported yet: ${JSON.stringify(
inputParams
)}`
);
}
);
this.addRibbonIcon("switch", "Remotely Save", async () => {
if (this.syncStatus !== "idle") {
new Notice(
@@ -91,18 +128,22 @@ export default class RemotelySavePlugin extends Plugin {
new Notice("2/6 Starting to fetch remote meta data.");
this.syncStatus = "getting_remote_meta";
const self = this;
const client = new RemoteClient(
this.settings.serviceType,
this.settings.s3,
this.settings.webdav
this.settings.webdav,
this.settings.dropbox,
this.app.vault.getName(),
() => self.saveSettings()
);
const remoteRsp = await client.listFromRemote();
// console.log(remoteRsp);
new Notice("3/6 Starting to fetch local meta data.");
this.syncStatus = "getting_local_meta";
const local = this.app.vault.getAllLoadedFiles();
const localHistory = await loadDeleteRenameHistoryTable(this.db);
// console.log(remoteRsp);
// console.log(local);
// console.log(localHistory);
@@ -174,12 +215,19 @@ export default class RemotelySavePlugin extends Plugin {
}
onunload() {
console.log("unloading plugin obsidian-remotely-save");
console.log(`unloading plugin ${this.manifest.id}`);
this.destroyDBs();
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.settings = Object.assign(
{},
JSON.parse(JSON.stringify(DEFAULT_SETTINGS)) /* copy an object */,
await this.loadData()
);
if (this.settings.dropbox.clientID === "") {
this.settings.dropbox.clientID = DEFAULT_SETTINGS.dropbox.clientID;
}
}
async saveSettings() {
@@ -209,20 +257,22 @@ export class PasswordModal extends Modal {
// contentEl.setText("Add Or change password.");
contentEl.createEl("h2", { text: "Hold on and PLEASE READ ON..." });
contentEl.createEl("p", {
text: "If the field is not empty, files are enctrypted using the password locally before sent to remote.",
text: "If the field is not empty, files would be encrypted locally before being uploaded.",
});
contentEl.createEl("p", {
text: "If the field is empty, then no password is used, and files would be sent without encryption.",
text: "If the field is empty, then files would be uploaded without encryption.",
});
contentEl.createEl("p", {
text: "Attention 1/4: The password itself is stored in PLAIN TEXT LOCALLY and would not be sent to remote by this plugin.",
text: "Attention 1/4: The password itself is stored in PLAIN TEXT LOCALLY.",
cls: "password-disclaimer",
});
contentEl.createEl("p", {
text: "Attention 2/4: Non-empty file contents are encrypted using openssl format. File/directory path are also encrypted then applied base32. BUT, some metadata such as file sizes and directory structures are not encrypted or can be easily guessed, and directory path are stored as 0-byte-size object remotely.",
text: "Attention 2/4: Some metadata are not encrypted or can be easily guessed. (File sizes are closed to their unencrypted ones, and directory path are stored as 0-byte-size object.)",
cls: "password-disclaimer",
});
contentEl.createEl("p", {
text: "Attention 3/4: Before changing password, you should make sure the remote store (s3/webdav/...) IS EMPTY, or REMOTE FILES WERE ENCRYPTED BY THAT NEW PASSWORD. OTHERWISE SOMETHING BAD WOULD HAPPEN!",
text: "Attention 3/4: You should make sure the remote store IS EMPTY, or REMOTE FILES WERE ENCRYPTED BY THAT NEW PASSWORD, to avoid conflictions.",
});
contentEl.createEl("p", {
text: "Attention 4/4: The longer the password, the better.",
@@ -237,7 +287,7 @@ export class PasswordModal extends Modal {
new Notice("New password saved!");
this.close();
});
button.setClass("password_second_confirm");
button.setClass("password-second-confirm");
})
.addButton((button) => {
button.setButtonText("Go Back");
@@ -253,6 +303,166 @@ export class PasswordModal extends Modal {
}
}
export class DropboxAuthModal 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() {
let { contentEl } = this;
const { authUrl, verifier } = await getAuthUrlAndVerifier(
this.plugin.settings.dropbox.clientID
);
contentEl.createEl("p", {
text: "Step 1: Visit the address in a browser, and follow the steps.",
});
contentEl.createEl("p").createEl("a", {
href: authUrl,
text: authUrl,
});
contentEl.createEl("p", {
text: 'Step 2: In the end of the web flow, you obtain a long code. Paste it here then click "Submit".',
});
let authCode = "";
new Setting(contentEl)
.setName("Auth Code from web page")
.setDesc('You need to click "Confirm".')
.addText((text) =>
text
.setPlaceholder("")
.setValue("")
.onChange((val) => {
authCode = val.trim();
})
)
.addButton(async (button) => {
button.setButtonText("Confirm");
button.onClick(async () => {
new Notice("Trying to connect to Dropbox");
try {
const authRes = await sendAuthReq(
this.plugin.settings.dropbox.clientID,
verifier,
authCode
);
const self = this;
setConfigBySuccessfullAuthInplace(
this.plugin.settings.dropbox,
authRes,
() => self.plugin.saveSettings()
);
const client = new RemoteClient(
"dropbox",
undefined,
undefined,
this.plugin.settings.dropbox,
this.app.vault.getName(),
() => self.plugin.saveSettings()
);
const username = await client.getUser();
this.plugin.settings.dropbox.username = username;
await this.plugin.saveSettings();
new Notice(`Good! We've connected to Dropbox as user ${username}!`);
this.authDiv.toggleClass(
"dropbox-auth-button-hide",
this.plugin.settings.dropbox.username !== ""
);
this.revokeAuthDiv.toggleClass(
"dropbox-revoke-auth-button-hide",
this.plugin.settings.dropbox.username === ""
);
this.revokeAuthSetting.setDesc(
`You've connected as user ${this.plugin.settings.dropbox.username}. If you want to disconnect, click this button.`
);
this.close();
} catch (err) {
console.error(err);
new Notice("Something goes wrong while connecting to Dropbox.");
}
});
});
}
onClose() {
let { contentEl } = this;
contentEl.empty();
}
}
export class ExportSettingsQrCodeModal extends Modal {
plugin: RemotelySavePlugin;
constructor(app: App, plugin: RemotelySavePlugin) {
super(app);
this.plugin = plugin;
}
async onOpen() {
let { contentEl } = this;
const { rawUri, imgUri } = await exportQrCodeUri(
this.plugin.settings,
this.app.vault.getName(),
this.plugin.manifest.version
);
const div1 = contentEl.createDiv();
div1.createEl("p", {
text: "You can use another device to scan this qrcode.",
});
div1.createEl("p", {
text: "Or, you can click the button to copy the special url.",
});
const div2 = contentEl.createDiv();
div2.createEl(
"button",
{
text: "Click to copy the special URI",
},
(el) => {
el.onclick = async () => {
await navigator.clipboard.writeText(rawUri);
new Notice("special uri copied to clipboard!");
};
}
);
const div3 = contentEl.createDiv();
div3.createEl(
"img",
{
cls: "qrcode-img",
},
async (el) => {
el.src = imgUri;
}
);
}
onClose() {
let { contentEl } = this;
contentEl.empty();
}
}
class RemotelySaveSettingTab extends PluginSettingTab {
plugin: RemotelySavePlugin;
@@ -293,52 +503,20 @@ class RemotelySaveSettingTab extends PluginSettingTab {
});
});
// we need to create the div in advance of s3Div and webdavDiv
// we need to create the div in advance of any other service divs
const serviceChooserDiv = generalDiv.createEl("div");
let clickChooserTimes = 0;
serviceChooserDiv.onClickEvent((x) => {
if (Platform.isIosApp) {
// downgrade the experiment
// because iOS doesn't support x.detail
clickChooserTimes += 1;
setTimeout(function () {
clickChooserTimes = 0;
}, 2000);
}
if ((Platform.isIosApp && clickChooserTimes === 5) || x.detail === 5) {
if (this.plugin.settings.serviceType === "webdav") {
new Notice(
"You've enabled hidden unstable experimental webdav support before. Nothing changes."
);
} else if (!this.plugin.settings.enableExperimentService) {
this.plugin.settings.enableExperimentService = true;
this.plugin.saveSettings();
new Notice(
"You've enabled hidden unstable experimental webdav support. Reopen settings again and try webdav with caution."
);
} else if (this.plugin.settings.enableExperimentService) {
this.plugin.settings.enableExperimentService = false;
this.plugin.saveSettings();
new Notice(
"You've disabled hidden unstable experimental webdav support. Reopen settings again."
);
}
}
x.preventDefault();
});
const s3Div = containerEl.createEl("div", { cls: "s3-hide" });
s3Div.toggleClass("s3-hide", this.plugin.settings.serviceType !== "s3");
s3Div.createEl("h2", { text: "S3 (-compatible) Service" });
s3Div.createEl("h2", { text: "Remote For S3 (-compatible)" });
s3Div.createEl("p", {
text: "You can use Amazon S3 or another S3-compatible service to sync your vault. Enter your bucket information below.",
text: "Disclaimer: This plugin is NOT an official Amazon product.",
cls: "s3-disclaimer",
});
s3Div.createEl("p", {
text: "Disclaimer: The infomation is stored in PLAIN TEXT locally. Other malicious/harmful/faulty plugins may or may not be able to read the info. If you see any unintentional access to your S3 bucket, please immediately delete the access key to stop further accessment.",
text: "Disclaimer: The information is stored in PLAIN TEXT locally. Other malicious/harmful/faulty plugins could read the info. If you see any unintentional access to your bucket, please immediately delete the access key on your AWS (or other S3-service provider) settings.",
cls: "s3-disclaimer",
});
@@ -347,7 +525,7 @@ class RemotelySaveSettingTab extends PluginSettingTab {
});
s3Div.createEl("p", {
text: "Some Amazon S3 official docs:",
text: "Some Amazon S3 official docs for references:",
});
const s3LinksUl = s3Div.createEl("div").createEl("ul");
@@ -453,21 +631,134 @@ class RemotelySaveSettingTab extends PluginSettingTab {
});
});
const dropboxDiv = containerEl.createEl("div", { cls: "dropbox-hide" });
dropboxDiv.toggleClass(
"dropbox-hide",
this.plugin.settings.serviceType !== "dropbox"
);
dropboxDiv.createEl("h2", { text: "Remote For Dropbox" });
dropboxDiv.createEl("p", {
text: "Disclaimer: This app is NOT an official Dropbox product.",
cls: "dropbox-disclaimer",
});
dropboxDiv.createEl("p", {
text: "Disclaimer: The information is stored in PLAIN TEXT locally. Other malicious/harmful/faulty plugins could read the info. If you see any unintentional access to your Dropbox, please immediately disconnect this app on https://www.dropbox.com/account/connected_apps .",
cls: "dropbox-disclaimer",
});
dropboxDiv.createEl("p", {
text: `We will create and sync inside the folder /Apps/${
this.plugin.manifest.id
}/${this.app.vault.getName()} on your Dropbox.`,
});
const dropboxSelectAuthDiv = dropboxDiv.createDiv();
const dropboxAuthDiv = dropboxSelectAuthDiv.createDiv({
cls: "dropbox-auth-button-hide",
});
const dropboxRevokeAuthDiv = dropboxSelectAuthDiv.createDiv({
cls: "dropbox-revoke-auth-button-hide",
});
const revokeAuthSetting = new Setting(dropboxRevokeAuthDiv)
.setName("Revoke Auth")
.setDesc(
`You've connected as user ${this.plugin.settings.dropbox.username}. If you want to disconnect, click this button`
)
.addButton(async (button) => {
button.setButtonText("Revoke Auth");
button.onClick(async () => {
try {
const self = this;
const client = new RemoteClient(
"dropbox",
undefined,
undefined,
this.plugin.settings.dropbox,
this.app.vault.getName(),
() => self.plugin.saveSettings()
);
await client.revokeAuth();
this.plugin.settings.dropbox = JSON.parse(
JSON.stringify(DEFAULT_DROPBOX_CONFIG)
);
await this.plugin.saveSettings();
dropboxAuthDiv.toggleClass(
"dropbox-auth-button-hide",
this.plugin.settings.dropbox.username !== ""
);
dropboxRevokeAuthDiv.toggleClass(
"dropbox-revoke-auth-button-hide",
this.plugin.settings.dropbox.username === ""
);
new Notice("Revoked!");
} catch (err) {
console.error(err);
new Notice("Something goes wrong while revoking");
}
});
});
new Setting(dropboxAuthDiv)
.setName("Auth")
.setDesc("Auth")
.addButton(async (button) => {
button.setButtonText("Auth");
button.onClick(async () => {
new DropboxAuthModal(
this.app,
this.plugin,
dropboxAuthDiv,
dropboxRevokeAuthDiv,
revokeAuthSetting
).open();
});
});
dropboxAuthDiv.toggleClass(
"dropbox-auth-button-hide",
this.plugin.settings.dropbox.username !== ""
);
dropboxRevokeAuthDiv.toggleClass(
"dropbox-revoke-auth-button-hide",
this.plugin.settings.dropbox.username === ""
);
new Setting(dropboxDiv)
.setName("check connectivity")
.setDesc("check connectivity")
.addButton(async (button) => {
button.setButtonText("Check");
button.onClick(async () => {
new Notice("Checking...");
const self = this;
const client = new RemoteClient(
"dropbox",
undefined,
undefined,
this.plugin.settings.dropbox,
this.app.vault.getName(),
() => self.plugin.saveSettings()
);
const res = await client.checkConnectivity();
if (res) {
new Notice("Great! We can connect to Dropbox!");
} else {
new Notice("We cannot connect to Dropbox.");
}
});
});
const webdavDiv = containerEl.createEl("div", { cls: "webdav-hide" });
webdavDiv.toggleClass(
"webdav-hide",
this.plugin.settings.serviceType !== "webdav"
);
webdavDiv.createEl("h2", { text: "Webdav Service" });
webdavDiv.createEl("h2", { text: "Remote For Webdav" });
webdavDiv.createEl("p", {
text: "Disclaimer: Webdav functions are more experimental, and s3 functions are more stable now.",
cls: "webdav-disclaimer",
});
webdavDiv.createEl("p", {
text: "Disclaimer: The infomation is stored in PLAIN TEXT locally. Other malicious/harmful/faulty plugins may or may not be able to read the info. If you see any unintentional access to your webdav server, please immediately change the username and/or password to stop further accessment.",
text: "Disclaimer: The information is stored in PLAIN TEXT 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.",
cls: "webdav-disclaimer",
});
@@ -475,6 +766,10 @@ class RemotelySaveSettingTab extends PluginSettingTab {
text: "You need to configure CORS to allow requests from origin app://obsidian.md and capacitor://localhost and http://localhost",
});
webdavDiv.createEl("p", {
text: `We will create and sync inside the folder /${this.app.vault.getName()} on your server.`,
});
new Setting(webdavDiv)
.setName("server address")
.setDesc("server address")
@@ -516,12 +811,10 @@ class RemotelySaveSettingTab extends PluginSettingTab {
new Setting(webdavDiv)
.setName("server auth type")
.setDesc(
"Server auth type. If you do not set password, this option would be ignored."
)
.setDesc("If no password, this option would be ignored.")
.addDropdown((dropdown) => {
dropdown.addOption("basic", "basic");
dropdown.addOption("digest", "digest");
// dropdown.addOption("digest", "digest");
dropdown
.setValue(this.plugin.settings.webdav.authType)
@@ -541,7 +834,9 @@ class RemotelySaveSettingTab extends PluginSettingTab {
const client = new RemoteClient(
"webdav",
undefined,
this.plugin.settings.webdav
this.plugin.settings.webdav,
undefined,
this.app.vault.getName()
);
const res = await client.checkConnectivity();
if (res) {
@@ -556,20 +851,13 @@ class RemotelySaveSettingTab extends PluginSettingTab {
// after s3Div and webdavDiv being created
new Setting(serviceChooserDiv)
.setName("Choose service")
.setDesc("Choose a service, by default s3")
.setDesc("Choose a service.")
.addDropdown(async (dropdown) => {
const currService = this.plugin.settings.serviceType;
const enableExperimentService =
this.plugin.settings.enableExperimentService;
dropdown.addOption("s3", "s3 (-compatible)");
if (currService === "webdav" || enableExperimentService) {
dropdown.addOption("webdav", "webdav (experimental)");
if (!enableExperimentService) {
this.plugin.settings.enableExperimentService = true;
await this.plugin.saveSettings();
}
}
dropdown.addOption("s3", "S3 (-compatible)");
dropdown.addOption("dropbox", "Dropbox");
dropdown.addOption("webdav", "Webdav");
dropdown
.setValue(this.plugin.settings.serviceType)
.onChange(async (val: SUPPORTED_SERVICES_TYPE) => {
@@ -578,6 +866,10 @@ class RemotelySaveSettingTab extends PluginSettingTab {
"s3-hide",
this.plugin.settings.serviceType !== "s3"
);
dropboxDiv.toggleClass(
"dropbox-hide",
this.plugin.settings.serviceType !== "dropbox"
);
webdavDiv.toggleClass(
"webdav-hide",
this.plugin.settings.serviceType !== "webdav"
@@ -586,16 +878,34 @@ class RemotelySaveSettingTab extends PluginSettingTab {
});
});
// import and export
const importExportDiv = containerEl.createEl("div");
importExportDiv.createEl("h2", { text: "Import and Export Settings" });
new Setting(importExportDiv)
.setName("export")
.setDesc("Export all settings by generating a qrcode.")
.addButton(async (button) => {
button.setButtonText("Get QR Code");
button.onClick(async () => {
new ExportSettingsQrCodeModal(this.app, this.plugin).open();
});
});
new Setting(importExportDiv)
.setName("import")
.setDesc(
"You should open a camera or scan-qrcode app, to manually scan the QR code."
);
const debugDiv = containerEl.createEl("div");
debugDiv.createEl("h2", { text: "Debug" });
const syncPlanDiv = debugDiv.createEl("div");
syncPlanDiv.createEl("p", {
text: "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.",
});
new Setting(syncPlanDiv)
.setName("export sync plans")
.setDesc("export sync plans")
.setDesc(
"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"
)
.addButton(async (button) => {
button.setButtonText("Export");
button.onClick(async () => {
@@ -603,7 +913,6 @@ class RemotelySaveSettingTab extends PluginSettingTab {
new Notice("sync plans history exported");
});
});
new Setting(syncPlanDiv)
.setName("delete sync plans history in db")
.setDesc("delete sync plans history in db")
@@ -616,13 +925,11 @@ class RemotelySaveSettingTab extends PluginSettingTab {
});
const syncMappingDiv = debugDiv.createEl("div");
syncMappingDiv.createEl("p", {
text: "Sync mappings history stores the actual LOCAL last modified time of the REMOTE objects. Clearing it may cause unnecessary data exchanges in next-time sync.",
});
new Setting(syncMappingDiv)
.setName("delete sync mappings history in db")
.setDesc("delete sync mappings history in db")
.setDesc(
"Sync mappings history stores the actual LOCAL last modified time of the REMOTE objects. Clearing it may cause unnecessary data exchanges in next-time sync. Click the button to delete sync mappings history in db"
)
.addButton(async (button) => {
button.setButtonText("Delete Sync Mappings");
button.onClick(async () => {
@@ -632,12 +939,11 @@ class RemotelySaveSettingTab extends PluginSettingTab {
});
const dbsResetDiv = debugDiv.createEl("div");
syncMappingDiv.createEl("p", {
text: "Reset local internal caches/databases (for debugging purposes). You would want to reload the plugin after resetting this. This option will not empty the {s3, password...} settings.",
});
new Setting(syncMappingDiv)
new Setting(dbsResetDiv)
.setName("reset local internal cache/databases")
.setDesc("reset local internal cache/databases")
.setDesc(
"Reset local internal caches/databases (for debugging purposes). You would want to reload the plugin after resetting this. This option will not empty the {s3, password...} settings."
)
.addButton(async (button) => {
button.setButtonText("Reset");
button.onClick(async () => {
+22 -1
View File
@@ -45,7 +45,10 @@ export const getFolderLevels = (x: string) => {
const y1 = x.split("/");
let i = 0;
for (let index = 0; index + 1 < y1.length; index++) {
res.push(y1.slice(0, index + 1).join("/"));
const k = y1.slice(0, index + 1).join("/");
if (k !== "" && k !== "/") {
res.push(k);
}
}
return res;
};
@@ -142,3 +145,21 @@ export const getPathFolder = (a: string) => {
const b = path.posix.dirname(a);
return b.endsWith("/") ? b : `${b}/`;
};
/**
* https://stackoverflow.com/questions/54511144
* @param a
* @param delimiter
* @returns
*/
export const setToString = (a: Set<string>, delimiter: string = ",") => {
return [...a].join(delimiter);
};
export const extractSvgSub = (x: string, subEl: string = "rect") => {
const parser = new window.DOMParser();
const dom = parser.parseFromString(x, "image/svg+xml");
const svg = dom.querySelector("svg");
svg.setAttribute("viewbox", "0 0 10 10");
return svg.innerHTML;
};
+88 -11
View File
@@ -1,28 +1,56 @@
import { Vault } from "obsidian";
import type { SUPPORTED_SERVICES_TYPE } from "./baseTypes";
import * as s3 from "./s3";
import * as webdav from "./webdav";
import type {
SUPPORTED_SERVICES_TYPE,
S3Config,
DropboxConfig,
WebdavConfig,
} from "./baseTypes";
import * as s3 from "./remoteForS3";
import * as webdav from "./remoteForWebdav";
import * as dropbox from "./remoteForDropbox";
export class RemoteClient {
readonly serviceType: SUPPORTED_SERVICES_TYPE;
readonly s3Client?: s3.S3Client;
readonly s3Config?: s3.S3Config;
readonly webdavClient?: webdav.WebDAVClient;
readonly webdavConfig?: webdav.WebdavConfig;
readonly s3Config?: S3Config;
readonly webdavClient?: webdav.WrappedWebdavClient;
readonly webdavConfig?: WebdavConfig;
readonly dropboxClient?: dropbox.WrappedDropboxClient;
readonly dropboxConfig?: DropboxConfig;
constructor(
serviceType: SUPPORTED_SERVICES_TYPE,
s3Config?: s3.S3Config,
webdavConfig?: webdav.WebdavConfig
s3Config?: S3Config,
webdavConfig?: WebdavConfig,
dropboxConfig?: DropboxConfig,
vaultName?: string,
saveUpdatedConfigFunc?: () => Promise<any>
) {
this.serviceType = serviceType;
// the client may modify the config inplace,
// so we use a ref not copy of config here
if (serviceType === "s3") {
this.s3Config = s3Config;
this.s3Client = s3.getS3Client(s3Config);
this.s3Client = s3.getS3Client(this.s3Config);
} else if (serviceType === "webdav") {
if (vaultName === undefined) {
throw Error("remember to provide vault name while init webdav client");
}
this.webdavConfig = webdavConfig;
this.webdavClient = webdav.getWebdavClient(webdavConfig);
this.webdavClient = webdav.getWebdavClient(this.webdavConfig, vaultName);
} else if (serviceType === "dropbox") {
if (vaultName === undefined || saveUpdatedConfigFunc === undefined) {
throw Error(
"remember to provide vault name and callback while init dropbox client"
);
}
this.dropboxConfig = dropboxConfig;
this.dropboxClient = dropbox.getDropboxClient(
this.dropboxConfig,
vaultName,
saveUpdatedConfigFunc
);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
@@ -37,6 +65,8 @@ export class RemoteClient {
);
} else if (this.serviceType === "webdav") {
return await webdav.getRemoteMeta(this.webdavClient, fileOrFolderPath);
} else if (this.serviceType === "dropbox") {
return await dropbox.getRemoteMeta(this.dropboxClient, fileOrFolderPath);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
@@ -47,7 +77,8 @@ export class RemoteClient {
vault: Vault,
isRecursively: boolean = false,
password: string = "",
remoteEncryptedKey: string = ""
remoteEncryptedKey: string = "",
foldersCreatedBefore: Set<string> | undefined = undefined
) => {
if (this.serviceType === "s3") {
return await s3.uploadToRemote(
@@ -68,6 +99,16 @@ export class RemoteClient {
password,
remoteEncryptedKey
);
} else if (this.serviceType === "dropbox") {
return await dropbox.uploadToRemote(
this.dropboxClient,
fileOrFolderPath,
vault,
isRecursively,
password,
remoteEncryptedKey,
foldersCreatedBefore
);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
@@ -78,6 +119,8 @@ export class RemoteClient {
return await s3.listFromRemote(this.s3Client, this.s3Config, prefix);
} else if (this.serviceType === "webdav") {
return await webdav.listFromRemote(this.webdavClient, prefix);
} else if (this.serviceType === "dropbox") {
return await dropbox.listFromRemote(this.dropboxClient, prefix);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
@@ -109,6 +152,15 @@ export class RemoteClient {
password,
remoteEncryptedKey
);
} else if (this.serviceType === "dropbox") {
return await dropbox.downloadFromRemote(
this.dropboxClient,
fileOrFolderPath,
vault,
mtime,
password,
remoteEncryptedKey
);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
@@ -134,6 +186,13 @@ export class RemoteClient {
password,
remoteEncryptedKey
);
} else if (this.serviceType === "dropbox") {
return await dropbox.deleteFromRemote(
this.dropboxClient,
fileOrFolderPath,
password,
remoteEncryptedKey
);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
@@ -144,6 +203,24 @@ export class RemoteClient {
return await s3.checkConnectivity(this.s3Client, this.s3Config);
} else if (this.serviceType === "webdav") {
return await webdav.checkConnectivity(this.webdavClient);
} else if (this.serviceType === "dropbox") {
return await dropbox.checkConnectivity(this.dropboxClient);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
};
getUser = async () => {
if (this.serviceType === "dropbox") {
return await dropbox.getUserDisplayName(this.dropboxClient);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
};
revokeAuth = async () => {
if (this.serviceType === "dropbox") {
return await dropbox.revokeAuth(this.dropboxClient);
} else {
throw Error(`not supported service type ${this.serviceType}`);
}
+627
View File
@@ -0,0 +1,627 @@
import * as path from "path";
import { FileStats, Vault } from "obsidian";
import { Dropbox, DropboxAuth, DropboxResponse, files } from "dropbox";
export { Dropbox } from "dropbox";
import { RemoteItem, DropboxConfig } from "./baseTypes";
import {
arrayBufferToBuffer,
bufferToArrayBuffer,
mkdirpInVault,
getPathFolder,
getFolderLevels,
setToString,
} from "./misc";
import { decryptArrayBuffer, encryptArrayBuffer } from "./encrypt";
export const DEFAULT_DROPBOX_CONFIG = {
accessToken: "",
clientID: process.env.DEFAULT_DROPBOX_APP_KEY,
refreshToken: "",
accessTokenExpiresInSeconds: 0,
accessTokenExpiresAtTime: 0,
accountID: "",
username: "",
};
export const getDropboxPath = (fileOrFolderPath: string, vaultName: string) => {
let key = fileOrFolderPath;
if (fileOrFolderPath === "/" || fileOrFolderPath === "") {
// special
key = `/${vaultName}`;
}
if (!fileOrFolderPath.startsWith("/")) {
// then this is original path in Obsidian
key = `/${vaultName}/${fileOrFolderPath}`;
}
if (key.endsWith("/")) {
key = key.slice(0, key.length - 1);
}
return key;
};
const getNormPath = (fileOrFolderPath: string, vaultName: string) => {
if (
!(
fileOrFolderPath === `/${vaultName}` ||
fileOrFolderPath.startsWith(`/${vaultName}/`)
)
) {
throw Error(`"${fileOrFolderPath}" doesn't starts with "/${vaultName}/"`);
}
return fileOrFolderPath.slice(`/${vaultName}/`.length);
};
const fromDropboxItemToRemoteItem = (
x:
| files.FileMetadataReference
| files.FolderMetadataReference
| files.DeletedMetadataReference,
vaultName: string
): RemoteItem => {
let key = getNormPath(x.path_display, vaultName);
if (x[".tag"] === "folder" && !key.endsWith("/")) {
key = `${key}/`;
}
if (x[".tag"] === "folder") {
return {
key: key,
lastModified: undefined,
size: 0,
remoteType: "dropbox",
etag: `${x.id}\t`,
} as RemoteItem;
} else if (x[".tag"] === "file") {
return {
key: key,
lastModified: Date.parse(x.server_modified).valueOf(),
size: x.size,
remoteType: "dropbox",
etag: `${x.id}\t${x.content_hash}`,
} as RemoteItem;
} else if (x[".tag"] === "deleted") {
throw Error("do not support deleted tag");
}
};
/**
* Dropbox api doesn't return mtime for folders.
* This is a try to assign mtime by using files in folder.
* @param allFilesFolders
* @returns
*/
const fixLastModifiedTimeInplace = (allFilesFolders: RemoteItem[]) => {
if (allFilesFolders.length === 0) {
return;
}
// sort by longer to shorter
allFilesFolders.sort((a, b) => b.key.length - a.key.length);
// a "map" from dir to mtime
let potentialMTime = {} as Record<string, number>;
// first sort pass, from buttom to up
for (const item of allFilesFolders) {
if (item.key.endsWith("/")) {
// itself is a folder, and initially doesn't have mtime
if (item.lastModified === undefined && item.key in potentialMTime) {
// previously we gathered all sub info of this folder
item.lastModified = potentialMTime[item.key];
}
}
const parent = `${path.posix.dirname(item.key)}/`;
if (item.lastModified !== undefined) {
if (parent in potentialMTime) {
potentialMTime[parent] = Math.max(
potentialMTime[parent],
item.lastModified
);
} else {
potentialMTime[parent] = item.lastModified;
}
}
}
// second pass, from up to buttom.
// fill mtime by parent folder or Date.Now() if still not available.
// this is only possible if no any sub-folder-files recursively.
// we do not sort the array again, just iterate over it by reverse
// using good old for loop.
for (let i = allFilesFolders.length - 1; i >= 0; --i) {
const item = allFilesFolders[i];
if (!item.key.endsWith("/")) {
continue; // skip files
}
if (item.lastModified !== undefined) {
continue; // don't need to deal with it
}
const parent = `${path.posix.dirname(item.key)}/`;
if (parent in potentialMTime) {
item.lastModified = potentialMTime[parent];
} else {
item.lastModified = Date.now().valueOf();
potentialMTime[item.key] = item.lastModified;
}
}
return allFilesFolders;
};
////////////////////////////////////////////////////////////////////////////////
// Dropbox authorization using PKCE
// see https://dropbox.tech/developers/pkce--what-and-why-
////////////////////////////////////////////////////////////////////////////////
export const getAuthUrlAndVerifier = async (appKey: string) => {
const auth = new DropboxAuth({
clientId: appKey,
});
const authUrl = (
await auth.getAuthenticationUrl(
undefined,
undefined,
"code",
"offline",
undefined,
"none",
true
)
).toString();
const verifier = auth.getCodeVerifier();
return {
authUrl: authUrl,
verifier: verifier,
};
};
export interface DropboxSuccessAuthRes {
access_token: string;
token_type: "bearer";
expires_in: string;
refresh_token?: string;
scope?: string;
uid?: string;
account_id?: string;
}
export const sendAuthReq = async (
appKey: string,
verifier: string,
authCode: string
) => {
const resp1 = await fetch("https://api.dropboxapi.com/oauth2/token", {
method: "POST",
body: new URLSearchParams({
code: authCode,
grant_type: "authorization_code",
code_verifier: verifier,
client_id: appKey,
}),
});
const resp2 = (await resp1.json()) as DropboxSuccessAuthRes;
return resp2;
};
export const sendRefreshTokenReq = async (
appKey: string,
refreshToken: string
) => {
console.log("start auto getting refreshed Dropbox access token.");
const resp1 = await fetch("https://api.dropboxapi.com/oauth2/token", {
method: "POST",
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
client_id: appKey,
}),
});
const resp2 = (await resp1.json()) as DropboxSuccessAuthRes;
console.log("finish auto getting refreshed Dropbox access token.");
return resp2;
};
export const setConfigBySuccessfullAuthInplace = async (
config: DropboxConfig,
authRes: DropboxSuccessAuthRes,
saveUpdatedConfigFunc: () => Promise<any> | undefined
) => {
console.log("start updating local info of Dropbox token");
config.accessToken = authRes.access_token;
config.accessTokenExpiresInSeconds = parseInt(authRes.expires_in);
config.accessTokenExpiresAtTime =
Date.now() + parseInt(authRes.expires_in) * 1000 - 10 * 1000;
if (authRes.refresh_token !== undefined) {
config.refreshToken = authRes.refresh_token;
}
if (authRes.refresh_token !== undefined) {
config.accountID = authRes.account_id;
}
if (saveUpdatedConfigFunc !== undefined) {
await saveUpdatedConfigFunc();
}
console.log("finish updating local info of Dropbox token");
};
////////////////////////////////////////////////////////////////////////////////
// Other usual common methods
////////////////////////////////////////////////////////////////////////////////
export class WrappedDropboxClient {
dropboxConfig: DropboxConfig;
vaultName: string;
saveUpdatedConfigFunc: () => Promise<any>;
dropbox: Dropbox;
vaultFolderExists: boolean;
constructor(
dropboxConfig: DropboxConfig,
vaultName: string,
saveUpdatedConfigFunc: () => Promise<any>
) {
this.dropboxConfig = dropboxConfig;
this.vaultName = vaultName;
this.saveUpdatedConfigFunc = saveUpdatedConfigFunc;
this.vaultFolderExists = false;
}
init = async () => {
// check token
if (
this.dropboxConfig.accessToken === "" ||
this.dropboxConfig.refreshToken === ""
) {
throw Error("The user has not manually auth yet.");
}
const currentTs = Date.now();
if (this.dropboxConfig.accessTokenExpiresAtTime > currentTs) {
this.dropbox = new Dropbox({
accessToken: this.dropboxConfig.accessToken,
});
} else {
if (this.dropboxConfig.refreshToken === "") {
throw Error(
"We need to automatically refresh token but none is stored."
);
}
const resp = await sendRefreshTokenReq(
this.dropboxConfig.clientID,
this.dropboxConfig.refreshToken
);
setConfigBySuccessfullAuthInplace(
this.dropboxConfig,
resp,
this.saveUpdatedConfigFunc
);
this.dropbox = new Dropbox({
accessToken: this.dropboxConfig.accessToken,
});
}
// check vault folder
// console.log(`checking remote has folder /${this.vaultName}`);
if (this.vaultFolderExists) {
// console.log(`already checked, /${this.vaultName} exist before`)
} else {
const res = await this.dropbox.filesListFolder({
path: "",
recursive: false,
});
for (const item of res.result.entries) {
if (item.path_display === `/${this.vaultName}`) {
this.vaultFolderExists = true;
break;
}
}
if (!this.vaultFolderExists) {
console.log(`remote does not have folder /${this.vaultName}`);
await this.dropbox.filesCreateFolderV2({
path: `/${this.vaultName}`,
});
console.log(`remote folder /${this.vaultName} created`);
this.vaultFolderExists = true;
} else {
// console.log(`remote folder /${this.vaultName} exists`);
}
}
return this.dropbox;
};
}
/**
* @param dropboxConfig
* @returns
*/
export const getDropboxClient = (
dropboxConfig: DropboxConfig,
vaultName: string,
saveUpdatedConfigFunc: () => Promise<any>
) => {
return new WrappedDropboxClient(
dropboxConfig,
vaultName,
saveUpdatedConfigFunc
);
};
export const getRemoteMeta = async (
client: WrappedDropboxClient,
fileOrFolderPath: string
) => {
await client.init();
if (fileOrFolderPath === "" || fileOrFolderPath === "/") {
// filesGetMetadata doesn't support root folder
// we instead try to list files
// if no error occurs, we ensemble a fake result.
const rsp = await client.dropbox.filesListFolder({
path: `/${client.vaultName}`,
recursive: false, // don't need to recursive here
});
if (rsp.status !== 200) {
throw Error(JSON.stringify(rsp));
}
return {
key: fileOrFolderPath,
lastModified: undefined,
size: 0,
remoteType: "dropbox",
etag: undefined,
} as RemoteItem;
}
const key = getDropboxPath(fileOrFolderPath, client.vaultName);
const rsp = await client.dropbox.filesGetMetadata({
path: key,
});
if (rsp.status !== 200) {
throw Error(JSON.stringify(rsp));
}
return fromDropboxItemToRemoteItem(rsp.result, client.vaultName);
};
export const uploadToRemote = async (
client: WrappedDropboxClient,
fileOrFolderPath: string,
vault: Vault,
isRecursively: boolean = false,
password: string = "",
remoteEncryptedKey: string = "",
foldersCreatedBefore: Set<string> | undefined = undefined
) => {
await client.init();
let uploadFile = fileOrFolderPath;
if (password !== "") {
uploadFile = remoteEncryptedKey;
}
uploadFile = getDropboxPath(uploadFile, client.vaultName);
const isFolder = fileOrFolderPath.endsWith("/");
if (isFolder && isRecursively) {
throw Error("upload function doesn't implement recursive function yet!");
} else if (isFolder && !isRecursively) {
// folder
if (password === "") {
// if not encrypted, mkdir a remote folder
if (foldersCreatedBefore?.has(uploadFile)) {
// created, pass
} else {
try {
await client.dropbox.filesCreateFolderV2({
path: uploadFile,
});
foldersCreatedBefore?.add(uploadFile);
} catch (err) {
if (err.status === 409) {
// pass
foldersCreatedBefore?.add(uploadFile);
} else {
throw err;
}
}
}
const res = await getRemoteMeta(client, uploadFile);
return res;
} else {
// if encrypted, upload a fake file with the encrypted file name
await client.dropbox.filesUpload({
path: uploadFile,
contents: "",
});
return await getRemoteMeta(client, uploadFile);
}
} else {
// file
// we ignore isRecursively parameter here
const localContent = await vault.adapter.readBinary(fileOrFolderPath);
let remoteContent = localContent;
if (password !== "") {
remoteContent = await encryptArrayBuffer(localContent, password);
}
// in dropbox, we don't need to create folders before uploading! cool!
// TODO: filesUploadSession for larger files (>=150 MB)
await client.dropbox.filesUpload({
path: uploadFile,
contents: remoteContent,
mode: {
".tag": "overwrite",
},
});
// we want to mark that parent folders are created
if (foldersCreatedBefore !== undefined) {
const dirs = getFolderLevels(uploadFile).map((x) =>
getDropboxPath(x, client.vaultName)
);
for (const dir of dirs) {
foldersCreatedBefore?.add(dir);
}
}
return await getRemoteMeta(client, uploadFile);
}
};
export const listFromRemote = async (
client: WrappedDropboxClient,
prefix?: string
) => {
if (prefix !== undefined) {
throw Error("prefix not supported (yet)");
}
await client.init();
let res = await client.dropbox.filesListFolder({
path: `/${client.vaultName}`,
recursive: true,
include_deleted: false,
limit: 1000,
});
if (res.status !== 200) {
throw Error(JSON.stringify(res));
}
// console.log(res);
const contents = res.result.entries;
const unifiedContents = contents
.filter((x) => x[".tag"] !== "deleted")
.filter((x) => x.path_display !== `/${client.vaultName}`)
.map((x) => fromDropboxItemToRemoteItem(x, client.vaultName));
while (res.result.has_more) {
res = await client.dropbox.filesListFolderContinue({
cursor: res.result.cursor,
});
if (res.status !== 200) {
throw Error(JSON.stringify(res));
}
const contents2 = res.result.entries;
const unifiedContents2 = contents2
.filter((x) => x[".tag"] !== "deleted")
.filter((x) => x.path_display !== `/${client.vaultName}`)
.map((x) => fromDropboxItemToRemoteItem(x, client.vaultName));
unifiedContents.push(...unifiedContents2);
}
fixLastModifiedTimeInplace(unifiedContents);
return {
Contents: unifiedContents,
};
};
const downloadFromRemoteRaw = async (
client: WrappedDropboxClient,
fileOrFolderPath: string
) => {
await client.init();
const key = getDropboxPath(fileOrFolderPath, client.vaultName);
const rsp = await client.dropbox.filesDownload({
path: key,
});
if ((rsp.result as any).fileBlob !== undefined) {
// we get a Blob
const content = (rsp.result as any).fileBlob as Blob;
return await content.arrayBuffer();
} else if ((rsp.result as any).fileBinary !== undefined) {
// we get a Buffer
const content = (rsp.result as any).fileBinary as Buffer;
return bufferToArrayBuffer(content);
} else {
throw Error(`unknown rsp from dropbox download: ${rsp}`);
}
};
export const downloadFromRemote = async (
client: WrappedDropboxClient,
fileOrFolderPath: string,
vault: Vault,
mtime: number,
password: string = "",
remoteEncryptedKey: string = ""
) => {
await client.init();
const isFolder = fileOrFolderPath.endsWith("/");
await mkdirpInVault(fileOrFolderPath, vault);
// the file is always local file
// we need to encrypt it
if (isFolder) {
// mkdirp locally is enough
// do nothing here
} else {
let downloadFile = fileOrFolderPath;
if (password !== "") {
downloadFile = remoteEncryptedKey;
}
downloadFile = getDropboxPath(downloadFile, client.vaultName);
const remoteContent = await downloadFromRemoteRaw(client, downloadFile);
let localContent = remoteContent;
if (password !== "") {
localContent = await decryptArrayBuffer(remoteContent, password);
}
await vault.adapter.writeBinary(fileOrFolderPath, localContent, {
mtime: mtime,
});
}
};
export const deleteFromRemote = async (
client: WrappedDropboxClient,
fileOrFolderPath: string,
password: string = "",
remoteEncryptedKey: string = ""
) => {
if (fileOrFolderPath === "/") {
return;
}
let remoteFileName = fileOrFolderPath;
if (password !== "") {
remoteFileName = remoteEncryptedKey;
}
remoteFileName = getDropboxPath(remoteFileName, client.vaultName);
await client.init();
try {
await client.dropbox.filesDeleteV2({
path: remoteFileName,
});
} catch (err) {
console.error("some error while deleting");
console.error(err);
}
};
export const checkConnectivity = async (client: WrappedDropboxClient) => {
try {
const results = await getRemoteMeta(client, "/");
if (results === undefined) {
return false;
}
return true;
} catch (err) {
console.error("dropbox connectivity error:");
console.error(err);
return false;
}
};
export const getUserDisplayName = async (client: WrappedDropboxClient) => {
await client.init();
const acct = await client.dropbox.usersGetCurrentAccount();
return acct.result.name.display_name;
};
export const revokeAuth = async (client: WrappedDropboxClient) => {
await client.init();
await client.dropbox.authTokenRevoke();
};
+7 -15
View File
@@ -27,17 +27,9 @@ import {
} from "./misc";
import * as mime from "mime-types";
import { RemoteItem } from "./baseTypes";
import { RemoteItem, S3Config } from "./baseTypes";
import { decryptArrayBuffer, encryptArrayBuffer } from "./encrypt";
export interface S3Config {
s3Endpoint: string;
s3Region: string;
s3AccessKeyID: string;
s3SecretAccessKey: string;
s3BucketName: string;
}
export const DEFAULT_S3_CONFIG = {
s3Endpoint: "",
s3Region: "",
@@ -225,12 +217,12 @@ const getObjectBodyToArrayBuffer = async (
b: Readable | ReadableStream | Blob
) => {
if (b instanceof Readable) {
const chunks: Uint8Array[] = [];
for await (let chunk of b) {
chunks.push(chunk);
}
const buf = Buffer.concat(chunks);
return bufferToArrayBuffer(buf);
return (await new Promise((resolve, reject) => {
const chunks: Uint8Array[] = [];
b.on("data", (chunk) => chunks.push(chunk));
b.on("error", reject);
b.on("end", () => resolve(bufferToArrayBuffer(Buffer.concat(chunks))));
})) as ArrayBuffer;
} else if (b instanceof ReadableStream) {
return await new Response(b, {}).arrayBuffer();
} else if (b instanceof Blob) {
+123 -59
View File
@@ -4,7 +4,7 @@ import { AuthType, BufferLike, createClient } from "webdav/web";
import type { WebDAVClient, ResponseDataDetailed, FileStat } from "webdav/web";
export type { WebDAVClient } from "webdav/web";
import type { RemoteItem } from "./baseTypes";
import type { RemoteItem, WebdavAuthType, WebdavConfig } from "./baseTypes";
import {
arrayBufferToBuffer,
@@ -14,15 +14,6 @@ import {
} from "./misc";
import { decryptArrayBuffer, encryptArrayBuffer } from "./encrypt";
export type WebdavAuthType = "digest" | "basic";
export interface WebdavConfig {
address: string;
username: string;
password: string;
authType: WebdavAuthType;
}
export const DEFAULT_WEBDAV_CONFIG = {
address: "",
username: "",
@@ -30,22 +21,35 @@ export const DEFAULT_WEBDAV_CONFIG = {
authType: "basic",
} as WebdavConfig;
const getWebdavPath = (fileOrFolderPath: string) => {
const getWebdavPath = (fileOrFolderPath: string, vaultName: string) => {
let key = fileOrFolderPath;
if (fileOrFolderPath === "/" || fileOrFolderPath === "") {
// special
key = `/${vaultName}/`;
}
if (!fileOrFolderPath.startsWith("/")) {
return `/${fileOrFolderPath}`;
key = `/${vaultName}/${fileOrFolderPath}`;
}
return fileOrFolderPath;
return key;
};
const getNormPath = (fileOrFolderPath: string) => {
if (fileOrFolderPath.startsWith("/")) {
return fileOrFolderPath.slice(1);
const getNormPath = (fileOrFolderPath: string, vaultName: string) => {
if (
!(
fileOrFolderPath === `/${vaultName}` ||
fileOrFolderPath.startsWith(`/${vaultName}/`)
)
) {
throw Error(`"${fileOrFolderPath}" doesn't starts with "/${vaultName}/"`);
}
return fileOrFolderPath;
// if (fileOrFolderPath.startsWith("/")) {
// return fileOrFolderPath.slice(1);
// }
return fileOrFolderPath.slice(`/${vaultName}/`.length);
};
const fromWebdavItemToRemoteItem = (x: FileStat) => {
let key = getNormPath(x.filename);
const fromWebdavItemToRemoteItem = (x: FileStat, vaultName: string) => {
let key = getNormPath(x.filename, vaultName);
if (x.type === "directory" && !key.endsWith("/")) {
key = `${key}/`;
}
@@ -58,45 +62,90 @@ const fromWebdavItemToRemoteItem = (x: FileStat) => {
} as RemoteItem;
};
export const getWebdavClient = (webdavConfig: WebdavConfig) => {
if (webdavConfig.username !== "" && webdavConfig.password !== "") {
return createClient(webdavConfig.address, {
username: webdavConfig.username,
password: webdavConfig.password,
authType:
webdavConfig.authType === "digest"
? AuthType.Digest
: AuthType.Password,
});
} else {
console.log("no password");
return createClient(webdavConfig.address);
export class WrappedWebdavClient {
webdavConfig: WebdavConfig;
vaultName: string;
client: WebDAVClient;
vaultFolderExists: boolean;
constructor(webdavConfig: WebdavConfig, vaultName: string) {
this.webdavConfig = webdavConfig;
this.vaultName = vaultName;
this.vaultFolderExists = false;
}
init = async () => {
// init client if not inited
if (this.client === undefined) {
if (
this.webdavConfig.username !== "" &&
this.webdavConfig.password !== ""
) {
this.client = createClient(this.webdavConfig.address, {
username: this.webdavConfig.username,
password: this.webdavConfig.password,
authType:
this.webdavConfig.authType === "digest"
? AuthType.Digest
: AuthType.Password,
});
} else {
console.log("no password");
this.client = createClient(this.webdavConfig.address);
}
}
// check vault folder
if (this.vaultFolderExists) {
// pass
} else {
const res = await this.client.exists(`/${this.vaultName}`);
if (res) {
// console.log("remote vault folder exits!");
this.vaultFolderExists = true;
} else {
console.log("remote vault folder not exists, creating");
await this.client.createDirectory(`/${this.vaultName}`);
console.log("remote vault folder created!");
this.vaultFolderExists = true;
}
}
};
}
export const getWebdavClient = (
webdavConfig: WebdavConfig,
vaultName: string
) => {
return new WrappedWebdavClient(webdavConfig, vaultName);
};
export const getRemoteMeta = async (
client: WebDAVClient,
client: WrappedWebdavClient,
fileOrFolderPath: string
) => {
const res = (await client.stat(getWebdavPath(fileOrFolderPath), {
await client.init();
const remotePath = getWebdavPath(fileOrFolderPath, client.vaultName);
// console.log(`remotePath = ${remotePath}`);
const res = (await client.client.stat(remotePath, {
details: false,
})) as FileStat;
return fromWebdavItemToRemoteItem(res);
return fromWebdavItemToRemoteItem(res, client.vaultName);
};
export const uploadToRemote = async (
client: WebDAVClient,
client: WrappedWebdavClient,
fileOrFolderPath: string,
vault: Vault,
isRecursively: boolean = false,
password: string = "",
remoteEncryptedKey: string = ""
) => {
await client.init();
let uploadFile = fileOrFolderPath;
if (password !== "") {
uploadFile = remoteEncryptedKey;
}
uploadFile = getWebdavPath(uploadFile);
uploadFile = getWebdavPath(uploadFile, client.vaultName);
const isFolder = fileOrFolderPath.endsWith("/");
@@ -106,17 +155,17 @@ export const uploadToRemote = async (
// folder
if (password === "") {
// if not encrypted, mkdir a remote folder
await client.createDirectory(uploadFile, {
await client.client.createDirectory(uploadFile, {
recursive: true,
});
const res = await getRemoteMeta(client, uploadFile);
return res;
} else {
// if encrypted, upload a fake file with the encrypted file name
await client.putFileContents(uploadFile, "", {
await client.client.putFileContents(uploadFile, "", {
overwrite: true,
onUploadProgress: (progress) => {
console.log(`Uploaded ${progress.loaded} bytes of ${progress.total}`);
// console.log(`Uploaded ${progress.loaded} bytes of ${progress.total}`);
},
});
@@ -133,9 +182,9 @@ export const uploadToRemote = async (
// we need to create folders before uploading
const dir = getPathFolder(uploadFile);
if (dir !== "/" && dir !== "") {
await client.createDirectory(dir, { recursive: true });
await client.client.createDirectory(dir, { recursive: true });
}
await client.putFileContents(uploadFile, remoteContent, {
await client.client.putFileContents(uploadFile, remoteContent, {
overwrite: true,
onUploadProgress: (progress) => {
console.log(`Uploaded ${progress.loaded} bytes of ${progress.total}`);
@@ -146,26 +195,36 @@ export const uploadToRemote = async (
}
};
export const listFromRemote = async (client: WebDAVClient, prefix?: string) => {
export const listFromRemote = async (
client: WrappedWebdavClient,
prefix?: string
) => {
if (prefix !== undefined) {
throw Error("prefix not supported");
}
const contents = (await client.getDirectoryContents("/", {
deep: true,
details: false /* no need for verbose details here */,
glob: "/**" /* avoid dot files by using glob */,
})) as FileStat[];
await client.init();
const contents = (await client.client.getDirectoryContents(
`/${client.vaultName}`,
{
deep: true,
details: false /* no need for verbose details here */,
glob: "/**" /* avoid dot files by using glob */,
}
)) as FileStat[];
return {
Contents: contents.map((x) => fromWebdavItemToRemoteItem(x)),
Contents: contents.map((x) =>
fromWebdavItemToRemoteItem(x, client.vaultName)
),
};
};
const downloadFromRemoteRaw = async (
client: WebDAVClient,
client: WrappedWebdavClient,
fileOrFolderPath: string
) => {
const buff = (await client.getFileContents(
getWebdavPath(fileOrFolderPath)
await client.init();
const buff = (await client.client.getFileContents(
getWebdavPath(fileOrFolderPath, client.vaultName)
)) as BufferLike;
if (buff instanceof ArrayBuffer) {
return buff;
@@ -176,13 +235,15 @@ const downloadFromRemoteRaw = async (
};
export const downloadFromRemote = async (
client: WebDAVClient,
client: WrappedWebdavClient,
fileOrFolderPath: string,
vault: Vault,
mtime: number,
password: string = "",
remoteEncryptedKey: string = ""
) => {
await client.init();
const isFolder = fileOrFolderPath.endsWith("/");
await mkdirpInVault(fileOrFolderPath, vault);
@@ -198,7 +259,7 @@ export const downloadFromRemote = async (
if (password !== "") {
downloadFile = remoteEncryptedKey;
}
downloadFile = getWebdavPath(downloadFile);
downloadFile = getWebdavPath(downloadFile, client.vaultName);
const remoteContent = await downloadFromRemoteRaw(client, downloadFile);
let localContent = remoteContent;
if (password !== "") {
@@ -211,7 +272,7 @@ export const downloadFromRemote = async (
};
export const deleteFromRemote = async (
client: WebDAVClient,
client: WrappedWebdavClient,
fileOrFolderPath: string,
password: string = "",
remoteEncryptedKey: string = ""
@@ -223,17 +284,20 @@ export const deleteFromRemote = async (
if (password !== "") {
remoteFileName = remoteEncryptedKey;
}
remoteFileName = getWebdavPath(remoteFileName);
remoteFileName = getWebdavPath(remoteFileName, client.vaultName);
await client.init();
try {
await client.deleteFile(remoteFileName);
console.log(`delete ${remoteFileName} succeeded`);
await client.client.deleteFile(remoteFileName);
// console.log(`delete ${remoteFileName} succeeded`);
} catch (err) {
console.error("some error while deleting");
console.log(err);
}
};
export const checkConnectivity = async (client: WebDAVClient) => {
export const checkConnectivity = async (client: WrappedWebdavClient) => {
await client.init();
try {
const results = await getRemoteMeta(client, "/");
if (results === undefined) {
+39 -19
View File
@@ -9,7 +9,7 @@ import type { FileFolderHistoryRecord, InternalDBs } from "./localdb";
import { RemoteClient } from "./remote";
import type { SUPPORTED_SERVICES_TYPE, RemoteItem } from "./baseTypes";
import { mkdirpInVault, isHiddenPath, isVaildText } from "./misc";
import { mkdirpInVault, isHiddenPath, isVaildText, setToString } from "./misc";
import {
decryptBase32ToString,
encryptStringToBase32,
@@ -389,7 +389,7 @@ const getOperation = (
}
if (r.decision === "unknown") {
throw Error(`unknown decision for ${r}`);
throw Error(`unknown decision for ${JSON.stringify(r)}`);
}
return r;
@@ -428,7 +428,8 @@ const dispatchOperationToActual = async (
client: RemoteClient,
db: InternalDBs,
vault: Vault,
password: string = ""
password: string = "",
foldersCreatedBefore: Set<string> | undefined = undefined
) => {
let remoteEncryptedKey = key;
if (password !== "") {
@@ -461,7 +462,8 @@ const dispatchOperationToActual = async (
vault,
false,
password,
remoteEncryptedKey
remoteEncryptedKey,
foldersCreatedBefore
);
await upsertSyncMetaMappingData(
client.serviceType,
@@ -493,7 +495,8 @@ const dispatchOperationToActual = async (
vault,
false,
password,
remoteEncryptedKey
remoteEncryptedKey,
foldersCreatedBefore
);
await upsertSyncMetaMappingData(
client.serviceType,
@@ -521,18 +524,35 @@ export const doActualSync = async (
password: string = ""
) => {
const keyStates = syncPlan.mixedStates;
await Promise.all(
Object.entries(keyStates)
.sort((k, v) => -(k as string).length)
.map(async ([k, v]) =>
dispatchOperationToActual(
k as string,
v as FileOrFolderMixedState,
client,
db,
vault,
password
)
)
);
const foldersCreatedBefore = new Set<string>();
for (const [k, v] of Object.entries(keyStates).sort(
([k1, v1], [k2, v2]) => k2.length - k1.length
)) {
const k2 = k as string;
const v2 = v as FileOrFolderMixedState;
await dispatchOperationToActual(
k as string,
v as FileOrFolderMixedState,
client,
db,
vault,
password,
foldersCreatedBefore
);
// console.log(`finished ${k}, with ${setToString(foldersCreatedBefore)}`);
}
// await Promise.all(
// Object.entries(keyStates)
// .map(async ([k, v]) =>
// dispatchOperationToActual(
// k as string,
// v as FileOrFolderMixedState,
// client,
// db,
// vault,
// password,
// foldersCreatedBefore
// )
// )
// );
};
+25 -2
View File
@@ -1,6 +1,10 @@
/* set the styles */
.password_second_confirm {
.password-second-confirm {
font-weight: bold;
}
.password-disclaimer {
font-weight: bold;
}
@@ -11,10 +15,29 @@
display: none;
}
.dropbox-disclaimer {
font-weight: bold;
}
.dropbox-hide {
display: none;
}
.dropbox-auth-button-hide {
display: none;
}
.dropbox-revoke-auth-button-hide {
display: none;
}
.webdav-disclaimer {
font-weight: bold;
}
.webdav-hide {
display: none;
}
.qrcode-img {
width: 350px;
height: 350px;
}
+37
View File
@@ -1,6 +1,7 @@
import * as fs from "fs";
import * as path from "path";
import { expect } from "chai";
import { JSDOM } from "jsdom";
import * as misc from "../src/misc";
@@ -69,6 +70,28 @@ describe("Misc: get folder levels", () => {
const res3 = ["xxx", "xxx/yyy", "xxx/yyy/zzz"];
expect(misc.getFolderLevels(item3)).to.deep.equal(res3);
});
it("should treat path starting with / correctly", () => {
const item = "/xxx/yyy/zzz.md";
const res = ["/xxx", "/xxx/yyy"];
expect(misc.getFolderLevels(item)).to.deep.equal(res);
const item2 = "/xxx/yyy/zzz";
const res2 = ["/xxx", "/xxx/yyy"];
expect(misc.getFolderLevels(item2)).to.deep.equal(res2);
const item3 = "/xxx/yyy/zzz/";
const res3 = ["/xxx", "/xxx/yyy", "/xxx/yyy/zzz"];
expect(misc.getFolderLevels(item3)).to.deep.equal(res3);
const item4 = "/xxx";
const res4 = [] as string[];
expect(misc.getFolderLevels(item4)).to.deep.equal(res4);
const item5 = "/";
const res5 = [] as string[];
expect(misc.getFolderLevels(item5)).to.deep.equal(res5);
});
});
describe("Misc: vaild file name tests", () => {
@@ -111,3 +134,17 @@ describe("Misc: get dirname", () => {
expect(y).to.equal("/");
});
});
describe("Misc: extract svg", () => {
beforeEach(function () {
const fakeBrowser = new JSDOM("");
global.window = fakeBrowser.window as any;
});
it("should extract rect from svg correctly", () => {
const x = "<svg><rect/><g/></svg>";
const y = misc.extractSvgSub(x);
// console.log(x)
expect(y).to.equal("<rect/><g/>");
});
});
+1
View File
@@ -11,6 +11,7 @@
// "allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"importHelpers": true,
"isolatedModules": true,
"lib": ["dom", "es5", "scripthost", "es2015"]
},
"include": ["**/*.ts"]
+1 -1
View File
@@ -1,3 +1,3 @@
{
"0.1.6": "0.12.15"
"0.2.5": "0.12.15"
}
+11
View File
@@ -1,7 +1,10 @@
require("dotenv").config();
const path = require("path");
const webpack = require("webpack");
const TerserPlugin = require("terser-webpack-plugin");
const DEFAULT_DROPBOX_APP_KEY = process.env.DROPBOX_APP_KEY || "";
module.exports = {
entry: "./src/main.ts",
target: "web",
@@ -11,6 +14,9 @@ module.exports = {
libraryTarget: "commonjs",
},
plugins: [
new webpack.DefinePlugin({
"process.env.DEFAULT_DROPBOX_APP_KEY": `"${DEFAULT_DROPBOX_APP_KEY}"`,
}),
// Work around for Buffer is undefined:
// https://github.com/webpack/changelog-v5/issues/10
new webpack.ProvidePlugin({
@@ -27,6 +33,10 @@ module.exports = {
use: "ts-loader",
exclude: /node_modules/,
},
{
test: /\.svg?$/,
type: "asset/source",
},
],
},
resolve: {
@@ -38,6 +48,7 @@ module.exports = {
// console: require.resolve("console-browserify"),
// constants: require.resolve("constants-browserify"),
// crypto: require.resolve("crypto-browserify"),
crypto: false,
// domain: require.resolve("domain-browser"),
// events: require.resolve("events"),
// http: require.resolve("stream-http"),