Compare commits

...
11 Commits
Author SHA1 Message Date
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
17 changed files with 258 additions and 114 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
+20 -4
View File
@@ -53,7 +53,7 @@ Additionally, the plugin author may occasionally visit Obsidian official forum a
- 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.
@@ -62,9 +62,9 @@ Additionally, the plugin author may occasionally visit Obsidian official forum a
- **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` folder.
- 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.
- Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**.
### webdav
@@ -73,4 +73,20 @@ Additionally, the plugin author may occasionally visit Obsidian official forum a
- 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.
- Password-based end-to-end encryption is also supported.
- 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
+3
View File
@@ -18,6 +18,9 @@ esbuild
banner: {
js: banner,
},
loader: {
".svg": "text",
},
entryPoints: ["./src/main.ts"],
bundle: true,
external: [
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "remotely-save",
"name": "Remotely Save",
"version": "0.2.3",
"version": "0.2.4",
"minAppVersion": "0.12.15",
"description": "Yet another unofficial plugin allowing users to synchronize notes between local device and the cloud service.",
"author": "fyears",
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "remotely-save",
"version": "0.2.3",
"version": "0.2.4",
"description": "This is yet another sync plugin for Obsidian app.",
"scripts": {
"dev": "node esbuild.config.mjs",
@@ -22,6 +22,7 @@
"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",
@@ -32,6 +33,7 @@
"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",
"ts-loader": "^9.2.6",
+55 -57
View File
@@ -60,12 +60,12 @@ const DEFAULT_SETTINGS: RemotelySavePluginSettings = {
export default class RemotelySavePlugin extends Plugin {
settings: RemotelySavePluginSettings;
cm: CodeMirror.Editor;
// cm: CodeMirror.Editor;
db: InternalDBs;
syncStatus: SyncStatusType;
async onload() {
console.log("loading plugin remotely-save");
console.log(`loading plugin ${this.manifest.id}`);
await this.loadSettings();
@@ -215,7 +215,7 @@ export default class RemotelySavePlugin extends Plugin {
}
onunload() {
console.log("unloading plugin remotely-save");
console.log(`unloading plugin ${this.manifest.id}`);
this.destroyDBs();
}
@@ -257,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.",
@@ -285,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");
@@ -328,7 +330,7 @@ export class DropboxAuthModal extends Modal {
);
contentEl.createEl("p", {
text: "Step 1: Visit the following address in a browser, and follow the steps on the web page to authorize.",
text: "Step 1: Visit the address in a browser, and follow the steps.",
});
contentEl.createEl("p").createEl("a", {
href: authUrl,
@@ -388,7 +390,7 @@ export class DropboxAuthModal extends Modal {
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`
`You've connected as user ${this.plugin.settings.dropbox.username}. If you want to disconnect, click this button.`
);
this.close();
} catch (err) {
@@ -421,15 +423,16 @@ export class ExportSettingsQrCodeModal extends Modal {
this.plugin.manifest.version
);
contentEl.createEl("p", {
const div1 = contentEl.createDiv();
div1.createEl("p", {
text: "You can use another device to scan this qrcode.",
});
contentEl.createEl("p", {
div1.createEl("p", {
text: "Or, you can click the button to copy the special url.",
});
contentEl.createEl(
const div2 = contentEl.createDiv();
div2.createEl(
"button",
{
text: "Click to copy the special URI",
@@ -442,7 +445,8 @@ export class ExportSettingsQrCodeModal extends Modal {
}
);
contentEl.createEl(
const div3 = contentEl.createDiv();
div3.createEl(
"img",
{
cls: "qrcode-img",
@@ -507,11 +511,12 @@ class RemotelySaveSettingTab extends PluginSettingTab {
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",
});
@@ -520,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");
@@ -633,19 +638,17 @@ class RemotelySaveSettingTab extends PluginSettingTab {
);
dropboxDiv.createEl("h2", { text: "Remote For Dropbox" });
dropboxDiv.createEl("p", {
text: "Disclaimer: Sync support for Dropbox are more experimental, and s3 functions are more stable now.",
text: "Disclaimer: This app is NOT an official Dropbox product.",
cls: "dropbox-disclaimer",
});
dropboxDiv.createEl("p", {
text: "Disclaimer: This app is NOT an official Dropbox product. It just uses Dropbox open api.",
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: "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 Dropbox, please immediately disconnect this app on https://www.dropbox.com/account/connected_apps .",
cls: "dropbox-disclaimer",
});
dropboxDiv.createEl("p", {
text: "We will create a folder Apps/remotely-save on your Dropbox. All files/folders sync would happen inside this folder.",
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();
@@ -755,12 +758,7 @@ class RemotelySaveSettingTab extends PluginSettingTab {
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",
});
@@ -768,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")
@@ -809,9 +811,7 @@ 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");
@@ -834,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) {
@@ -849,13 +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;
dropdown.addOption("s3", "s3 (-compatible)");
dropdown.addOption("s3", "S3 (-compatible)");
dropdown.addOption("dropbox", "Dropbox");
dropdown.addOption("webdav", "webdav (experimental)");
dropdown.addOption("webdav", "Webdav");
dropdown
.setValue(this.plugin.settings.serviceType)
.onChange(async (val: SUPPORTED_SERVICES_TYPE) => {
@@ -882,7 +884,7 @@ class RemotelySaveSettingTab extends PluginSettingTab {
new Setting(importExportDiv)
.setName("export")
.setDesc("export all settings by generating qrcode")
.setDesc("Export all settings by generating a qrcode.")
.addButton(async (button) => {
button.setButtonText("Get QR Code");
button.onClick(async () => {
@@ -892,18 +894,18 @@ class RemotelySaveSettingTab extends PluginSettingTab {
new Setting(importExportDiv)
.setName("import")
.setDesc("You should manually open a camera app to scan the QR code");
.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 () => {
@@ -911,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")
@@ -924,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 () => {
@@ -940,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 () => {
+8
View File
@@ -155,3 +155,11 @@ export const getPathFolder = (a: string) => {
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;
};
+5 -2
View File
@@ -14,7 +14,7 @@ export class RemoteClient {
readonly serviceType: SUPPORTED_SERVICES_TYPE;
readonly s3Client?: s3.S3Client;
readonly s3Config?: S3Config;
readonly webdavClient?: webdav.WebDAVClient;
readonly webdavClient?: webdav.WrappedWebdavClient;
readonly webdavConfig?: WebdavConfig;
readonly dropboxClient?: dropbox.WrappedDropboxClient;
readonly dropboxConfig?: DropboxConfig;
@@ -34,8 +34,11 @@ export class RemoteClient {
this.s3Config = 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(this.webdavConfig);
this.webdavClient = webdav.getWebdavClient(this.webdavConfig, vaultName);
} else if (serviceType === "dropbox") {
if (vaultName === undefined || saveUpdatedConfigFunc === undefined) {
throw Error(
+7
View File
@@ -26,6 +26,10 @@ export const DEFAULT_DROPBOX_CONFIG = {
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}`;
@@ -320,6 +324,7 @@ export class WrappedDropboxClient {
path: `/${this.vaultName}`,
});
console.log(`remote folder /${this.vaultName} created`);
this.vaultFolderExists = true;
} else {
// console.log(`remote folder /${this.vaultName} exists`);
}
@@ -541,6 +546,8 @@ export const downloadFromRemote = async (
password: string = "",
remoteEncryptedKey: string = ""
) => {
await client.init();
const isFolder = fileOrFolderPath.endsWith("/");
await mkdirpInVault(fileOrFolderPath, vault);
+111 -38
View File
@@ -21,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}/`;
}
@@ -49,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,
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:
webdavConfig.authType === "digest"
this.webdavConfig.authType === "digest"
? AuthType.Digest
: AuthType.Password,
});
} else {
console.log("no password");
return createClient(webdavConfig.address);
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("exits!");
this.vaultFolderExists = true;
} else {
console.log("not exists, creating");
await this.client.createDirectory(`/${this.vaultName}`);
console.log("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("/");
@@ -97,14 +155,14 @@ 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}`);
@@ -124,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}`);
@@ -137,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("/", {
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[];
}
)) 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;
@@ -167,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);
@@ -189,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 !== "") {
@@ -202,7 +272,7 @@ export const downloadFromRemote = async (
};
export const deleteFromRemote = async (
client: WebDAVClient,
client: WrappedWebdavClient,
fileOrFolderPath: string,
password: string = "",
remoteEncryptedKey: string = ""
@@ -214,9 +284,11 @@ export const deleteFromRemote = async (
if (password !== "") {
remoteFileName = remoteEncryptedKey;
}
remoteFileName = getWebdavPath(remoteFileName);
remoteFileName = getWebdavPath(remoteFileName, client.vaultName);
await client.init();
try {
await client.deleteFile(remoteFileName);
await client.client.deleteFile(remoteFileName);
// console.log(`delete ${remoteFileName} succeeded`);
} catch (err) {
console.error("some error while deleting");
@@ -224,7 +296,8 @@ export const deleteFromRemote = async (
}
};
export const checkConnectivity = async (client: WebDAVClient) => {
export const checkConnectivity = async (client: WrappedWebdavClient) => {
await client.init();
try {
const results = await getRemoteMeta(client, "/");
if (results === undefined) {
+5 -1
View File
@@ -1,6 +1,10 @@
/* set the styles */
.password_second_confirm {
.password-second-confirm {
font-weight: bold;
}
.password-disclaimer {
font-weight: bold;
}
+15
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";
@@ -133,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 -1
View File
@@ -1,3 +1,3 @@
{
"0.2.3": "0.12.15"
"0.2.4": "0.12.15"
}
+4
View File
@@ -33,6 +33,10 @@ module.exports = {
use: "ts-loader",
exclude: /node_modules/,
},
{
test: /\.svg?$/,
type: "asset/source",
},
],
},
resolve: {