0.24.0.dev-rc4

This commit is contained in:
vorotamoroz
2024-10-18 11:14:58 +01:00
parent 7ca5ac5ac7
commit e0e0ab0426
19 changed files with 555 additions and 367 deletions

View File

@@ -1,7 +1,7 @@
{
"id": "obsidian-livesync",
"name": "Self-hosted LiveSync",
"version": "0.24.0.dev-rc3",
"version": "0.24.0.dev-rc4",
"minAppVersion": "0.9.12",
"description": "Community implementation of self-hosted livesync. Reflect your vault changes to some other devices immediately. Please make sure to disable other synchronize solutions to avoid content corruption or duplication.",
"author": "vorotamoroz",

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "obsidian-livesync",
"version": "0.24.0.dev-rc3",
"version": "0.24.0.dev-rc4",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "obsidian-livesync",
"version": "0.24.0.dev-rc3",
"version": "0.24.0.dev-rc4",
"license": "MIT",
"dependencies": {
"@aws-sdk/client-s3": "^3.645.0",

View File

@@ -1,6 +1,6 @@
{
"name": "obsidian-livesync",
"version": "0.24.0.dev-rc3",
"version": "0.24.0.dev-rc4",
"description": "Reflect your vault changes to some other devices immediately. Please make sure to disable other synchronize solutions to avoid content corruption or duplication.",
"main": "main.js",
"type": "module",

View File

@@ -9,6 +9,7 @@ export const EVENT_LEAF_ACTIVE_CHANGED = "leaf-active-changed";
export const EVENT_LOG_ADDED = "log-added";
export const EVENT_REQUEST_OPEN_SETTINGS = "request-open-settings";
export const EVENT_REQUEST_OPEN_SETTING_WIZARD = "request-open-setting-wizard";
export const EVENT_REQUEST_OPEN_SETUP_URI = "request-open-setup-uri";
export const EVENT_REQUEST_COPY_SETUP_URI = "request-copy-setup-uri";

View File

@@ -1492,14 +1492,13 @@ export class ConfigSync extends LiveSyncCommands implements IObsidianModule {
return true;
}
async _askHiddenFileConfiguration(opt: { enableFetch?: boolean, enableOverwrite?: boolean }) {
const message = `Would you like to enable \`Customization sync\`?
This feature allows you to sync your customisations -- such as configurations, themes, snippets, and plugins -- across your devices in a fully controlled manner, unlike the fully automatic behaviour of hidden file synchronisation.
const message = `Would you like to enable **Customization sync**?
You may use this feature alongside hidden file synchronisation. When both features are enabled, items configured as \`Automatic\` in this feature will be managed by hidden file synchronisation.
Do not worry, you will be prompted to enable or keep disabled hidden file synchronisation after this dialogue.
Of course, you can enable or disable this feature at any time.
> [!DETAILS]-
> This feature allows you to sync your customisations -- such as configurations, themes, snippets, and plugins -- across your devices in a fully controlled manner, unlike the fully automatic behaviour of hidden file synchronisation.
>
> You may use this feature alongside hidden file synchronisation. When both features are enabled, items configured as \`Automatic\` in this feature will be managed by **hidden file synchronisation**.
> Do not worry, you will be prompted to enable or keep disabled **hidden file synchronisation** after this dialogue.
`
const CHOICE_CUSTOMIZE = "Yes, Enable it";
const CHOICE_DISABLE = "No, Disable it";
@@ -1576,6 +1575,7 @@ Of course, you can enable or disable this feature at any time.
this.plugin.deviceAndVaultName = name;
}
this.plugin.settings.usePluginSync = true;
this.plugin.settings.useAdvancedMode = true;
await this.plugin.saveSettings();
await this.scanAllConfigFiles(true);
}

View File

@@ -748,18 +748,19 @@ export class HiddenFileSync extends LiveSyncCommands implements IObsidianModule
return true;
}
async _askHiddenFileConfiguration(opt: { enableFetch?: boolean, enableOverwrite?: boolean }) {
const messageFetch = `${opt.enableFetch ? `- Fetch: Use the files stored from other devices. Choose this option if you have already configured hidden file synchronization on those devices and wish to accept their files.\n` : ""}`;
const messageOverwrite = `${opt.enableOverwrite ? ` - Overwrite: Use the files from this device. Select this option if you want to overwrite the files stored on other devices.\n` : ""}`;
const messageMerge = `- Merge: Merge the files from this device with those on other devices. Choose this option if you wish to combine files from multiple sources.
However, please be reminded that merging may cause conflicts if the files are not identical. Additionally, this process may occur within the same folder, potentially breaking your plug-in or theme settings that comprise multiple files.\n`;
const message = `Would you like to enable \`Hidden File Synchronization\`?
This feature allows you to synchronize all hidden files without any user interaction.
To enable this feature, you should choose one of the following options:
const messageFetch = `${opt.enableFetch ? `> - Fetch: Use the files stored from other devices. Choose this option if you have already configured hidden file synchronization on those devices and wish to accept their files.\n` : ""}`;
const messageOverwrite = `${opt.enableOverwrite ? `> - Overwrite: Use the files from this device. Select this option if you want to overwrite the files stored on other devices.\n` : ""}`;
const messageMerge = `> - Merge: Merge the files from this device with those on other devices. Choose this option if you wish to combine files from multiple sources.
> However, please be reminded that merging may cause conflicts if the files are not identical. Additionally, this process may occur within the same folder, potentially breaking your plug-in or theme settings that comprise multiple files.\n`;
const message = `Would you like to enable **Hidden File Synchronization**?
> [!DETAILS]-
> This feature allows you to synchronize all hidden files without any user interaction.
> To enable this feature, you should choose one of the following options:
${messageFetch}${messageOverwrite}${messageMerge}
Note: Please keep in mind that enabling this feature alongside customisation sync may override certain behaviors.`
> [!IMPORTANT]
> Please keep in mind that enabling this feature alongside customisation sync may override certain behaviors.`
const CHOICE_FETCH = "Fetch";
const CHOICE_OVERWRITE = "Overwrite";
const CHOICE_MERGE = "Merge";
@@ -817,6 +818,7 @@ Note: Please keep in mind that enabling this feature alongside customisation syn
} else if (mode == "MERGE") {
await this.syncInternalFilesAndDatabase("safe", true);
}
this.plugin.settings.useAdvancedMode = true;
this.plugin.settings.syncInternalFiles = true;
await this.plugin.saveSettings();
Logger(`Done! Restarting the app is strongly recommended!`, LOG_LEVEL_NOTICE);

Submodule src/lib updated: 92d7b03916...5079b0bf79

View File

@@ -347,11 +347,29 @@ export default class ObsidianLiveSyncPlugin extends Plugin implements LiveSyncLo
async onLiveSyncReady() {
if (!await this.$everyOnLayoutReady()) return;
eventHub.emitEvent(EVENT_LAYOUT_READY);
if (this.settings.suspendFileWatching) {
Logger("'Suspend file watching' turned on. Are you sure this is what you intended? Every modification on the vault will be ignored.", LOG_LEVEL_NOTICE);
}
if (this.settings.suspendParseReplicationResult) {
Logger("'Suspend database reflecting' turned on. Are you sure this is what you intended? Every replicated change will be postponed until disabling this option.", LOG_LEVEL_NOTICE);
if (this.settings.suspendFileWatching || this.settings.suspendParseReplicationResult) {
const ANSWER_KEEP = "Keep this plug-in suspended";
const ANSWER_RESUME = "Resume and restart Obsidian";
const message = `Self-hosted LiveSync has been configured to ignore some events. Is this intentional for you?
| Type | Status | Note |
|:---:|:---:|---|
| Storage Events | ${this.settings.suspendFileWatching ? "suspended" : "active"} | Every modification will be ignored |
| Database Events | ${this.settings.suspendParseReplicationResult ? "suspended" : "active"} | Every synchronised change will be postponed |
Do you want to resume them and restart Obsidian?
> [!DETAILS]-
> These flags are set by the plug-in while rebuilding, or fetching. If the process ends abnormally, it may be kept unintended.
> If you are not sure, you can try to rerun these processes. Make sure to back your vault up.
`;
if (await this.confirm.askSelectStringDialogue(message, [ANSWER_KEEP, ANSWER_RESUME], { defaultAction: ANSWER_KEEP, title: "Scram Enabled" }) == ANSWER_RESUME) {
this.settings.suspendFileWatching = false;
this.settings.suspendParseReplicationResult = false;
await this.saveSettings();
await this.$$scheduleAppReload();
return;
}
}
const isInitialized = await this.$$initializeDatabase(false, false);
if (!isInitialized) {
@@ -411,7 +429,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin implements LiveSyncLo
const lastVersion = ~~(versionNumberString2Number(manifestVersion) / 1000);
if (lastVersion > this.settings.lastReadUpdates && this.settings.isConfigured) {
Logger($f`Self-hosted LiveSync has undergone a major upgrade. Please open the setting dialog, and check the information pane.`, LOG_LEVEL_NOTICE);
Logger($f`You have some unread release notes! Please read them once!`, LOG_LEVEL_NOTICE);
}
//@ts-ignore
@@ -559,7 +577,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin implements LiveSyncLo
$anyAfterConnectCheckFailed(): Promise<boolean | "CHECKAGAIN" | undefined> { return InterceptiveAny; }
$$replicateAllToServer(showingNotice: boolean = false): Promise<boolean> { throwShouldBeOverridden() }
$$replicateAllToServer(showingNotice: boolean = false, sendChunksInBulkDisabled: boolean = false): Promise<boolean> { throwShouldBeOverridden() }
$$replicateAllFromServer(showingNotice: boolean = false): Promise<boolean> { throwShouldBeOverridden() }
// Remote Governing

View File

@@ -54,21 +54,9 @@ export class ModuleFileHandler extends AbstractModule implements ICoreModule {
if (!onlyChunks) {
return await this.db.store(readFile);
} else {
return true;
return await this.db.createChunks(readFile, false, true);
}
}
// I remember that it should be processed naturally. -->
// // If the file is exist on the database, then it should be updated.
// // Check the file is already conflicted or not.
// const conflictedRevs = await this.db.getConflictedRevs(file);
// if (conflictedRevs.length > 0) {
// // If conflicted, then it should be stored as new conflicted file.
// const readFile = await this.readFileFromStub(file);
// this.db.store(readFile, true);
// return false;
// }
//< --
// entry is exist on the database, check the difference between the file and the entry.

View File

@@ -27,6 +27,15 @@ export class ModuleRebuilder extends AbstractModule implements ICoreModule, Rebu
}
}
async askUsingOptionalFeature(opt: {
enableFetch?: boolean;
enableOverwrite?: boolean;
}) {
if (await this.core.confirm.askYesNoDialog("Do you want to enable extra features? If you are new to Self-hosted LiveSync, try the core feature first!", { title: "Enable extra features", defaultOption: "No", timeout: 15 }) == "yes") {
await this.core.$allAskUsingOptionalSyncFeature(opt);
}
}
async rebuildRemote() {
await this.core.$allSuspendExtraSync();
this.core.settings.isConfigured = true;
@@ -36,11 +45,11 @@ export class ModuleRebuilder extends AbstractModule implements ICoreModule, Rebu
await this.core.$$tryResetRemoteDatabase();
await this.core.$$markRemoteLocked();
await delay(500);
await this.core.$allAskUsingOptionalSyncFeature({ enableOverwrite: true });
await this.askUsingOptionalFeature({ enableOverwrite: true });
await delay(1000);
await this.core.$$replicateAllToServer(true);
await delay(1000);
await this.core.$$replicateAllToServer(true);
await this.core.$$replicateAllToServer(true, true);
}
$rebuildRemote(): Promise<void> {
return this.rebuildRemote();
@@ -59,11 +68,11 @@ export class ModuleRebuilder extends AbstractModule implements ICoreModule, Rebu
await this.core.$$tryResetRemoteDatabase();
await this.core.$$markRemoteLocked();
await delay(500);
await this.core.$allAskUsingOptionalSyncFeature({ enableOverwrite: true });
await this.askUsingOptionalFeature({ enableOverwrite: true });
await delay(1000);
await this.core.$$replicateAllToServer(true);
await delay(1000);
await this.core.$$replicateAllToServer(true);
await this.core.$$replicateAllToServer(true, true);
}
@@ -169,7 +178,7 @@ export class ModuleRebuilder extends AbstractModule implements ICoreModule, Rebu
await delay(1000);
await this.core.$$replicateAllFromServer(true);
await this.resumeReflectingDatabase();
await this.core.$allAskUsingOptionalSyncFeature({ enableFetch: true });
await this.askUsingOptionalFeature({ enableFetch: true });
}
async fetchLocalWithRebuild() {
return await this.fetchLocal(true);

View File

@@ -231,12 +231,17 @@ Or if you are sure know what had been happened, we can unlock the database from
return;
}
if (isAnyNote(change)) {
const docPath = getPath(change);
if (!await this.core.$$isTargetFile(docPath)) {
Logger(`Skipped: ${docPath}`, LOG_LEVEL_VERBOSE);
return;
}
if (this.databaseQueuedProcessor._isSuspended) {
Logger(`Processing scheduled: ${change.path}`, LOG_LEVEL_INFO);
Logger(`Processing scheduled: ${docPath}`, LOG_LEVEL_INFO);
}
const size = change.size;
if (this.core.$$isFileSizeExceeded(size)) {
Logger(`Processing ${change.path} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
Logger(`Processing ${docPath} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
return;
}
this.databaseQueuedProcessor.enqueue(change);
@@ -258,6 +263,7 @@ Or if you are sure know what had been happened, we can unlock the database from
databaseQueuedProcessor = new QueueProcessor(async (docs: EntryBody[]) => {
const dbDoc = docs[0] as LoadedEntry; // It has no `data`
const path = getPath(dbDoc);
// If `Read chunks online` is disabled, chunks should be transferred before here.
// However, in some cases, chunks are after that. So, if missing chunks exist, we have to wait for them.
const doc = await this.localDatabase.getDBEntryFromMeta({ ...dbDoc }, {}, false, true, true);
@@ -308,15 +314,17 @@ Or if you are sure know what had been happened, we can unlock the database from
return Promise.resolve(true);
}
async $$replicateAllToServer(showingNotice: boolean = false): Promise<boolean> {
async $$replicateAllToServer(showingNotice: boolean = false, sendChunksInBulkDisabled: boolean = false): Promise<boolean> {
if (!this.core.isReady) return false;
if (!await this.core.$everyBeforeReplicate(showingNotice)) {
Logger(`Replication has been cancelled by some module failure`, LOG_LEVEL_NOTICE);
return false;
}
if (this.core.replicator instanceof LiveSyncCouchDBReplicator) {
if (await this.core.confirm.askYesNoDialog("Do you want to send all chunks before replication?", { defaultOption: "No", timeout: 20 }) == "yes") {
await this.core.replicator.sendChunks(this.core.settings, undefined, true, 0);
if (!sendChunksInBulkDisabled) {
if (this.core.replicator instanceof LiveSyncCouchDBReplicator) {
if (await this.core.confirm.askYesNoDialog("Do you want to send all chunks before replication?", { defaultOption: "No", timeout: 20 }) == "yes") {
await this.core.replicator.sendChunks(this.core.settings, undefined, true, 0);
}
}
}
const ret = await this.core.replicator.replicateAllToServer(this.settings, showingNotice);

View File

@@ -1,39 +1,40 @@
import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
import { AbstractModule } from "../AbstractModule.ts";
import { sizeToHumanReadable } from "octagonal-wheels/number";
import { delay } from "octagonal-wheels/promises";
import type { ICoreModule } from "../ModuleTypes.ts";
export class ModuleCheckRemoteSize extends AbstractModule implements ICoreModule {
async $allScanStat(): Promise<boolean> {
this._log(`Checking storage sizes`, LOG_LEVEL_VERBOSE);
if (this.settings.notifyThresholdOfRemoteStorageSize < 0) {
const message = `Now, Self-hosted LiveSync is able to check the remote storage size on the start-up.
const message = `We can set a maximum database capacity warning, **to take action before running out of space on the remote storage**.
Do you want to enable this?
You can configure the threshold size for your remote storage. This will be different for your server.
> [!MORE]-
> - 0: Do not warn about storage size.
> This is recommended if you have enough space on the remote storage especially you have self-hosted. And you can check the storage size and rebuild manually.
> - 800: Warn if the remote storage size exceeds 800MB.
> This is recommended if you are using fly.io with 1GB limit or IBM Cloudant.
> - 2000: Warn if the remote storage size exceeds 2GB.
Please choose the threshold size as you like.
- 0: Do not warn about storage size.
This is recommended if you have enough space on the remote storage especially you have self-hosted. And you can check the storage size and rebuild manually.
- 800: Warn if the remote storage size exceeds 800MB.
This is recommended if you are using fly.io with 1GB limit or IBM Cloudant.
- 2000: Warn if the remote storage size exceeds 2GB.
And if your actual storage size exceeds the threshold after the setup, you may warned again. But do not worry, you can enlarge the threshold (or rebuild everything to reduce the size).
If we have reached the limit, we will be asked to enlarge the limit step by step.
`
const ANSWER_0 = "Do not warn";
const ANSWER_800 = "800MB";
const ANSWER_2000 = "2GB";
const ANSWER_0 = "No, never warn please";
const ANSWER_800 = "800MB (Cloudant, fly.io)";
const ANSWER_2000 = "2GB (Standard)";
const ASK_ME_NEXT_TIME = "Ask me later";
const ret = await this.core.confirm.confirmWithMessage("Remote storage size threshold", message, [ANSWER_0, ANSWER_800, ANSWER_2000], ANSWER_800, 40);
const ret = await this.core.confirm.askSelectStringDialogue(message, [ANSWER_0, ANSWER_800, ANSWER_2000, ASK_ME_NEXT_TIME], {
defaultAction: ASK_ME_NEXT_TIME,
title: "Setting up database size notification", timeout: 40
});
if (ret == ANSWER_0) {
this.settings.notifyThresholdOfRemoteStorageSize = 0;
await this.core.saveSettings();
} else if (ret == ANSWER_800) {
this.settings.notifyThresholdOfRemoteStorageSize = 800;
await this.core.saveSettings();
} else {
} else if (ret == ANSWER_2000) {
this.settings.notifyThresholdOfRemoteStorageSize = 2000;
await this.core.saveSettings();
}
@@ -45,28 +46,38 @@ And if your actual storage size exceeds the threshold after the setup, you may w
if (estimatedSize) {
const maxSize = this.settings.notifyThresholdOfRemoteStorageSize * 1024 * 1024;
if (estimatedSize > maxSize) {
const message = `Remote storage size: ${sizeToHumanReadable(estimatedSize)}. It exceeds the configured value ${sizeToHumanReadable(maxSize)}.
This may cause the storage to be full. You should enlarge the remote storage, or rebuild everything to reduce the size. \n
**Note:** If you are new to Self-hosted LiveSync, you should enlarge the threshold. \n
const message = `**Your database is getting larger!** But do not worry, we can address it now. The time before running out of space on the remote storage.
Self-hosted LiveSync will not release the storage automatically even if the file is deleted. This is why they need regular maintenance.\n
| Measured size | Configured size |
| --- | --- |
| ${sizeToHumanReadable(estimatedSize)} | ${sizeToHumanReadable(maxSize)} |
If you have enough space on the remote storage, you can enlarge the threshold. Otherwise, you should rebuild everything.\n
> [!MORE]-
> If you have been using it for many years, there may be unreferenced chunks - that is, garbage - accumulating in the database. Therefore, we recommend rebuilding everything. It will probably become much smaller.
>
> If the volume of your vault is simply increasing, it is better to rebuild everything after organizing the files. Self-hosted LiveSync does not delete the actual data even if you delete it to speed up the process. It is roughly [documented](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).
>
> If you don't mind the increase, you can increase the notification limit by 100MB. This is the case if you are running it on your own server. However, it is better to rebuild everything from time to time.
>
> [!WARNING]
> If you perform rebuild everything, make sure all devices are synchronised. The plug-in will merge as much as possible, though.
However, **Please make sure that all devices have been synchronised**. \n
\n`;
const newMax = ~~(estimatedSize / 1024 / 1024) + 100;
const ANSWER_ENLARGE_LIMIT = `Enlarge to ${newMax}MB`;
const ANSWER_REBUILD = "Rebuild now";
const ANSWER_ENLARGE_LIMIT = `increase to ${newMax}MB`;
const ANSWER_REBUILD = "Rebuild Everything Now";
const ANSWER_IGNORE = "Dismiss";
const ret = await this.core.confirm.confirmWithMessage("Remote storage size exceeded", message, [ANSWER_ENLARGE_LIMIT, ANSWER_REBUILD, ANSWER_IGNORE,], ANSWER_IGNORE, 20);
const ret = await this.core.confirm.askSelectStringDialogue(message, [ANSWER_ENLARGE_LIMIT, ANSWER_REBUILD, ANSWER_IGNORE,], {
defaultAction: ANSWER_IGNORE,
title: "Remote storage size exceeded the limit", timeout: 60
});
if (ret == ANSWER_REBUILD) {
const ret = await this.core.confirm.askYesNoDialog("This may take a bit of a long time. Do you really want to rebuild everything now?", { defaultOption: "No" });
if (ret == "yes") {
this._log(`Receiving all from the server before rebuilding`, LOG_LEVEL_NOTICE);
await this.core.$$replicateAllFromServer(true);
await delay(3000);
this._log(`Obsidian will be reloaded to rebuild everything.`, LOG_LEVEL_NOTICE);
this.core.settings.notifyThresholdOfRemoteStorageSize = -1;
await this.saveSettings();
await this.core.rebuilder.scheduleRebuild();
}
} else if (ret == ANSWER_ENLARGE_LIMIT) {

View File

@@ -77,7 +77,11 @@ export class ModuleRedFlag extends AbstractModule implements ICoreModule {
}
} else if (isRedFlag3Raised) {
this._log(`${FLAGMD_REDFLAG3} or ${FLAGMD_REDFLAG3_HR} has been detected! Self-hosted LiveSync will discard the local database and fetch everything from the remote once again.`, LOG_LEVEL_NOTICE);
const makeLocalChunkBeforeSync = ((await this.core.confirm.askYesNoDialog("Do you want to create local chunks before fetching?", { defaultOption: "Yes" })) == "yes");
const makeLocalChunkBeforeSync = ((await this.core.confirm.askYesNoDialog(`Do you want to create local chunks before fetching?
> [!MORE]-
> If creating local chunks before fetching, only the difference between the local and remote will be fetched.
`, { defaultOption: "Yes", title: "Trick to transfer efficiently" })) == "yes");
await this.core.rebuilder.$fetchLocal(makeLocalChunkBeforeSync);
await this.deleteRedFlag3();
if (this.settings.suspendFileWatching) {
@@ -87,6 +91,8 @@ export class ModuleRedFlag extends AbstractModule implements ICoreModule {
this.core.$$performRestart();
return false;
}
} else {
this._log("Your content of files will be synchronised gradually. Please wait for the completion.", LOG_LEVEL_NOTICE);
}
} else {
// Case of FLAGMD_REDFLAG.

View File

@@ -1,7 +1,29 @@
import { ButtonComponent } from "obsidian";
import { App, FuzzySuggestModal, MarkdownRenderer, Modal, Plugin, Setting } from "../../../deps.ts";
import { EVENT_PLUGIN_UNLOADED, eventHub } from "../../../common/events.ts";
import { delay } from "octagonal-wheels/promises";
export class InputStringDialog extends Modal {
class AutoClosableModal extends Modal {
removeEvent: (() => void) | undefined;
constructor(app: App) {
super(app);
this.removeEvent = eventHub.on(EVENT_PLUGIN_UNLOADED, async () => {
await delay(100);
if (!this.removeEvent) return;
this.close();
this.removeEvent = undefined;
});
}
onClose() {
if (this.removeEvent) {
this.removeEvent();
this.removeEvent = undefined
}
}
}
export class InputStringDialog extends AutoClosableModal {
result: string | false = false;
onSubmit: (result: string | false) => void;
title: string;
@@ -47,6 +69,7 @@ export class InputStringDialog extends Modal {
}
onClose() {
super.onClose();
const { contentEl } = this;
contentEl.empty();
if (this.isManuallyClosed) {
@@ -95,7 +118,7 @@ export class PopoverSelectString extends FuzzySuggestModal<string> {
}
}
export class MessageBox extends Modal {
export class MessageBox extends AutoClosableModal {
plugin: Plugin;
title: string;
@@ -144,16 +167,19 @@ export class MessageBox extends Modal {
onOpen() {
const { contentEl } = this;
this.titleEl.setText(this.title);
contentEl.addEventListener("click", () => {
if (this.timer) {
clearInterval(this.timer);
this.timer = undefined;
this.defaultButtonComponent?.setButtonText(`${this.defaultAction}`);
}
})
const div = contentEl.createDiv();
div.style.userSelect = "text";
void MarkdownRenderer.render(this.plugin.app, this.contentMd, div, "/", this.plugin);
const buttonSetting = new Setting(contentEl);
const labelWrapper = contentEl.createDiv();
labelWrapper.addClass("sls-dialogue-note-wrapper");
const labelEl = labelWrapper.createEl("label", { text: "To stop the countdown, tap anywhere on the dialogue" });
labelEl.addClass("sls-dialogue-note-countdown");
if (!this.timeout || !this.timer) {
labelWrapper.empty();
labelWrapper.style.display = "none";
}
buttonSetting.infoEl.style.display = "none";
buttonSetting.controlEl.style.flexWrap = "wrap";
if (this.wideButton) {
@@ -162,6 +188,15 @@ export class MessageBox extends Modal {
buttonSetting.controlEl.style.justifyContent = "center";
buttonSetting.controlEl.style.flexGrow = "1";
}
contentEl.addEventListener("click", () => {
if (this.timer) {
labelWrapper.empty();
labelWrapper.style.display = "none";
clearInterval(this.timer);
this.timer = undefined;
this.defaultButtonComponent?.setButtonText(`${this.defaultAction}`);
}
})
for (const button of this.buttons) {
buttonSetting.addButton((btn) => {
btn
@@ -190,6 +225,7 @@ export class MessageBox extends Modal {
}
onClose() {
super.onClose();
const { contentEl } = this;
contentEl.empty();
if (this.timer) {

View File

@@ -1,9 +1,11 @@
import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from 'octagonal-wheels/common/logger.js';
import { SETTING_VERSION_SUPPORT_CASE_INSENSITIVE } from '../../lib/src/common/types.js';
import { EVENT_REQUEST_OPEN_SETTINGS, EVENT_REQUEST_OPEN_SETUP_URI, eventHub } from '../../common/events.ts';
import { EVENT_REQUEST_OPEN_SETTING_WIZARD, EVENT_REQUEST_OPEN_SETTINGS, EVENT_REQUEST_OPEN_SETUP_URI, eventHub } from '../../common/events.ts';
import { AbstractModule } from "../AbstractModule.ts";
import type { ICoreModule } from "../ModuleTypes.ts";
const URI_DOC = "https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use";
export class ModuleMigration extends AbstractModule implements ICoreModule {
async migrateDisableBulkSend() {
@@ -159,6 +161,63 @@ ___However, to enable either of these changes, both remote and local databases n
}
async initialMessage() {
const message = `Your device has **not been set up yet**. Let me guide you through the setup process.
Please keep in mind that every dialogue content can be copied to the clipboard. If you need to refer to it later, you can paste it into a note in Obsidian. You can also translate it into your language using a translation tool.
First, do you have **Setup URI**?
Note: If you do not know what it is, please refer to the [documentation](${URI_DOC}).
`;
const USE_SETUP = "Yes, I have";
const NEXT = "No, I do not have";
const ret = await this.core.confirm.askSelectStringDialogue(message, [
USE_SETUP, NEXT], {
title: "Welcome to Self-hosted LiveSync",
defaultAction: USE_SETUP
});
if (ret === USE_SETUP) {
eventHub.emitEvent(EVENT_REQUEST_OPEN_SETUP_URI);
return false;
}
else if (ret == NEXT) {
return true;
}
return false;
}
async askAgainForSetupURI() {
const message = `We strongly recommend that you generate a set-up URI and use it.
If you do not have knowledge about it, please refer to the [documentation](${URI_DOC}) (Sorry again, but it is important).
How do you want to set it up manually?`;
const USE_MINIMAL = "Take me into the setup wizard";
const USE_SETUP = "Set it up all manually";
const NEXT = "Remind me at the next launch";
const ret = await this.core.confirm.askSelectStringDialogue(message, [
USE_MINIMAL, USE_SETUP, NEXT], {
title: "Recommendation to use Setup URI",
defaultAction: USE_MINIMAL
});
if (ret === USE_MINIMAL) {
eventHub.emitEvent(EVENT_REQUEST_OPEN_SETTING_WIZARD);
return false;
}
if (ret === USE_SETUP) {
eventHub.emitEvent(EVENT_REQUEST_OPEN_SETTINGS);
return false;
}
else if (ret == NEXT) {
return false;
}
return false;
}
async $everyOnFirstInitialize(): Promise<boolean> {
if (!this.localDatabase.isReady) {
this._log(`Something went wrong! The local database is not ready`, LOG_LEVEL_NOTICE);
@@ -170,40 +229,11 @@ ___However, to enable either of these changes, both remote and local databases n
}
if (!this.settings.isConfigured) {
// Case sensitivity
const message = `Hello and welcome to Self-hosted LiveSync.
Your device seems to **not be configured yet**. Please finish the setup and synchronise your vaults!
Click anywhere to stop counting down.
## At the first device
- With Setup URI -> Use \`Use the copied setup URI\`.
If you have configured it automatically, you should have one.
- Without Setup URI -> Use \`Setup wizard\` in setting dialogue. **\`Minimal setup\` is recommended**.
- What is the Setup URI? -> Do not worry! We have [some docs](https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use) now. Please refer to them once.
## At the subsequent device
- With Setup URI -> Use \`Use the copied setup URI\`.
If you do not have it yet, you can copy it on the first device.
- Without Setup URI -> Use \`Setup wizard\` in setting dialogue, but **strongly recommends using setup URI**.
`
const OPEN_SETUP = "Open setting dialog";
const USE_SETUP = "Use the copied setup URI";
const DISMISS = "Dismiss";
const ret = await this.core.confirm.confirmWithMessage("Welcome to Self-hosted LiveSync", message, [
USE_SETUP, OPEN_SETUP, DISMISS], DISMISS, 40);
if (ret === OPEN_SETUP) {
try {
eventHub.emitEvent(EVENT_REQUEST_OPEN_SETTINGS);
} catch (ex) {
this._log("Something went wrong on opening setting dialog, please open it manually", LOG_LEVEL_NOTICE);
this._log(ex, LOG_LEVEL_VERBOSE);
}
} else if (ret == USE_SETUP) {
eventHub.emitEvent(EVENT_REQUEST_OPEN_SETUP_URI);
if (!await this.initialMessage() || !await this.askAgainForSetupURI()) {
this._log("The setup has been cancelled, Self-hosted LiveSync waiting for your setup!", LOG_LEVEL_NOTICE);
return false;
}
return true;
}
return true;
}

View File

@@ -106,28 +106,6 @@ export class ModuleInteractiveConflictResolver extends AbstractObsidianModule im
return false;
}
// async resolveConflictByNewerEntry(path: FilePathWithPrefix) {
// const id = await this.plugin.$$path2id(path);
// const doc = await this.localDatabase.getRaw<AnyEntry>(id, { conflicts: true });
// // If there is no conflict, return with false.
// if (!("_conflicts" in doc) || doc._conflicts === undefined) return false;
// if (doc._conflicts.length == 0) return false;
// this._log(`Hidden file conflicted:${getPath(doc)}`);
// const conflicts = doc._conflicts.sort((a, b) => Number(a.split("-")[0]) - Number(b.split("-")[0]));
// const revA = doc._rev;
// const revB = conflicts[0];
// const revBDoc = await this.localDatabase.getRaw<EntryDoc>(id, { rev: revB });
// // determine which revision should been deleted.
// // simply check modified time
// const mtimeA = ("mtime" in doc && doc.mtime) || 0;
// const mtimeB = ("mtime" in revBDoc && revBDoc.mtime) || 0;
// const delRev = mtimeA < mtimeB ? revA : revB;
// // delete older one.
// await this.localDatabase.removeRevision(id, delRev);
// this._log(`Older one has been deleted:${getPath(doc)}`);
// return true;
// }
async $allScanStat(): Promise<boolean> {
const notes: { path: string, mtime: number }[] = [];
this._log(`Checking conflicted files`, LOG_LEVEL_VERBOSE);

View File

@@ -1,7 +1,7 @@
import { ObsidianLiveSyncSettingTab } from "./SettingDialogue/ObsidianLiveSyncSettingTab.ts";
import { type IObsidianModule, AbstractObsidianModule } from "../AbstractObsidianModule.ts";
// import { PouchDB } from "../../lib/src/pouchdb/pouchdb-browser";
import { EVENT_REQUEST_OPEN_SETTINGS, eventHub } from "../../common/events.ts";
import { EVENT_REQUEST_OPEN_SETTING_WIZARD, EVENT_REQUEST_OPEN_SETTINGS, eventHub } from "../../common/events.ts";
export class ModuleObsidianSettingDialogue extends AbstractObsidianModule implements IObsidianModule {
@@ -11,6 +11,11 @@ export class ModuleObsidianSettingDialogue extends AbstractObsidianModule implem
this.settingTab = new ObsidianLiveSyncSettingTab(this.app, this.plugin);
this.plugin.addSettingTab(this.settingTab);
eventHub.onEvent(EVENT_REQUEST_OPEN_SETTINGS, () => this.openSetting());
eventHub.onEvent(EVENT_REQUEST_OPEN_SETTING_WIZARD, () => {
this.openSetting();
void this.settingTab.enableMinimalSetup();
});
return Promise.resolve(true);
}

View File

@@ -405,11 +405,51 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab {
}
}
screenElements: { [key: string]: HTMLElement[] } = {};
changeDisplay(screen: string) {
for (const k in this.screenElements) {
if (k == screen) {
this.screenElements[k].forEach((element) => element.removeClass("setting-collapsed"));
} else {
this.screenElements[k].forEach((element) => element.addClass("setting-collapsed"));
}
}
if (this.menuEl) {
this.menuEl.querySelectorAll(`.sls-setting-label`).forEach((element) => {
if (element.hasClass(`c-${screen}`)) {
element.addClass("selected");
(element.querySelector<HTMLInputElement>("input[type=radio]"))!.checked = true;
} else {
element.removeClass("selected");
(element.querySelector<HTMLInputElement>("input[type=radio]"))!.checked = false;
}
});
}
this.selectedScreen = screen;
}
async enableMinimalSetup() {
this.editingSettings.liveSync = false;
this.editingSettings.periodicReplication = false;
this.editingSettings.syncOnSave = false;
this.editingSettings.syncOnEditorSave = false;
this.editingSettings.syncOnStart = false;
this.editingSettings.syncOnFileOpen = false;
this.editingSettings.syncAfterMerge = false;
this.plugin.replicator.closeReplication();
await this.saveAllDirtySettings();
this.containerEl.addClass("isWizard");
this.inWizard = true;
this.changeDisplay("20")
}
menuEl?: HTMLElement;
display(): void {
const changeDisplay = this.changeDisplay.bind(this);
const { containerEl } = this;
this.settingComponents.length = 0;
this.controlledElementFunc.length = 0;
this.onSavedHandlers.length = 0;
this.screenElements = {};
if (this._editingSettings == undefined || this.initialSettings == undefined) {
this.reloadAllSettings();
}
@@ -436,26 +476,26 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab {
setStyle(containerEl, "menu-setting-advanced", () => this.isConfiguredAs("useAdvancedMode", true));
setStyle(containerEl, "menu-setting-edgecase", () => this.isConfiguredAs("useEdgeCaseMode", true));
const screenElements: { [key: string]: HTMLElement[] } = {};
const addScreenElement = (key: string, element: HTMLElement) => {
if (!(key in screenElements)) {
screenElements[key] = [];
if (!(key in this.screenElements)) {
this.screenElements[key] = [];
}
screenElements[key].push(element);
this.screenElements[key].push(element);
};
const menuWrapper = this.createEl(containerEl, "div", { cls: "sls-setting-menu-wrapper" });
const w = menuWrapper.createDiv("");
w.addClass("sls-setting-menu");
const menuTabs = w.querySelectorAll(".sls-setting-label");
if (this.menuEl) {
this.menuEl.remove();
}
this.menuEl = menuWrapper.createDiv("");
this.menuEl.addClass("sls-setting-menu");
const menuTabs = this.menuEl.querySelectorAll(".sls-setting-label");
const selectPane = (event: Event) => {
const target = event.target as HTMLElement;
if (target.tagName == "INPUT") {
const value = target.getAttribute("value");
if (value && this.selectedScreen != value) {
changeDisplay(value);
// target.parentElement?.parentElement?.querySelector(".sls-setting-label.selected")?.removeClass("selected");
// target.parentElement?.addClass("selected");
}
}
}
@@ -575,17 +615,19 @@ Store only the settings. **Caution: This may lead to data corruption**; database
}
setLevelClass(el, level)
el.createEl("h3", { text: title, cls: "sls-setting-pane-title" });
w.createEl("label", { cls: `sls-setting-label c-${order} ${wizardHidden ? "wizardHidden" : ""}` }, el => {
setLevelClass(el, level)
const inputEl = el.createEl("input", {
type: "radio", name: "disp", value: `${order}`, cls: "sls-setting-tab"
} as DomElementInfo);
el.createEl("div", {
cls: "sls-setting-menu-btn", text: icon, title: title
});
inputEl.addEventListener("change", selectPane);
inputEl.addEventListener("click", selectPane);
})
if (this.menuEl) {
this.menuEl.createEl("label", { cls: `sls-setting-label c-${order} ${wizardHidden ? "wizardHidden" : ""}` }, el => {
setLevelClass(el, level)
const inputEl = el.createEl("input", {
type: "radio", name: "disp", value: `${order}`, cls: "sls-setting-tab"
} as DomElementInfo);
el.createEl("div", {
cls: "sls-setting-menu-btn", text: icon, title: title
});
inputEl.addEventListener("change", selectPane);
inputEl.addEventListener("click", selectPane);
})
}
addScreenElement(`${order}`, el);
const p = Promise.resolve(el)
// fireAndForget
@@ -615,31 +657,13 @@ Store only the settings. **Caution: This may lead to data corruption**; database
return p;
}
const changeDisplay = (screen: string) => {
for (const k in screenElements) {
if (k == screen) {
screenElements[k].forEach((element) => element.removeClass("setting-collapsed"));
} else {
screenElements[k].forEach((element) => element.addClass("setting-collapsed"));
}
}
w.querySelectorAll(`.sls-setting-label`).forEach((element) => {
if (element.hasClass(`c-${screen}`)) {
element.addClass("selected");
(element.querySelector<HTMLInputElement>("input[type=radio]"))!.checked = true;
} else {
element.removeClass("selected");
(element.querySelector<HTMLInputElement>("input[type=radio]"))!.checked = false;
}
});
this.selectedScreen = screen;
};
menuTabs.forEach((element) => {
const e = element.querySelector(".sls-setting-tab");
if (!e) return;
e.addEventListener("change", (event) => {
menuTabs.forEach((element) => element.removeClass("selected"));
changeDisplay((event.currentTarget as HTMLInputElement).value);
this.changeDisplay((event.currentTarget as HTMLInputElement).value);
element.addClass("selected");
});
});
@@ -772,18 +796,7 @@ Store only the settings. **Caution: This may lead to data corruption**; database
.setName("Minimal setup")
.addButton((text) => {
text.setButtonText("Start").onClick(async () => {
this.editingSettings.liveSync = false;
this.editingSettings.periodicReplication = false;
this.editingSettings.syncOnSave = false;
this.editingSettings.syncOnEditorSave = false;
this.editingSettings.syncOnStart = false;
this.editingSettings.syncOnFileOpen = false;
this.editingSettings.syncAfterMerge = false;
this.plugin.replicator.closeReplication();
await this.saveAllDirtySettings();
containerEl.addClass("isWizard");
this.inWizard = true;
changeDisplay("0")
await this.enableMinimalSetup();
})
})
new Setting(paneEl)
@@ -816,6 +829,8 @@ Store only the settings. **Caution: This may lead to data corruption**; database
text.setButtonText("Discard").onClick(async () => {
if (await this.plugin.confirm.askYesNoDialog("Do you really want to discard existing settings and databases?", { defaultOption: "No" }) == "yes") {
this.editingSettings = { ...this.editingSettings, ...DEFAULT_SETTINGS };
await this.saveAllDirtySettings();
this.plugin.settings = { ...DEFAULT_SETTINGS };
await this.plugin.$$saveSettingData();
await this.plugin.$$resetLocalDatabase();
// await this.plugin.initializeDatabase();
@@ -918,14 +933,193 @@ Store only the settings. **Caution: This may lead to data corruption**; database
new Setting(paneEl).autoWireToggle("showStatusOnStatusbar");
});
void addPanel(paneEl, "Logging").then((paneEl) => {
paneEl.addClass("wizardHidden");
new Setting(paneEl).autoWireToggle("lessInformationInLog");
new Setting(paneEl)
.autoWireToggle("showVerboseLog", { onUpdate: visibleOnly(() => this.isConfiguredAs("lessInformationInLog", false)) });
});
new Setting(paneEl)
.setClass("wizardOnly")
.addButton((button) => button
.setButtonText("Next")
.setCta()
.onClick(() => {
this.changeDisplay("0");
})
);
})
let checkResultDiv: HTMLDivElement;
const checkConfig = async (checkResultDiv: HTMLDivElement | undefined) => {
Logger(`Checking database configuration`, LOG_LEVEL_INFO);
let isSuccessful = true;
const emptyDiv = createDiv();
emptyDiv.innerHTML = "<span></span>";
checkResultDiv?.replaceChildren(...[emptyDiv]);
const addResult = (msg: string, classes?: string[]) => {
const tmpDiv = createDiv();
tmpDiv.addClass("ob-btn-config-fix");
if (classes) {
tmpDiv.addClasses(classes);
}
tmpDiv.innerHTML = `${msg}`;
checkResultDiv?.appendChild(tmpDiv);
};
try {
if (isCloudantURI(this.editingSettings.couchDB_URI)) {
Logger("This feature cannot be used with IBM Cloudant.", LOG_LEVEL_NOTICE);
return;
}
const r = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, window.origin);
const responseConfig = r.json;
const addConfigFixButton = (title: string, key: string, value: string) => {
if (!checkResultDiv) return;
const tmpDiv = createDiv();
tmpDiv.addClass("ob-btn-config-fix");
tmpDiv.innerHTML = `<label>${title}</label><button>Fix</button>`;
const x = checkResultDiv.appendChild(tmpDiv);
x.querySelector("button")?.addEventListener("click", () => {
fireAndForget(async () => {
Logger(`CouchDB Configuration: ${title} -> Set ${key} to ${value}`)
const res = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, undefined, key, value);
if (res.status == 200) {
Logger(`CouchDB Configuration: ${title} successfully updated`, LOG_LEVEL_NOTICE);
checkResultDiv.removeChild(x);
await checkConfig(checkResultDiv);
} else {
Logger(`CouchDB Configuration: ${title} failed`, LOG_LEVEL_NOTICE);
Logger(res.text, LOG_LEVEL_VERBOSE);
}
});
});
};
addResult("---Notice---", ["ob-btn-config-head"]);
addResult("If the server configuration is not persistent (e.g., running on docker), the values set from here will also be volatile. Once you are able to connect, please reflect the settings in the server's local.ini.", ["ob-btn-config-info"]);
addResult("--Config check--", ["ob-btn-config-head"]);
// Admin check
// for database creation and deletion
if (!(this.editingSettings.couchDB_USER in responseConfig.admins)) {
addResult(`⚠ You do not have administrative privileges.`);
} else {
addResult("✔ You have administrative privileges.");
}
// HTTP user-authorization check
if (responseConfig?.chttpd?.require_valid_user != "true") {
isSuccessful = false;
addResult("❗ chttpd.require_valid_user is wrong.");
addConfigFixButton("Set chttpd.require_valid_user = true", "chttpd/require_valid_user", "true");
} else {
addResult("✔ chttpd.require_valid_user is ok.");
}
if (responseConfig?.chttpd_auth?.require_valid_user != "true") {
isSuccessful = false;
addResult("❗ chttpd_auth.require_valid_user is wrong.");
addConfigFixButton("Set chttpd_auth.require_valid_user = true", "chttpd_auth/require_valid_user", "true");
} else {
addResult("✔ chttpd_auth.require_valid_user is ok.");
}
// HTTPD check
// Check Authentication header
if (!responseConfig?.httpd["WWW-Authenticate"]) {
isSuccessful = false;
addResult("❗ httpd.WWW-Authenticate is missing");
addConfigFixButton("Set httpd.WWW-Authenticate", "httpd/WWW-Authenticate", 'Basic realm="couchdb"');
} else {
addResult("✔ httpd.WWW-Authenticate is ok.");
}
if (responseConfig?.httpd?.enable_cors != "true") {
isSuccessful = false;
addResult("❗ httpd.enable_cors is wrong");
addConfigFixButton("Set httpd.enable_cors", "httpd/enable_cors", "true");
} else {
addResult("✔ httpd.enable_cors is ok.");
}
// If the server is not cloudant, configure request size
if (!isCloudantURI(this.editingSettings.couchDB_URI)) {
// REQUEST SIZE
if (Number(responseConfig?.chttpd?.max_http_request_size ?? 0) < 4294967296) {
isSuccessful = false;
addResult("❗ chttpd.max_http_request_size is low)");
addConfigFixButton("Set chttpd.max_http_request_size", "chttpd/max_http_request_size", "4294967296");
} else {
addResult("✔ chttpd.max_http_request_size is ok.");
}
if (Number(responseConfig?.couchdb?.max_document_size ?? 0) < 50000000) {
isSuccessful = false;
addResult("❗ couchdb.max_document_size is low)");
addConfigFixButton("Set couchdb.max_document_size", "couchdb/max_document_size", "50000000");
} else {
addResult("✔ couchdb.max_document_size is ok.");
}
}
// CORS check
// checking connectivity for mobile
if (responseConfig?.cors?.credentials != "true") {
isSuccessful = false;
addResult("❗ cors.credentials is wrong");
addConfigFixButton("Set cors.credentials", "cors/credentials", "true");
} else {
addResult("✔ cors.credentials is ok.");
}
const ConfiguredOrigins = ((responseConfig?.cors?.origins ?? "") + "").split(",");
if (responseConfig?.cors?.origins == "*" || (ConfiguredOrigins.indexOf("app://obsidian.md") !== -1 && ConfiguredOrigins.indexOf("capacitor://localhost") !== -1 && ConfiguredOrigins.indexOf("http://localhost") !== -1)) {
addResult("✔ cors.origins is ok.");
} else {
addResult("❗ cors.origins is wrong");
addConfigFixButton("Set cors.origins", "cors/origins", "app://obsidian.md,capacitor://localhost,http://localhost");
isSuccessful = false;
}
addResult("--Connection check--", ["ob-btn-config-head"]);
addResult(`Current origin:${window.location.origin}`);
// Request header check
const origins = [
"app://obsidian.md",
"capacitor://localhost",
"http://localhost"];
for (const org of origins) {
const rr = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, org);
const responseHeaders = Object.fromEntries(Object.entries(rr.headers)
.map((e) => {
e[0] = `${e[0]}`.toLowerCase();
return e;
}));
addResult(`Origin check:${org}`);
if (responseHeaders["access-control-allow-credentials"] != "true") {
addResult("❗ CORS is not allowing credentials");
isSuccessful = false;
} else {
addResult("✔ CORS credentials OK");
}
if (responseHeaders["access-control-allow-origin"] != org) {
addResult(`⚠ CORS Origin is unmatched:${origin}->${responseHeaders["access-control-allow-origin"]}`);
} else {
addResult("✔ CORS origin OK");
}
}
addResult("--Done--", ["ob-btn-config-head"]);
addResult("If you have some trouble with Connection-check even though all Config-check has been passed, please check your reverse proxy's configuration.", ["ob-btn-config-info"]);
Logger(`Checking configuration done`, LOG_LEVEL_INFO);
} catch (ex: any) {
if (ex?.status == 401) {
isSuccessful = false;
addResult(`❗ Access forbidden.`);
addResult(`We could not continue the test.`);
Logger(`Checking configuration done`, LOG_LEVEL_INFO);
} else {
Logger(`Checking configuration failed`, LOG_LEVEL_NOTICE);
Logger(ex);
isSuccessful = false;
}
}
return isSuccessful;
};
void addPane(containerEl, "Remote Configuration", "🛰️", 0, false).then((paneEl) => {
void addPanel(paneEl, "Remote Server").then((paneEl) => {
// const containerRemoteDatabaseEl = containerEl.createDiv();
@@ -1039,164 +1233,9 @@ However, your report is needed to stabilise this. I appreciate you for your grea
.setButtonText("Check")
.setDisabled(false)
.onClick(async () => {
const checkConfig = async () => {
Logger(`Checking database configuration`, LOG_LEVEL_INFO);
const emptyDiv = createDiv();
emptyDiv.innerHTML = "<span></span>";
checkResultDiv.replaceChildren(...[emptyDiv]);
const addResult = (msg: string, classes?: string[]) => {
const tmpDiv = createDiv();
tmpDiv.addClass("ob-btn-config-fix");
if (classes) {
tmpDiv.addClasses(classes);
}
tmpDiv.innerHTML = `${msg}`;
checkResultDiv.appendChild(tmpDiv);
};
try {
if (isCloudantURI(this.editingSettings.couchDB_URI)) {
Logger("This feature cannot be used with IBM Cloudant.", LOG_LEVEL_NOTICE);
return;
}
const r = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, window.origin);
const responseConfig = r.json;
const addConfigFixButton = (title: string, key: string, value: string) => {
const tmpDiv = createDiv();
tmpDiv.addClass("ob-btn-config-fix");
tmpDiv.innerHTML = `<label>${title}</label><button>Fix</button>`;
const x = checkResultDiv.appendChild(tmpDiv);
x.querySelector("button")?.addEventListener("click", () => {
fireAndForget(async () => {
Logger(`CouchDB Configuration: ${title} -> Set ${key} to ${value}`)
const res = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, undefined, key, value);
if (res.status == 200) {
Logger(`CouchDB Configuration: ${title} successfully updated`, LOG_LEVEL_NOTICE);
checkResultDiv.removeChild(x);
await checkConfig();
} else {
Logger(`CouchDB Configuration: ${title} failed`, LOG_LEVEL_NOTICE);
Logger(res.text, LOG_LEVEL_VERBOSE);
}
});
});
};
addResult("---Notice---", ["ob-btn-config-head"]);
addResult("If the server configuration is not persistent (e.g., running on docker), the values set from here will also be volatile. Once you are able to connect, please reflect the settings in the server's local.ini.", ["ob-btn-config-info"]);
addResult("--Config check--", ["ob-btn-config-head"]);
// Admin check
// for database creation and deletion
if (!(this.editingSettings.couchDB_USER in responseConfig.admins)) {
addResult(`⚠ You do not have administrative privileges.`);
} else {
addResult("✔ You have administrative privileges.");
}
// HTTP user-authorization check
if (responseConfig?.chttpd?.require_valid_user != "true") {
addResult("❗ chttpd.require_valid_user is wrong.");
addConfigFixButton("Set chttpd.require_valid_user = true", "chttpd/require_valid_user", "true");
} else {
addResult("✔ chttpd.require_valid_user is ok.");
}
if (responseConfig?.chttpd_auth?.require_valid_user != "true") {
addResult("❗ chttpd_auth.require_valid_user is wrong.");
addConfigFixButton("Set chttpd_auth.require_valid_user = true", "chttpd_auth/require_valid_user", "true");
} else {
addResult("✔ chttpd_auth.require_valid_user is ok.");
}
// HTTPD check
// Check Authentication header
if (!responseConfig?.httpd["WWW-Authenticate"]) {
addResult("❗ httpd.WWW-Authenticate is missing");
addConfigFixButton("Set httpd.WWW-Authenticate", "httpd/WWW-Authenticate", 'Basic realm="couchdb"');
} else {
addResult("✔ httpd.WWW-Authenticate is ok.");
}
if (responseConfig?.httpd?.enable_cors != "true") {
addResult("❗ httpd.enable_cors is wrong");
addConfigFixButton("Set httpd.enable_cors", "httpd/enable_cors", "true");
} else {
addResult("✔ httpd.enable_cors is ok.");
}
// If the server is not cloudant, configure request size
if (!isCloudantURI(this.editingSettings.couchDB_URI)) {
// REQUEST SIZE
if (Number(responseConfig?.chttpd?.max_http_request_size ?? 0) < 4294967296) {
addResult("❗ chttpd.max_http_request_size is low)");
addConfigFixButton("Set chttpd.max_http_request_size", "chttpd/max_http_request_size", "4294967296");
} else {
addResult("✔ chttpd.max_http_request_size is ok.");
}
if (Number(responseConfig?.couchdb?.max_document_size ?? 0) < 50000000) {
addResult("❗ couchdb.max_document_size is low)");
addConfigFixButton("Set couchdb.max_document_size", "couchdb/max_document_size", "50000000");
} else {
addResult("✔ couchdb.max_document_size is ok.");
}
}
// CORS check
// checking connectivity for mobile
if (responseConfig?.cors?.credentials != "true") {
addResult("❗ cors.credentials is wrong");
addConfigFixButton("Set cors.credentials", "cors/credentials", "true");
} else {
addResult("✔ cors.credentials is ok.");
}
const ConfiguredOrigins = ((responseConfig?.cors?.origins ?? "") + "").split(",");
if (responseConfig?.cors?.origins == "*" || (ConfiguredOrigins.indexOf("app://obsidian.md") !== -1 && ConfiguredOrigins.indexOf("capacitor://localhost") !== -1 && ConfiguredOrigins.indexOf("http://localhost") !== -1)) {
addResult("✔ cors.origins is ok.");
} else {
addResult("❗ cors.origins is wrong");
addConfigFixButton("Set cors.origins", "cors/origins", "app://obsidian.md,capacitor://localhost,http://localhost");
}
addResult("--Connection check--", ["ob-btn-config-head"]);
addResult(`Current origin:${window.location.origin}`);
// Request header check
const origins = [
"app://obsidian.md",
"capacitor://localhost",
"http://localhost"];
for (const org of origins) {
const rr = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, org);
const responseHeaders = Object.fromEntries(Object.entries(rr.headers)
.map((e) => {
e[0] = `${e[0]}`.toLowerCase();
return e;
}));
addResult(`Origin check:${org}`);
if (responseHeaders["access-control-allow-credentials"] != "true") {
addResult("❗ CORS is not allowing credentials");
} else {
addResult("✔ CORS credentials OK");
}
if (responseHeaders["access-control-allow-origin"] != org) {
addResult(`❗ CORS Origin is unmatched:${origin}->${responseHeaders["access-control-allow-origin"]}`);
} else {
addResult("✔ CORS origin OK");
}
}
addResult("--Done--", ["ob-btn-config-head"]);
addResult("If you have some trouble with Connection-check even though all Config-check has been passed, please check your reverse proxy's configuration.", ["ob-btn-config-info"]);
Logger(`Checking configuration done`, LOG_LEVEL_INFO);
} catch (ex: any) {
if (ex?.status == 401) {
addResult(`❗ Access forbidden.`);
addResult(`We could not continue the test.`);
Logger(`Checking configuration done`, LOG_LEVEL_INFO);
} else {
Logger(`Checking configuration failed`, LOG_LEVEL_NOTICE);
Logger(ex);
}
}
};
await checkConfig();
await checkConfig(checkResultDiv);
}));
const checkResultDiv = this.createEl(paneEl, "div", {
checkResultDiv = this.createEl(paneEl, "div", {
text: "",
});
@@ -1245,10 +1284,26 @@ However, your report is needed to stabilise this. I appreciate you for your grea
.setButtonText("Next")
.setCta()
.setDisabled(false)
.onClick(() => {
.onClick(async () => {
if (!await checkConfig(checkResultDiv)) {
if (await this.plugin.confirm.askYesNoDialog("The configuration check has failed. Do you want to continue anyway?", { defaultOption: "No", title: "Remote Configuration Check Failed" }) == "no") {
return;
}
}
const isEncryptionFullyEnabled = !this.editingSettings.encrypt || !this.editingSettings.usePathObfuscation;
if (isEncryptionFullyEnabled) {
if (await this.plugin.confirm.askYesNoDialog("Enabling End-to-End Encryption and Path Obfuscation is strongly recommended. Do you surely want to continue without encryption?", { defaultOption: "No", title: "Encryption is not enabled" }) == "no") {
return;
}
}
if (!this.editingSettings.encrypt) {
this.editingSettings.passphrase = "";
}
if (!await isPassphraseValid()) {
if (await this.plugin.confirm.askYesNoDialog("End-to-End encryption seems to have trouble. Do you surely want to continue with the current settings?", { defaultOption: "No", title: "Encryption has some trouble" }) == "no") {
return;
}
}
if (isCloudantURI(this.editingSettings.couchDB_URI)) {
this.editingSettings = { ...this.editingSettings, ...PREFERRED_SETTING_CLOUDANT };
} else if (this.editingSettings.remoteType == REMOTE_MINIO) {
@@ -1279,7 +1334,7 @@ However, your report is needed to stabilise this. I appreciate you for your grea
}
this.createEl(paneEl, "div", {
text: `Please select any preset to complete the wizard.`,
text: `Please select and apply any preset item to complete the wizard.`,
cls: "wizardOnly"
}).addClasses(["op-warn-info"]);
@@ -1362,9 +1417,12 @@ However, your report is needed to stabilise this. I appreciate you for your grea
await this.plugin.realizeSettingSyncMode();
await rebuildDB("localOnly");
// this.resetEditingSettings();
Logger("All done! Please set up subsequent devices with 'Copy current settings as a new setup URI' and 'Use the copied setup URI'.", LOG_LEVEL_NOTICE);
// await this.plugin.addOnSetup.command_copySetupURI();
eventHub.emitEvent(EVENT_REQUEST_COPY_SETUP_URI);
if (await this.plugin.confirm.askYesNoDialog(
"All done!, do you want to generate a setup URI to set up other devices?",
{ defaultOption: "Yes", title: "Congratulations!" }
) == "yes") {
eventHub.emitEvent(EVENT_REQUEST_COPY_SETUP_URI);
}
} else {
if (isNeedRebuildLocal() || isNeedRebuildRemote()) {
await confirmRebuild();
@@ -1714,7 +1772,7 @@ However, your report is needed to stabilise this. I appreciate you for your grea
});
void addPane(containerEl, "Hatch", "🧰", 50, false).then((paneEl) => {
void addPane(containerEl, "Hatch", "🧰", 50, true).then((paneEl) => {
// const hatchWarn = this.createEl(paneEl, "div", { text: `To stop the boot up sequence for fixing problems on databases, you can put redflag.md on top of your vault (Rebooting obsidian is required).` });
// hatchWarn.addClass("op-warn-info");
void addPanel(paneEl, "Reporting Issue").then((paneEl) => {
@@ -2269,7 +2327,7 @@ ${stringifyYaml(pluginConfig)}`;
const isRemoteLocked = () => this.plugin?.replicator?.remoteLocked;
// if (this.plugin?.replicator?.remoteLockedAndDeviceNotAccepted) {
this.createEl(paneEl, "div", {
text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization, and this device was not marked as 'resolved'. It caused by some operations like this. Re-initialized. Local database initialization should be required. Please back your vault up, reset the local database, and press 'Mark this device as resolved'. ",
text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization, and this device was not marked as 'resolved'. It caused by some operations like this. Re-initialized. Local database initialization should be required. Please back your vault up, reset the local database, and press 'Mark this device as resolved'. This warning kept showing until confirming the device is resolved by the replication.",
cls: "op-warn"
}, c => {
this.createEl(c, "button", {
@@ -2284,7 +2342,7 @@ ${stringifyYaml(pluginConfig)}`;
})
}, visibleOnly(isRemoteLockedAndDeviceNotAccepted));
this.createEl(paneEl, "div", {
text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization. (This device is marked 'resolved') When all your devices are marked 'resolved', unlock the database.",
text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization. (This device is marked 'resolved') When all your devices are marked 'resolved', unlock the database. This warning kept showing until confirming the device is resolved by the replication",
cls: "op-warn"
}, c => this.createEl(c, "button", {
text: "I'm ready, unlock the database", cls: "mod-warning"

View File

@@ -23,6 +23,44 @@ Thank you, and I hope your troubles will be resolved!
---
## 0.24.0.dev-rc4
### Improved
- The welcome message is now more simple to encourage the use of the Setup-URI.
- And the secondary message is also simpler to guide users to Minimal Setup.
- But Setup-URI will be recommended again, due to its importance.
- These dialogues contain a link to the documentation which can be clicked.
- The minimal setup is more minimal now. And, the setup is more user-friendly.
- Now the Configuration of the remote database is checked more robust, but we can ignore the warning and proceed with the setup.
- Before we are asked about each feature, we are asked if we want to use optional features in the first place.
- This is to prevent the user from being overwhelmed by the features.
- And made it clear that it is not recommended for new users.
- Many messages have been improved for better understanding.
- Ridiculous messages have been (carefully) refined.
- Dialogues are more informative and friendly.
- A lot of messages have been mostly rewritten, leveraging Markdown.
- Especially auto-closing dialogues are now explicitly labelled: `To stop the countdown, tap anywhere on the dialogue`.
- Now if the is plugin configured to ignore some events, we will get a chance to fix it, in addition to the warning.
- And why that has happened is also explained in the dialogue.
### Fixed
- While restarting the plug-in, the shown dialogues will be automatically closed to avoid unexpected behaviour.
- Replicated documents that the local device has configured to ignore are now correctly ignored.
- The chunks of the document on the local device during the first transfer will be created correctly.
- And why we should create them is now explained in the dialogue.
- If optional features have been enabled in the wizard, `Enable advanced features` will be toggled correctly.
### Changed
- Some default settings have been changed for easier new user experience.
- Preventing the meaningless migration of the settings.
### Tidied
- Commented-out codes have been gradually removed.
## 0.24.0.dev-rc3
### Fixed