feat(cloud-sync): add selective backup and restore
This commit is contained in:
1 parent
e432304dbc
commit
a75d343666
23 files changed
+2427
-216
No files matched your search
@@ -0,0 +1,431 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watch } from "vue";
|
||||||
|
import { useI18n } from "vue-i18n";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
|
import type { SyncCatalogItem, SyncSelection, SyncSnapshotCatalog } from "@/lib/backend/api";
|
||||||
|
import { transferCategoryForKey, type SettingsTransferCategoryId } from "@/lib/settings/settingsTransfer";
|
||||||
|
|
||||||
|
type BackupSettingsCategoryId = Exclude<SettingsTransferCategoryId, "other"> | "ai";
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
open: boolean;
|
||||||
|
mode: "upload" | "restore";
|
||||||
|
catalog: SyncSnapshotCatalog | null;
|
||||||
|
defaultIncludeSecrets?: boolean;
|
||||||
|
}>();
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
"update:open": [value: boolean];
|
||||||
|
confirm: [selection: SyncSelection];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const selection = ref<SyncSelection>(emptySelection());
|
||||||
|
const isRestore = computed(() => props.mode === "restore");
|
||||||
|
|
||||||
|
const backupSettingsCategoryOrder: readonly BackupSettingsCategoryId[] = ["appearance", "editor", "formatter", "navigation", "data", "shortcuts", "snippets", "ai"];
|
||||||
|
const backupSettingsCategoryLabelKeys: Record<BackupSettingsCategoryId, string> = {
|
||||||
|
appearance: "settings.appearanceTab",
|
||||||
|
ai: "settings.aiTab",
|
||||||
|
editor: "settings.editorTab",
|
||||||
|
formatter: "settings.sqlFormatterTab",
|
||||||
|
navigation: "settings.navigationTab",
|
||||||
|
data: "settings.dataTab",
|
||||||
|
shortcuts: "settings.shortcutsTab",
|
||||||
|
snippets: "settings.snippetsTab",
|
||||||
|
};
|
||||||
|
const nonSyncableEditorSettingIds = new Set(["updateNotificationsEnabled", "autoDownloadUpdates", "autoUpdateApp", "autoUpdateDrivers", "autoUpdateJdbc", "autoUpdateMcp", "autoUpdatePlugins", "updateDownloadSource", "ignoredUpdateVersion"]);
|
||||||
|
const desktopSettingCategories: Record<string, BackupSettingsCategoryId> = {
|
||||||
|
show_tray_icon: "appearance",
|
||||||
|
icon_theme: "appearance",
|
||||||
|
quit_on_close: "appearance",
|
||||||
|
close_action_prompted: "appearance",
|
||||||
|
sidebar_table_page_size: "navigation",
|
||||||
|
metadata_cache_max_memory_mb: "data",
|
||||||
|
duckdb_worker_process_isolation: "data",
|
||||||
|
duckdb_worker_max_processes: "data",
|
||||||
|
};
|
||||||
|
const editorSettingCategoryOverrides: Partial<Record<string, BackupSettingsCategoryId>> = {
|
||||||
|
aiFontFamily: "ai",
|
||||||
|
aiFontSize: "ai",
|
||||||
|
customThemeColors: "appearance",
|
||||||
|
appLayout: "appearance",
|
||||||
|
tabLayout: "appearance",
|
||||||
|
tabPlacement: "appearance",
|
||||||
|
tabGroupMode: "appearance",
|
||||||
|
tabGroupCustomizations: "appearance",
|
||||||
|
tabSortMode: "appearance",
|
||||||
|
compactTabTitle: "appearance",
|
||||||
|
executeModeDefaultVersion: "editor",
|
||||||
|
globalConnectTimeoutSecs: "editor",
|
||||||
|
connectTimeoutInheritConnectionIds: "editor",
|
||||||
|
globalQueryTimeoutSecs: "editor",
|
||||||
|
queryTimeoutInheritConnectionIds: "editor",
|
||||||
|
timeoutInheritanceMigrationVersion: "editor",
|
||||||
|
blockDangerousRedisCommands: "editor",
|
||||||
|
tableDdlWordWrap: "editor",
|
||||||
|
refreshDdlOnOpen: "editor",
|
||||||
|
excludeDdlStorage: "editor",
|
||||||
|
sqlSemanticDiagnosticsEnabled: "editor",
|
||||||
|
infiniteScrollMaxRows: "data",
|
||||||
|
tableFontSize: "data",
|
||||||
|
mongoViewMode: "data",
|
||||||
|
dataGridMultiRowTranspose: "data",
|
||||||
|
dataGridHideNullColumns: "data",
|
||||||
|
dataGridBooleanDisplayMode: "data",
|
||||||
|
numericColumnRightAlign: "data",
|
||||||
|
structureEditorDensity: "data",
|
||||||
|
tableInfoActiveTab: "data",
|
||||||
|
tableInfoDrawerPinned: "data",
|
||||||
|
tableInfoDrawerWidth: "data",
|
||||||
|
cellDetailDrawerWidth: "data",
|
||||||
|
cellDetailPanelLayout: "data",
|
||||||
|
cellDetailJsonFormatted: "data",
|
||||||
|
cellDetailMetadataCollapsed: "data",
|
||||||
|
localFilterPopoverWidth: "data",
|
||||||
|
dataGridRenderMode: "data",
|
||||||
|
dataGridSearchMode: "data",
|
||||||
|
dataGridRowNumberMode: "data",
|
||||||
|
dataGridCopyExtractor: "data",
|
||||||
|
dataGridExtractorOptions: "data",
|
||||||
|
dataGridExtractorOptionsMigrationVersion: "data",
|
||||||
|
resultRunDisplayMode: "data",
|
||||||
|
dataGridTextFilterPanelHeight: "data",
|
||||||
|
columnWidthDensity: "data",
|
||||||
|
dataGridColumnWidthMode: "data",
|
||||||
|
sidebarConnectionSortMode: "navigation",
|
||||||
|
sidebarTableSearchLocal: "navigation",
|
||||||
|
sidebarGlobalSearchLocal: "navigation",
|
||||||
|
sidebarBrowseObjectsOnDatabaseActivationMigrationVersion: "navigation",
|
||||||
|
rememberedConnectionDatabases: "navigation",
|
||||||
|
sidebarShowConnectionNotes: "navigation",
|
||||||
|
customColumnFormatters: "data",
|
||||||
|
columnFormatters: "data",
|
||||||
|
pluginShortcuts: "shortcuts",
|
||||||
|
objectBrowserShowCheckbox: "data",
|
||||||
|
objectBrowserViewMode: "data",
|
||||||
|
};
|
||||||
|
|
||||||
|
function editorSettingCategory(id: string): BackupSettingsCategoryId {
|
||||||
|
const transferCategory = transferCategoryForKey(id);
|
||||||
|
if (transferCategory === "other") return "editor";
|
||||||
|
return editorSettingCategoryOverrides[id] ?? transferCategory ?? "editor";
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectableDesktopSettings(catalog: SyncSnapshotCatalog): SyncCatalogItem[] {
|
||||||
|
return catalog.desktopSettings.filter((item) => Object.prototype.hasOwnProperty.call(desktopSettingCategories, item.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectableEditorSettings(catalog: SyncSnapshotCatalog): SyncCatalogItem[] {
|
||||||
|
return catalog.editorSettings.filter((item) => !nonSyncableEditorSettingIds.has(item.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectedSettings(savedIds: string[] | undefined, items: SyncCatalogItem[]): string[] {
|
||||||
|
if (savedIds === undefined) return items.map((item) => item.id);
|
||||||
|
const saved = new Set(savedIds);
|
||||||
|
return items.filter((item) => saved.has(item.id)).map((item) => item.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const backupSettingsCategories = computed(() => {
|
||||||
|
const catalog = props.catalog;
|
||||||
|
if (!catalog) return [];
|
||||||
|
const groups = new Map<BackupSettingsCategoryId, { desktop: SyncCatalogItem[]; editor: SyncCatalogItem[] }>();
|
||||||
|
for (const category of backupSettingsCategoryOrder) groups.set(category, { desktop: [], editor: [] });
|
||||||
|
for (const item of selectableDesktopSettings(catalog)) groups.get(desktopSettingCategories[item.id])?.desktop.push(item);
|
||||||
|
for (const item of selectableEditorSettings(catalog)) groups.get(editorSettingCategory(item.id))?.editor.push(item);
|
||||||
|
return backupSettingsCategoryOrder.flatMap((category) => {
|
||||||
|
const group = groups.get(category)!;
|
||||||
|
const desktopSelected = group.desktop.filter((item) => selection.value.desktopSettings?.includes(item.id)).length;
|
||||||
|
const editorSelected = group.editor.filter((item) => selection.value.editorSettings?.includes(item.id)).length;
|
||||||
|
const total = group.desktop.length + group.editor.length;
|
||||||
|
if (!total) return [];
|
||||||
|
return [{ id: category, labelKey: backupSettingsCategoryLabelKeys[category], desktop: group.desktop, editor: group.editor, total, selected: desktopSelected + editorSelected }];
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function emptySelection(): SyncSelection {
|
||||||
|
return {
|
||||||
|
connections: [],
|
||||||
|
connectionSecrets: [],
|
||||||
|
tunnelProfiles: [],
|
||||||
|
tunnelSecrets: [],
|
||||||
|
savedSqlFolders: [],
|
||||||
|
savedSqlFiles: [],
|
||||||
|
desktopSettings: [],
|
||||||
|
editorSettings: [],
|
||||||
|
aiConfigs: [],
|
||||||
|
pluginUiStorage: [],
|
||||||
|
sidebarLayout: false,
|
||||||
|
pinnedTreeNodeIds: false,
|
||||||
|
includeSecrets: false,
|
||||||
|
syncCredentials: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetFromCatalog() {
|
||||||
|
const catalog = props.catalog;
|
||||||
|
if (!catalog) return;
|
||||||
|
const saved = catalog.selection;
|
||||||
|
const desktopSettings = selectableDesktopSettings(catalog);
|
||||||
|
const editorSettings = selectableEditorSettings(catalog);
|
||||||
|
selection.value = {
|
||||||
|
...emptySelection(),
|
||||||
|
connections: saved?.connections ?? catalog.connections.map((item) => item.id),
|
||||||
|
connectionSecrets: saved?.connectionSecrets ?? (catalog.hasEncryptedSecrets ? catalog.connectionSecrets : []),
|
||||||
|
tunnelProfiles: saved?.tunnelProfiles ?? catalog.tunnelProfiles.map((item) => item.id),
|
||||||
|
tunnelSecrets: saved?.tunnelSecrets ?? (catalog.hasEncryptedSecrets ? catalog.tunnelSecrets : []),
|
||||||
|
savedSqlFolders: saved?.savedSqlFolders ?? catalog.savedSqlFolders.map((item) => item.id),
|
||||||
|
savedSqlFiles: saved?.savedSqlFiles ?? catalog.savedSqlFiles.map((item) => item.id),
|
||||||
|
desktopSettings: selectedSettings(saved?.desktopSettings, desktopSettings),
|
||||||
|
editorSettings: selectedSettings(saved?.editorSettings, editorSettings),
|
||||||
|
aiConfigs: saved?.aiConfigs ?? (catalog.aiConfigsLocked ? undefined : catalog.aiConfigs.map((item) => item.id)),
|
||||||
|
pluginUiStorage: saved?.pluginUiStorage ?? (catalog.pluginUiStorageLocked ? undefined : catalog.pluginUiStorage),
|
||||||
|
sidebarLayout: saved?.sidebarLayout ?? catalog.hasSidebarLayout,
|
||||||
|
pinnedTreeNodeIds: saved?.pinnedTreeNodeIds ?? catalog.hasPinnedTreeNodeIds,
|
||||||
|
includeSecrets: saved?.includeSecrets ?? (isRestore.value ? catalog.hasEncryptedSecrets : !!props.defaultIncludeSecrets),
|
||||||
|
syncCredentials: saved?.syncCredentials ?? (isRestore.value ? catalog.hasEncryptedSecrets : !!props.defaultIncludeSecrets),
|
||||||
|
};
|
||||||
|
if (selection.value.includeSecrets && !saved) onSecretsChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => [props.open, props.catalog] as const,
|
||||||
|
([open]) => {
|
||||||
|
if (open) resetFromCatalog();
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
function ids(key: "connections" | "connectionSecrets" | "tunnelProfiles" | "tunnelSecrets" | "savedSqlFolders" | "savedSqlFiles" | "desktopSettings" | "editorSettings" | "aiConfigs") {
|
||||||
|
return selection.value[key] ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleId(key: "connections" | "connectionSecrets" | "tunnelProfiles" | "tunnelSecrets" | "savedSqlFolders" | "savedSqlFiles" | "desktopSettings" | "editorSettings" | "aiConfigs", id: string) {
|
||||||
|
const current = ids(key);
|
||||||
|
selection.value[key] = current.includes(id) ? current.filter((item) => item !== id) : [...current, id];
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleAll(key: "connections" | "tunnelProfiles" | "savedSqlFolders" | "savedSqlFiles" | "desktopSettings" | "editorSettings" | "aiConfigs", items: SyncCatalogItem[]) {
|
||||||
|
const current = ids(key);
|
||||||
|
selection.value[key] = current.length === items.length ? [] : items.map((item) => item.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleSettingsCategory(category: BackupSettingsCategoryId) {
|
||||||
|
const catalog = props.catalog;
|
||||||
|
const group = backupSettingsCategories.value.find((item) => item.id === category);
|
||||||
|
if (!catalog || !group) return;
|
||||||
|
const include = group.selected !== group.total;
|
||||||
|
const desktopIds = new Set(selectedSettings(selection.value.desktopSettings, selectableDesktopSettings(catalog)));
|
||||||
|
const editorIds = new Set(selectedSettings(selection.value.editorSettings, selectableEditorSettings(catalog)));
|
||||||
|
for (const item of group.desktop) {
|
||||||
|
if (include) desktopIds.add(item.id);
|
||||||
|
else desktopIds.delete(item.id);
|
||||||
|
}
|
||||||
|
for (const item of group.editor) {
|
||||||
|
if (include) editorIds.add(item.id);
|
||||||
|
else editorIds.delete(item.id);
|
||||||
|
}
|
||||||
|
selection.value.desktopSettings = [...desktopIds];
|
||||||
|
selection.value.editorSettings = [...editorIds];
|
||||||
|
}
|
||||||
|
|
||||||
|
function togglePluginItem(pluginId: string, key: string) {
|
||||||
|
const current = selection.value.pluginUiStorage ?? [];
|
||||||
|
const exists = current.some((item) => item.pluginId === pluginId && item.key === key);
|
||||||
|
selection.value.pluginUiStorage = exists ? current.filter((item) => item.pluginId !== pluginId || item.key !== key) : [...current, props.catalog?.pluginUiStorage.find((item) => item.pluginId === pluginId && item.key === key)!];
|
||||||
|
}
|
||||||
|
|
||||||
|
function togglePluginAll() {
|
||||||
|
if (props.catalog?.pluginUiStorageLocked) {
|
||||||
|
selection.value.pluginUiStorage = selection.value.pluginUiStorage === undefined ? [] : undefined;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const all = props.catalog?.pluginUiStorage ?? [];
|
||||||
|
selection.value.pluginUiStorage = selection.value.pluginUiStorage?.length === all.length ? [] : [...all];
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleAllAiConfigs() {
|
||||||
|
if (props.catalog?.aiConfigsLocked) {
|
||||||
|
selection.value.aiConfigs = selection.value.aiConfigs === undefined ? [] : undefined;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toggleAll("aiConfigs", props.catalog?.aiConfigs ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSecretsChanged() {
|
||||||
|
if (!selection.value.includeSecrets || !props.catalog) return;
|
||||||
|
if (!selection.value.connectionSecrets?.length) selection.value.connectionSecrets = [...props.catalog.connectionSecrets];
|
||||||
|
if (!selection.value.tunnelSecrets?.length) selection.value.tunnelSecrets = [...props.catalog.tunnelSecrets];
|
||||||
|
if (!selection.value.aiConfigs?.length && props.catalog.aiConfigs.length) selection.value.aiConfigs = props.catalog.aiConfigs.map((item) => item.id);
|
||||||
|
if (!selection.value.pluginUiStorage?.length && !props.catalog.pluginUiStorageLocked) selection.value.pluginUiStorage = [...props.catalog.pluginUiStorage];
|
||||||
|
selection.value.syncCredentials = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function checked(key: "connections" | "connectionSecrets" | "tunnelProfiles" | "tunnelSecrets" | "savedSqlFolders" | "savedSqlFiles" | "desktopSettings" | "editorSettings" | "aiConfigs", id: string) {
|
||||||
|
return ids(key).includes(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmSelection() {
|
||||||
|
if (props.catalog) {
|
||||||
|
selection.value.desktopSettings = selectedSettings(selection.value.desktopSettings, selectableDesktopSettings(props.catalog));
|
||||||
|
selection.value.editorSettings = selectedSettings(selection.value.editorSettings, selectableEditorSettings(props.catalog));
|
||||||
|
}
|
||||||
|
emit("confirm", structuredClone(selection.value));
|
||||||
|
emit("update:open", false);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Dialog :open="open" @update:open="emit('update:open', $event)">
|
||||||
|
<DialogContent class="flex max-h-[min(88vh,calc(var(--dbx-viewport-height)-4rem))] flex-col gap-0 overflow-hidden border border-border !bg-background-solid p-0 text-foreground shadow-2xl !backdrop-blur-none sm:max-w-[760px]">
|
||||||
|
<DialogHeader class="shrink-0 border-b px-5 py-4">
|
||||||
|
<DialogTitle>{{ isRestore ? t("settings.syncSelectionRestoreTitle") : t("settings.syncSelectionUploadTitle") }}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{{ isRestore ? t("settings.syncSelectionRestoreNote") : t("settings.syncSelectionBackupNote") }}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div v-if="catalog" class="min-h-0 flex-1 space-y-2 overflow-y-auto px-5 py-4">
|
||||||
|
<details open class="border-b pb-2">
|
||||||
|
<summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">
|
||||||
|
<input :checked="selection.connections?.length === catalog.connections.length" type="checkbox" class="size-4 accent-primary" @click.stop.prevent="toggleAll('connections', catalog.connections)" />
|
||||||
|
<span>{{ t("settings.syncSelectionConnections") }}</span>
|
||||||
|
<span class="ml-auto text-xs text-muted-foreground">{{ selection.connections?.length ?? 0 }}/{{ catalog.connections.length }}</span>
|
||||||
|
</summary>
|
||||||
|
<div class="ml-6 space-y-1 pb-2">
|
||||||
|
<div v-for="item in catalog.connections" :key="item.id" class="py-1">
|
||||||
|
<label class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input :checked="checked('connections', item.id)" type="checkbox" class="size-4 accent-primary" @change="toggleId('connections', item.id)" />
|
||||||
|
<span class="min-w-0 truncate">{{ item.label || item.id }}</span>
|
||||||
|
</label>
|
||||||
|
<label v-if="catalog.connectionSecrets.includes(item.id)" class="ml-6 flex min-h-7 items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<input :checked="checked('connectionSecrets', item.id)" :disabled="!selection.includeSecrets || !selection.connections?.includes(item.id)" type="checkbox" class="size-3.5 accent-primary" @change="toggleId('connectionSecrets', item.id)" />
|
||||||
|
<span>{{ t("settings.syncSelectionConnectionSecrets") }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p v-if="!catalog.connections.length" class="py-1 text-xs text-muted-foreground">{{ t("settings.syncSelectionNoConnections") }}</p>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details open class="border-b pb-2">
|
||||||
|
<summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">
|
||||||
|
<input :checked="selection.tunnelProfiles?.length === catalog.tunnelProfiles.length" type="checkbox" class="size-4 accent-primary" @click.stop.prevent="toggleAll('tunnelProfiles', catalog.tunnelProfiles)" />
|
||||||
|
<span>{{ t("settings.syncSelectionTunnels") }}</span>
|
||||||
|
<span class="ml-auto text-xs text-muted-foreground">{{ selection.tunnelProfiles?.length ?? 0 }}/{{ catalog.tunnelProfiles.length }}</span>
|
||||||
|
</summary>
|
||||||
|
<div class="ml-6 space-y-1 pb-2">
|
||||||
|
<div v-for="item in catalog.tunnelProfiles" :key="item.id" class="py-1">
|
||||||
|
<label class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input :checked="checked('tunnelProfiles', item.id)" type="checkbox" class="size-4 accent-primary" @change="toggleId('tunnelProfiles', item.id)" />
|
||||||
|
<span class="min-w-0 truncate">{{ item.label || item.id }}</span>
|
||||||
|
</label>
|
||||||
|
<label v-if="catalog.tunnelSecrets.includes(item.id)" class="ml-6 flex min-h-7 items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<input :checked="checked('tunnelSecrets', item.id)" :disabled="!selection.includeSecrets || !selection.tunnelProfiles?.includes(item.id)" type="checkbox" class="size-3.5 accent-primary" @change="toggleId('tunnelSecrets', item.id)" />
|
||||||
|
<span>{{ t("settings.syncSelectionTunnelSecrets") }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p v-if="!catalog.tunnelProfiles.length" class="py-1 text-xs text-muted-foreground">{{ t("settings.syncSelectionNoTunnels") }}</p>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details open class="border-b pb-2">
|
||||||
|
<summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">{{ t("settings.syncSelectionSavedSql") }}</summary>
|
||||||
|
<div class="ml-6 space-y-2 pb-2">
|
||||||
|
<div>
|
||||||
|
<button type="button" class="mb-1 text-xs font-medium text-muted-foreground hover:text-foreground" @click="toggleAll('savedSqlFolders', catalog.savedSqlFolders)">
|
||||||
|
{{ t("settings.syncSelectionFolders") }} ({{ selection.savedSqlFolders?.length ?? 0 }}/{{ catalog.savedSqlFolders.length }})
|
||||||
|
</button>
|
||||||
|
<label v-for="item in catalog.savedSqlFolders" :key="item.id" class="flex min-h-7 items-center gap-2 pl-1 text-sm">
|
||||||
|
<input :checked="checked('savedSqlFolders', item.id)" type="checkbox" class="size-4 accent-primary" @change="toggleId('savedSqlFolders', item.id)" />
|
||||||
|
<span class="min-w-0 truncate">{{ item.label || item.id }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<button type="button" class="mb-1 text-xs font-medium text-muted-foreground hover:text-foreground" @click="toggleAll('savedSqlFiles', catalog.savedSqlFiles)">{{ t("settings.syncSelectionFiles") }} ({{ selection.savedSqlFiles?.length ?? 0 }}/{{ catalog.savedSqlFiles.length }})</button>
|
||||||
|
<label v-for="item in catalog.savedSqlFiles" :key="item.id" class="flex min-h-7 items-center gap-2 pl-1 text-sm">
|
||||||
|
<input :checked="checked('savedSqlFiles', item.id)" type="checkbox" class="size-4 accent-primary" @change="toggleId('savedSqlFiles', item.id)" />
|
||||||
|
<span class="min-w-0 truncate">{{ item.label || item.id }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details open class="border-b pb-2">
|
||||||
|
<summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">{{ t("settings.syncSelectionPersonalSettings") }}</summary>
|
||||||
|
<div class="ml-6 space-y-1 py-2">
|
||||||
|
<label v-for="category in backupSettingsCategories" :key="category.id" class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input :checked="category.total > 0 && category.selected === category.total" type="checkbox" class="size-4 accent-primary" @change="toggleSettingsCategory(category.id)" />
|
||||||
|
<span>{{ t(category.labelKey) }}</span>
|
||||||
|
<span class="ml-auto text-xs text-muted-foreground">{{ category.selected }}/{{ category.total }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details open class="border-b pb-2">
|
||||||
|
<summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">
|
||||||
|
<input v-model="selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @click.stop @change="onSecretsChanged" />
|
||||||
|
<span>{{ t("settings.syncSelectionEncrypted") }}</span>
|
||||||
|
</summary>
|
||||||
|
<div class="ml-6 space-y-2 pb-2">
|
||||||
|
<label class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input v-model="selection.syncCredentials" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" />
|
||||||
|
<span>{{ t("settings.syncSelectionSyncCredentials") }}</span>
|
||||||
|
</label>
|
||||||
|
<div>
|
||||||
|
<label v-if="catalog.aiConfigsLocked" class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input :checked="selection.aiConfigs === undefined" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @change="toggleAllAiConfigs" />
|
||||||
|
<span>{{ t("settings.syncSelectionAiLocked") }}</span>
|
||||||
|
</label>
|
||||||
|
<template v-else>
|
||||||
|
<button type="button" class="mb-1 text-xs font-medium text-muted-foreground hover:text-foreground" :disabled="!selection.includeSecrets" @click="toggleAllAiConfigs">
|
||||||
|
{{ t("settings.syncSelectionAiConfigs") }} ({{ selection.aiConfigs?.length ?? 0 }}/{{ catalog.aiConfigs.length }})
|
||||||
|
</button>
|
||||||
|
<label v-for="item in catalog.aiConfigs" :key="item.id" class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input :checked="checked('aiConfigs', item.id)" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @change="toggleId('aiConfigs', item.id)" />
|
||||||
|
<span class="min-w-0 truncate">{{ item.label || item.id }}</span>
|
||||||
|
</label>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label v-if="catalog.pluginUiStorageLocked" class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input :checked="selection.pluginUiStorage === undefined" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @change="togglePluginAll" />
|
||||||
|
<span>{{ t("settings.syncSelectionPluginLocked") }}</span>
|
||||||
|
</label>
|
||||||
|
<template v-else>
|
||||||
|
<button type="button" class="mb-1 text-xs font-medium text-muted-foreground hover:text-foreground" :disabled="!selection.includeSecrets" @click="togglePluginAll">
|
||||||
|
{{ t("settings.syncSelectionPluginData") }} ({{ selection.pluginUiStorage?.length ?? 0 }}/{{ catalog.pluginUiStorage.length }})
|
||||||
|
</button>
|
||||||
|
<label v-for="item in catalog.pluginUiStorage" :key="item.pluginId + '/' + item.key" class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input :checked="selection.pluginUiStorage?.some((entry) => entry.pluginId === item.pluginId && entry.key === item.key)" :disabled="!selection.includeSecrets" type="checkbox" class="size-4 accent-primary" @change="togglePluginItem(item.pluginId, item.key)" />
|
||||||
|
<span class="min-w-0 truncate">{{ item.pluginName || item.pluginId }} / {{ item.key }}</span>
|
||||||
|
</label>
|
||||||
|
<p v-if="!catalog.pluginUiStorage.length" class="text-xs text-muted-foreground">{{ t("settings.syncSelectionNoPluginData") }}</p>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<p v-if="!catalog.hasEncryptedSecrets && isRestore" class="text-xs text-muted-foreground">{{ t("settings.syncSelectionNoEncrypted") }}</p>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details open class="pb-1">
|
||||||
|
<summary class="flex cursor-pointer list-none items-center gap-2 py-2 text-sm font-medium">{{ t("settings.syncSelectionWorkspace") }}</summary>
|
||||||
|
<div class="ml-6 space-y-1 pb-2">
|
||||||
|
<label class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input v-model="selection.sidebarLayout" :disabled="!catalog.hasSidebarLayout" type="checkbox" class="size-4 accent-primary" />
|
||||||
|
<span>{{ t("settings.syncSelectionSidebar") }}</span>
|
||||||
|
</label>
|
||||||
|
<label class="flex min-h-7 items-center gap-2 text-sm">
|
||||||
|
<input v-model="selection.pinnedTreeNodeIds" :disabled="!catalog.hasPinnedTreeNodeIds" type="checkbox" class="size-4 accent-primary" />
|
||||||
|
<span>{{ t("settings.syncSelectionPinned") }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter class="mx-0 mb-0 shrink-0 border-t px-5 pb-4 pt-3">
|
||||||
|
<Button variant="outline" @click="emit('update:open', false)">{{ t("settings.syncSelectionCancel") }}</Button>
|
||||||
|
<Button :disabled="!catalog" @click="confirmSelection">{{ isRestore ? t("settings.syncSelectionRestoreAction") : t("settings.syncSelectionUploadAction") }}</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</template>
|
||||||
@@ -124,6 +124,7 @@ import ThemeCustomizerDialog from "./ThemeCustomizerDialog.vue";
|
|||||||
import DataGridTypeColorSchemeDialog from "@/components/grid/DataGridTypeColorSchemeDialog.vue";
|
import DataGridTypeColorSchemeDialog from "@/components/grid/DataGridTypeColorSchemeDialog.vue";
|
||||||
import { DATA_GRID_TYPE_COLOR_SCHEME_AUTO_ID, cloneDataGridTypeColorSchemes, type DataGridTypeColorScheme } from "@/lib/dataGrid/dataGridTypeColorScheme";
|
import { DATA_GRID_TYPE_COLOR_SCHEME_AUTO_ID, cloneDataGridTypeColorSchemes, type DataGridTypeColorScheme } from "@/lib/dataGrid/dataGridTypeColorScheme";
|
||||||
import TunnelProfileManager from "@/components/connection/TunnelProfileManager.vue";
|
import TunnelProfileManager from "@/components/connection/TunnelProfileManager.vue";
|
||||||
|
import CloudSyncSelectionDialog from "@/components/editor/CloudSyncSelectionDialog.vue";
|
||||||
import DangerConfirmDialog from "./DangerConfirmDialog.vue";
|
import DangerConfirmDialog from "./DangerConfirmDialog.vue";
|
||||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||||
import { useTheme } from "@/composables/useTheme";
|
import { useTheme } from "@/composables/useTheme";
|
||||||
@@ -149,6 +150,7 @@ import {
|
|||||||
forgetWebdavSavedPassword,
|
forgetWebdavSavedPassword,
|
||||||
getAppSupportInfo,
|
getAppSupportInfo,
|
||||||
checkBackgroundImage,
|
checkBackgroundImage,
|
||||||
|
cloudSyncLocalCatalog,
|
||||||
clearBackgroundImage,
|
clearBackgroundImage,
|
||||||
saveBackgroundImage,
|
saveBackgroundImage,
|
||||||
loadMaxAgentTurns,
|
loadMaxAgentTurns,
|
||||||
@@ -163,12 +165,14 @@ import {
|
|||||||
saveSnippetSyncId,
|
saveSnippetSyncId,
|
||||||
retrySnippetLegacyCleanup,
|
retrySnippetLegacyCleanup,
|
||||||
snippetSyncDownload,
|
snippetSyncDownload,
|
||||||
|
snippetSyncInspect,
|
||||||
snippetSyncSettings,
|
snippetSyncSettings,
|
||||||
snippetSyncTest,
|
snippetSyncTest,
|
||||||
snippetSyncUpload,
|
snippetSyncUpload,
|
||||||
snippetTokenStatus,
|
snippetTokenStatus,
|
||||||
webdavPasswordStatus,
|
webdavPasswordStatus,
|
||||||
webdavSyncDownload,
|
webdavSyncDownload,
|
||||||
|
webdavSyncInspect,
|
||||||
webdavSyncSecretsStatus,
|
webdavSyncSecretsStatus,
|
||||||
webdavSyncTest,
|
webdavSyncTest,
|
||||||
webdavSyncUpload,
|
webdavSyncUpload,
|
||||||
@@ -181,6 +185,8 @@ import {
|
|||||||
type McpServerStatus,
|
type McpServerStatus,
|
||||||
type SnippetProvider,
|
type SnippetProvider,
|
||||||
type SnippetSyncConfig,
|
type SnippetSyncConfig,
|
||||||
|
type SyncSelection,
|
||||||
|
type SyncSnapshotCatalog,
|
||||||
type WebDavConfig,
|
type WebDavConfig,
|
||||||
} from "@/lib/backend/api";
|
} from "@/lib/backend/api";
|
||||||
import { eventToModifierOnlyShortcut, eventToShortcut } from "@/lib/editor/keyboardShortcuts";
|
import { eventToModifierOnlyShortcut, eventToShortcut } from "@/lib/editor/keyboardShortcuts";
|
||||||
@@ -295,7 +301,7 @@ import {
|
|||||||
type ToolbarVisibilityItem,
|
type ToolbarVisibilityItem,
|
||||||
} from "@/lib/settings/settingsSearch";
|
} from "@/lib/settings/settingsSearch";
|
||||||
import { LOCALE_OPTIONS } from "@/lib/app/localeOptions";
|
import { LOCALE_OPTIONS } from "@/lib/app/localeOptions";
|
||||||
import { DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES, DEFAULT_WEB_DAV_REMOTE_PATH, normalizedWebDavAutoUploadInterval, writeWebDavAutoUploadFields } from "@/lib/webdav/webdavAutoUploadConfig";
|
import { DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES, DEFAULT_WEB_DAV_REMOTE_PATH, normalizedWebDavAutoUploadInterval, writeWebDavAutoUploadFields, writeWebDavBackupSelection } from "@/lib/webdav/webdavAutoUploadConfig";
|
||||||
import { apiUrl, webPath } from "@/lib/common/webPath";
|
import { apiUrl, webPath } from "@/lib/common/webPath";
|
||||||
import { DEFAULT_DATA_GRID_FONT_FAMILY, DEFAULT_UI_FONT_FAMILY, normalizeCustomFontFamilyInput, readableFontFamily, SYSTEM_UI_FONT_FAMILY } from "@/lib/app/appFonts";
|
import { DEFAULT_DATA_GRID_FONT_FAMILY, DEFAULT_UI_FONT_FAMILY, normalizeCustomFontFamilyInput, readableFontFamily, SYSTEM_UI_FONT_FAMILY } from "@/lib/app/appFonts";
|
||||||
import { buildFontFamilyOptions, displayFontFamily, isPresetFontFamily, loadSystemFontNames } from "@/lib/app/fontFamilyOptions";
|
import { buildFontFamilyOptions, displayFontFamily, isPresetFontFamily, loadSystemFontNames } from "@/lib/app/fontFamilyOptions";
|
||||||
@@ -4215,6 +4221,9 @@ const webdavBusy = ref<"" | "test" | "upload" | "download">("");
|
|||||||
const webdavMessage = ref("");
|
const webdavMessage = ref("");
|
||||||
const webdavError = ref(false);
|
const webdavError = ref(false);
|
||||||
const syncMethodTab = ref<"webdav" | "snippet">("webdav");
|
const syncMethodTab = ref<"webdav" | "snippet">("webdav");
|
||||||
|
const syncSelectionOpen = ref(false);
|
||||||
|
const syncSelectionMode = ref<"upload" | "restore">("upload");
|
||||||
|
const syncSelectionCatalog = ref<SyncSnapshotCatalog | null>(null);
|
||||||
|
|
||||||
const snippetProvider = ref<SnippetProvider>((localStorage.getItem("dbx-snippet-provider") as SnippetProvider) || "github");
|
const snippetProvider = ref<SnippetProvider>((localStorage.getItem("dbx-snippet-provider") as SnippetProvider) || "github");
|
||||||
const snippetInstanceUrl = ref(localStorage.getItem("dbx-gitlab-instance-url") || "https://gitlab.com");
|
const snippetInstanceUrl = ref(localStorage.getItem("dbx-gitlab-instance-url") || "https://gitlab.com");
|
||||||
@@ -4236,13 +4245,13 @@ const legacySnippetId = ref("");
|
|||||||
const pendingLegacyCleanupId = ref("");
|
const pendingLegacyCleanupId = ref("");
|
||||||
const snippetSyncSettingsLoading = ref(true);
|
const snippetSyncSettingsLoading = ref(true);
|
||||||
|
|
||||||
const webdavReady = computed(() => !!webdavEndpoint.value.trim() && !webdavBusy.value && (!webdavSyncSecrets.value || !!webdavSecretsPassphrase.value.trim() || webdavHasSavedSecretsPassphrase.value));
|
const webdavReady = computed(() => !!webdavEndpoint.value.trim() && !webdavBusy.value);
|
||||||
const snippetReady = computed(() => !snippetSyncSettingsLoading.value && !snippetBusy.value && (snippetProvider.value !== "gitlab" || (!snippetInstanceError.value && snippetInstanceUrl.value === activeSnippetInstanceUrl.value)) && (!!snippetToken.value.trim() || snippetHasSavedToken.value));
|
const snippetReady = computed(() => !snippetSyncSettingsLoading.value && !snippetBusy.value && (snippetProvider.value !== "gitlab" || (!snippetInstanceError.value && snippetInstanceUrl.value === activeSnippetInstanceUrl.value)) && (!!snippetToken.value.trim() || snippetHasSavedToken.value));
|
||||||
const snippetUploadReady = computed(() => snippetReady.value && !!snippetPassphrase.value.trim() && (!snippetIncludeSecrets.value || !!snippetSecretsPassphrase.value.trim()));
|
const snippetUploadReady = computed(() => snippetReady.value && !!snippetPassphrase.value.trim());
|
||||||
// Legacy plaintext snippets have no outer encryption password. Let the
|
// Legacy plaintext snippets have no outer encryption password. Let the
|
||||||
// backend require one only after it detects an encrypted envelope so those
|
// backend require one only after it detects an encrypted envelope so those
|
||||||
// snapshots remain recoverable for migration.
|
// snapshots remain recoverable for migration.
|
||||||
const snippetDownloadReady = computed(() => snippetReady.value && (!snippetRestoreSecrets.value || !!snippetSecretsPassphrase.value.trim()));
|
const snippetDownloadReady = computed(() => snippetReady.value);
|
||||||
|
|
||||||
function currentSnippetConfig(replaceLegacySnippet = false): SnippetSyncConfig {
|
function currentSnippetConfig(replaceLegacySnippet = false): SnippetSyncConfig {
|
||||||
return {
|
return {
|
||||||
@@ -4373,13 +4382,10 @@ async function uploadSnippetSnapshot() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await runSnippetAction("upload", async () => {
|
await runSnippetAction("upload", async () => {
|
||||||
const summary = await snippetSyncUpload(currentSnippetConfig(), settingsStore.editorSettings, snippetPassphrase.value, snippetIncludeSecrets.value, snippetIncludeSecrets.value ? snippetSecretsPassphrase.value : undefined);
|
syncSelectionCatalog.value = await cloudSyncLocalCatalog(settingsStore.editorSettings);
|
||||||
snippetId.value = summary.snippetId;
|
syncSelectionMode.value = "upload";
|
||||||
await persistSnippetSyncId();
|
syncSelectionOpen.value = true;
|
||||||
return t("settings.syncSnippetUploadSuccess", {
|
return "";
|
||||||
bytes: summary.bytes,
|
|
||||||
id: summary.snippetId,
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4420,24 +4426,12 @@ async function retryLegacySnippetCleanup() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function downloadSnippetSnapshot() {
|
async function downloadSnippetSnapshot() {
|
||||||
if (!snippetId.value.trim() || !window.confirm(t("settings.syncDownloadConfirm"))) return;
|
if (!snippetId.value.trim()) return;
|
||||||
await runSnippetAction("download", async () => {
|
await runSnippetAction("download", async () => {
|
||||||
const result = await snippetSyncDownload(currentSnippetConfig(), snippetPassphrase.value, snippetRestoreSecrets.value, snippetRestoreSecrets.value ? snippetSecretsPassphrase.value : undefined);
|
syncSelectionCatalog.value = await snippetSyncInspect(currentSnippetConfig(), snippetPassphrase.value || undefined, snippetSecretsPassphrase.value || undefined);
|
||||||
if (result.editorSettings && typeof result.editorSettings === "object") settingsStore.updateEditorSettings(result.editorSettings as any);
|
syncSelectionMode.value = "restore";
|
||||||
await settingsStore.updateDesktopSettings(result.desktopSettings);
|
syncSelectionOpen.value = true;
|
||||||
await connectionStore.initFromDisk();
|
return "";
|
||||||
await savedSqlStore.initFromStorage();
|
|
||||||
// Snapshot downloads replace backend-managed tunnel profiles, so refresh
|
|
||||||
// the already-loaded Pinia store instead of leaving the UI stale.
|
|
||||||
await tunnelProfileStore.refresh();
|
|
||||||
await settingsStore.reloadAiConfigs();
|
|
||||||
let message = t("settings.syncSnippetDownloadSuccess", {
|
|
||||||
bytes: result.summary.bytes,
|
|
||||||
id: result.summary.snippetId,
|
|
||||||
});
|
|
||||||
if (result.applySummary.encryptedSecretsPresent && !result.applySummary.secretsApplied) message += ` ${t("settings.syncSecretsSkipped")}`;
|
|
||||||
if (result.applySummary.secretsApplied) message += ` ${t("settings.syncSecretsApplied")}`;
|
|
||||||
return message;
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4555,37 +4549,72 @@ async function testWebDav() {
|
|||||||
|
|
||||||
async function uploadWebDavSnapshot() {
|
async function uploadWebDavSnapshot() {
|
||||||
await runWebDavAction("upload", async () => {
|
await runWebDavAction("upload", async () => {
|
||||||
const summary = await webdavSyncUpload(currentWebDavConfig(), settingsStore.editorSettings, webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined, webdavSyncSecrets.value);
|
syncSelectionCatalog.value = await cloudSyncLocalCatalog(settingsStore.editorSettings);
|
||||||
return t("settings.syncUploadSuccess", {
|
syncSelectionMode.value = "upload";
|
||||||
bytes: summary.bytes,
|
syncSelectionOpen.value = true;
|
||||||
path: summary.remotePath,
|
return "";
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function downloadWebDavSnapshot() {
|
async function downloadWebDavSnapshot() {
|
||||||
if (!window.confirm(t("settings.syncDownloadConfirm"))) return;
|
|
||||||
await runWebDavAction("download", async () => {
|
await runWebDavAction("download", async () => {
|
||||||
const result = await webdavSyncDownload(currentWebDavConfig(), webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined, webdavSyncSecrets.value);
|
syncSelectionCatalog.value = await webdavSyncInspect(currentWebDavConfig(), webdavSecretsPassphrase.value || undefined);
|
||||||
if (result.editorSettings && typeof result.editorSettings === "object") {
|
syncSelectionMode.value = "restore";
|
||||||
settingsStore.updateEditorSettings(result.editorSettings as any);
|
syncSelectionOpen.value = true;
|
||||||
|
return "";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmSyncSelection(selection: SyncSelection) {
|
||||||
|
if (syncMethodTab.value === "snippet") {
|
||||||
|
if (syncSelectionMode.value === "upload") {
|
||||||
|
snippetIncludeSecrets.value = selection.includeSecrets;
|
||||||
|
await runSnippetAction("upload", async () => {
|
||||||
|
const summary = await snippetSyncUpload(currentSnippetConfig(), settingsStore.editorSettings, snippetPassphrase.value, selection.includeSecrets, selection.includeSecrets ? snippetSecretsPassphrase.value : undefined, selection);
|
||||||
|
snippetId.value = summary.snippetId;
|
||||||
|
await persistSnippetSyncId();
|
||||||
|
return t("settings.syncSnippetUploadSuccess", { bytes: summary.bytes, id: summary.snippetId });
|
||||||
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
snippetRestoreSecrets.value = selection.includeSecrets;
|
||||||
|
await runSnippetAction("download", async () => {
|
||||||
|
const result = await snippetSyncDownload(currentSnippetConfig(), snippetPassphrase.value, selection.includeSecrets, selection.includeSecrets ? snippetSecretsPassphrase.value : undefined, selection);
|
||||||
|
if (result.editorSettings && typeof result.editorSettings === "object") settingsStore.updateEditorSettings(result.editorSettings as any);
|
||||||
|
await settingsStore.updateDesktopSettings(result.desktopSettings);
|
||||||
|
await connectionStore.initFromDisk();
|
||||||
|
await savedSqlStore.initFromStorage();
|
||||||
|
await tunnelProfileStore.refresh();
|
||||||
|
await settingsStore.reloadAiConfigs();
|
||||||
|
let message = t("settings.syncSnippetDownloadSuccess", { bytes: result.summary.bytes, id: result.summary.snippetId });
|
||||||
|
if (result.applySummary.encryptedSecretsPresent && !result.applySummary.secretsApplied) message += ` ${t("settings.syncSecretsSkipped")}`;
|
||||||
|
if (result.applySummary.secretsApplied) message += ` ${t("settings.syncSecretsApplied")}`;
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
webdavSyncSecrets.value = selection.includeSecrets;
|
||||||
|
if (syncSelectionMode.value === "upload") {
|
||||||
|
await runWebDavAction("upload", async () => {
|
||||||
|
const summary = await webdavSyncUpload(currentWebDavConfig(), settingsStore.editorSettings, selection.includeSecrets ? webdavSecretsPassphrase.value || undefined : undefined, selection.includeSecrets, selection);
|
||||||
|
writeWebDavBackupSelection(selection);
|
||||||
|
return t("settings.syncUploadSuccess", { bytes: summary.bytes, path: summary.remotePath });
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await runWebDavAction("download", async () => {
|
||||||
|
const result = await webdavSyncDownload(currentWebDavConfig(), selection.includeSecrets ? webdavSecretsPassphrase.value || undefined : undefined, selection.includeSecrets, selection);
|
||||||
|
if (result.editorSettings && typeof result.editorSettings === "object") settingsStore.updateEditorSettings(result.editorSettings as any);
|
||||||
await settingsStore.updateDesktopSettings(result.desktopSettings);
|
await settingsStore.updateDesktopSettings(result.desktopSettings);
|
||||||
await connectionStore.initFromDisk();
|
await connectionStore.initFromDisk();
|
||||||
await savedSqlStore.initFromStorage();
|
await savedSqlStore.initFromStorage();
|
||||||
// Keep the shared tunnel profile UI consistent with the downloaded snapshot.
|
|
||||||
await tunnelProfileStore.refresh();
|
await tunnelProfileStore.refresh();
|
||||||
await settingsStore.reloadAiConfigs();
|
await settingsStore.reloadAiConfigs();
|
||||||
const message = t("settings.syncDownloadSuccess", {
|
const message = t("settings.syncDownloadSuccess", { bytes: result.summary.bytes, path: result.summary.remotePath });
|
||||||
bytes: result.summary.bytes,
|
if (result.applySummary.encryptedSecretsPresent && !result.applySummary.secretsApplied) return `${message} ${t("settings.syncSecretsSkipped")}`;
|
||||||
path: result.summary.remotePath,
|
if (result.applySummary.secretsApplied) return `${message} ${t("settings.syncSecretsApplied")}`;
|
||||||
});
|
|
||||||
if (result.applySummary.encryptedSecretsPresent && !result.applySummary.secretsApplied) {
|
|
||||||
return `${message} ${t("settings.syncSecretsSkipped")}`;
|
|
||||||
}
|
|
||||||
if (result.applySummary.secretsApplied) {
|
|
||||||
return `${message} ${t("settings.syncSecretsApplied")}`;
|
|
||||||
}
|
|
||||||
return message;
|
return message;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -9277,6 +9306,7 @@ LIMIT 100;</pre
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<CloudSyncSelectionDialog v-model:open="syncSelectionOpen" :mode="syncSelectionMode" :catalog="syncSelectionCatalog" :default-include-secrets="syncMethodTab === 'snippet' ? snippetIncludeSecrets : webdavSyncSecrets" @confirm="confirmSyncSelection" />
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- AI Settings Tab -->
|
<!-- AI Settings Tab -->
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { onMounted, onUnmounted } from "vue";
|
|||||||
import { useSettingsStore } from "@/stores/settingsStore";
|
import { useSettingsStore } from "@/stores/settingsStore";
|
||||||
import { appendDebugLog } from "@/lib/backend/debugLog";
|
import { appendDebugLog } from "@/lib/backend/debugLog";
|
||||||
import { webdavSyncSecretsStatus, webdavSyncUpload } from "@/lib/backend/api";
|
import { webdavSyncSecretsStatus, webdavSyncUpload } from "@/lib/backend/api";
|
||||||
import { readWebDavAutoUploadConfig, WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS } from "@/lib/webdav/webdavAutoUploadConfig";
|
import { readWebDavAutoUploadConfig, readWebDavBackupSelection, WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS } from "@/lib/webdav/webdavAutoUploadConfig";
|
||||||
|
|
||||||
export function useWebDavAutoUpload() {
|
export function useWebDavAutoUpload() {
|
||||||
const settingsStore = useSettingsStore();
|
const settingsStore = useSettingsStore();
|
||||||
@@ -33,7 +33,9 @@ export function useWebDavAutoUpload() {
|
|||||||
uploading = true;
|
uploading = true;
|
||||||
try {
|
try {
|
||||||
const secretsStatus = await webdavSyncSecretsStatus();
|
const secretsStatus = await webdavSyncSecretsStatus();
|
||||||
const summary = await webdavSyncUpload(config.webDavConfig, settingsStore.editorSettings, undefined, secretsStatus.enabled && secretsStatus.hasSavedPassphrase);
|
const selection = readWebDavBackupSelection();
|
||||||
|
const includeSecrets = (selection?.includeSecrets ?? secretsStatus.enabled) && secretsStatus.enabled && secretsStatus.hasSavedPassphrase;
|
||||||
|
const summary = await webdavSyncUpload(config.webDavConfig, settingsStore.editorSettings, undefined, includeSecrets, selection);
|
||||||
appendDebugLog("info", "[DBX][webdav:auto-upload:success]", {
|
appendDebugLog("info", "[DBX][webdav:auto-upload:success]", {
|
||||||
bytes: summary.bytes,
|
bytes: summary.bytes,
|
||||||
remotePath: summary.remotePath,
|
remotePath: summary.remotePath,
|
||||||
|
|||||||
@@ -8293,6 +8293,36 @@ export default {
|
|||||||
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
||||||
syncWebDavTitle: "WebDAV Sync",
|
syncWebDavTitle: "WebDAV Sync",
|
||||||
syncWebDavDescription: "Upload or restore a DBX snapshot, including saved SQL library entries, from a WebDAV-compatible storage service.",
|
syncWebDavDescription: "Upload or restore a DBX snapshot, including saved SQL library entries, from a WebDAV-compatible storage service.",
|
||||||
|
syncSelectionUploadTitle: "Select backup content",
|
||||||
|
syncSelectionRestoreTitle: "Select restore content",
|
||||||
|
syncSelectionBackupNote: "Sensitive credentials and plugin data are stored only in encrypted snapshots.",
|
||||||
|
syncSelectionRestoreNote: "Unchecked local content will be kept.",
|
||||||
|
syncSelectionConnections: "Connections and SSH",
|
||||||
|
syncSelectionConnectionSecrets: "Passwords, SSH passwords/key passphrases, and connection credentials",
|
||||||
|
syncSelectionNoConnections: "No connections",
|
||||||
|
syncSelectionTunnels: "Shared tunnel profiles",
|
||||||
|
syncSelectionTunnelSecrets: "Tunnel credentials",
|
||||||
|
syncSelectionNoTunnels: "No tunnel profiles",
|
||||||
|
syncSelectionSavedSql: "Saved SQL",
|
||||||
|
syncSelectionFolders: "SQL folders",
|
||||||
|
syncSelectionFiles: "SQL files",
|
||||||
|
syncSelectionPersonalSettings: "Personal settings",
|
||||||
|
syncSelectionDesktopSettings: "Desktop settings",
|
||||||
|
syncSelectionEditorSettings: "Editor settings",
|
||||||
|
syncSelectionEncrypted: "Encrypted sensitive information",
|
||||||
|
syncSelectionSyncCredentials: "Saved sync service credentials",
|
||||||
|
syncSelectionAiConfigs: "AI configurations",
|
||||||
|
syncSelectionAiLocked: "Remote AI configurations (encrypted contents locked)",
|
||||||
|
syncSelectionPluginData: "Plugin settings data",
|
||||||
|
syncSelectionPluginLocked: "Remote plugin settings (encrypted contents locked)",
|
||||||
|
syncSelectionNoPluginData: "No plugin settings data",
|
||||||
|
syncSelectionNoEncrypted: "The remote snapshot has no encrypted sensitive information.",
|
||||||
|
syncSelectionWorkspace: "Workspace layout",
|
||||||
|
syncSelectionSidebar: "Sidebar layout",
|
||||||
|
syncSelectionPinned: "Pinned tree nodes",
|
||||||
|
syncSelectionCancel: "Cancel",
|
||||||
|
syncSelectionRestoreAction: "Restore selected",
|
||||||
|
syncSelectionUploadAction: "Back up selected",
|
||||||
syncWebDavWebDescription: "In Web mode, the DBX server accesses WebDAV without browser CORS restrictions. Saved passwords remain in the current DBX instance.",
|
syncWebDavWebDescription: "In Web mode, the DBX server accesses WebDAV without browser CORS restrictions. Saved passwords remain in the current DBX instance.",
|
||||||
syncEndpoint: "WebDAV URL",
|
syncEndpoint: "WebDAV URL",
|
||||||
syncUsername: "Username",
|
syncUsername: "Username",
|
||||||
|
|||||||
@@ -7640,6 +7640,36 @@ export default withEnglishFallback({
|
|||||||
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
||||||
syncWebDavTitle: "Sincronización WebDAV",
|
syncWebDavTitle: "Sincronización WebDAV",
|
||||||
syncWebDavDescription: "Sube o restaura una instantánea de DBX, incluida la biblioteca SQL guardada, desde almacenamiento compatible con WebDAV.",
|
syncWebDavDescription: "Sube o restaura una instantánea de DBX, incluida la biblioteca SQL guardada, desde almacenamiento compatible con WebDAV.",
|
||||||
|
syncSelectionUploadTitle: "Seleccionar contenido de copia de seguridad",
|
||||||
|
syncSelectionRestoreTitle: "Seleccionar contenido para restaurar",
|
||||||
|
syncSelectionBackupNote: "Las credenciales sensibles y los datos de plugins solo se incluyen en instantáneas cifradas.",
|
||||||
|
syncSelectionRestoreNote: "El contenido local sin seleccionar se conservará.",
|
||||||
|
syncSelectionConnections: "Conexiones y SSH",
|
||||||
|
syncSelectionConnectionSecrets: "Contraseñas, contraseñas de SSH/frases de contraseña de claves y credenciales de conexión",
|
||||||
|
syncSelectionNoConnections: "No hay conexiones",
|
||||||
|
syncSelectionTunnels: "Perfiles de túnel compartidos",
|
||||||
|
syncSelectionTunnelSecrets: "Credenciales del túnel",
|
||||||
|
syncSelectionNoTunnels: "No hay perfiles de túnel",
|
||||||
|
syncSelectionSavedSql: "SQL guardado",
|
||||||
|
syncSelectionFolders: "Carpetas SQL",
|
||||||
|
syncSelectionFiles: "Archivos SQL",
|
||||||
|
syncSelectionPersonalSettings: "Configuración personal",
|
||||||
|
syncSelectionDesktopSettings: "Configuración del escritorio",
|
||||||
|
syncSelectionEditorSettings: "Configuración del editor",
|
||||||
|
syncSelectionEncrypted: "Información confidencial cifrada",
|
||||||
|
syncSelectionSyncCredentials: "Credenciales guardadas de servicios de sincronización",
|
||||||
|
syncSelectionAiConfigs: "Configuraciones de IA",
|
||||||
|
syncSelectionAiLocked: "Configuraciones remotas de IA (contenido cifrado bloqueado)",
|
||||||
|
syncSelectionPluginData: "Datos de configuración de plugins",
|
||||||
|
syncSelectionPluginLocked: "Configuración remota de plugins (contenido cifrado bloqueado)",
|
||||||
|
syncSelectionNoPluginData: "No hay datos de configuración de plugins",
|
||||||
|
syncSelectionNoEncrypted: "La instantánea remota no contiene información confidencial cifrada.",
|
||||||
|
syncSelectionWorkspace: "Distribución del espacio de trabajo",
|
||||||
|
syncSelectionSidebar: "Distribución de la barra lateral",
|
||||||
|
syncSelectionPinned: "Nodos fijados del árbol",
|
||||||
|
syncSelectionCancel: "Cancelar",
|
||||||
|
syncSelectionRestoreAction: "Restaurar selección",
|
||||||
|
syncSelectionUploadAction: "Respaldar selección",
|
||||||
syncWebDavWebDescription: "En modo Web, el servidor DBX accede a WebDAV sin las restricciones CORS del navegador. Las contraseñas guardadas permanecen en la instancia DBX actual.",
|
syncWebDavWebDescription: "En modo Web, el servidor DBX accede a WebDAV sin las restricciones CORS del navegador. Las contraseñas guardadas permanecen en la instancia DBX actual.",
|
||||||
syncEndpoint: "URL WebDAV",
|
syncEndpoint: "URL WebDAV",
|
||||||
syncUsername: "Usuario",
|
syncUsername: "Usuario",
|
||||||
|
|||||||
@@ -7565,6 +7565,36 @@ export default withEnglishFallback({
|
|||||||
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
||||||
syncWebDavTitle: "Sincronizzazione WebDAV",
|
syncWebDavTitle: "Sincronizzazione WebDAV",
|
||||||
syncWebDavDescription: "Carica o ripristina uno snapshot di DBX, inclusa la libreria SQL salvata, da un servizio di archiviazione compatibile con WebDAV.",
|
syncWebDavDescription: "Carica o ripristina uno snapshot di DBX, inclusa la libreria SQL salvata, da un servizio di archiviazione compatibile con WebDAV.",
|
||||||
|
syncSelectionUploadTitle: "Seleziona i contenuti da salvare",
|
||||||
|
syncSelectionRestoreTitle: "Seleziona i contenuti da ripristinare",
|
||||||
|
syncSelectionBackupNote: "Le credenziali sensibili e i dati dei plugin vengono inclusi solo negli snapshot crittografati.",
|
||||||
|
syncSelectionRestoreNote: "I contenuti locali non selezionati verranno mantenuti.",
|
||||||
|
syncSelectionConnections: "Connessioni e SSH",
|
||||||
|
syncSelectionConnectionSecrets: "Password, password SSH/passphrase delle chiavi e credenziali di connessione",
|
||||||
|
syncSelectionNoConnections: "Nessuna connessione",
|
||||||
|
syncSelectionTunnels: "Profili tunnel condivisi",
|
||||||
|
syncSelectionTunnelSecrets: "Credenziali del tunnel",
|
||||||
|
syncSelectionNoTunnels: "Nessun profilo tunnel",
|
||||||
|
syncSelectionSavedSql: "SQL salvati",
|
||||||
|
syncSelectionFolders: "Cartelle SQL",
|
||||||
|
syncSelectionFiles: "File SQL",
|
||||||
|
syncSelectionPersonalSettings: "Impostazioni personali",
|
||||||
|
syncSelectionDesktopSettings: "Impostazioni desktop",
|
||||||
|
syncSelectionEditorSettings: "Impostazioni dell'editor",
|
||||||
|
syncSelectionEncrypted: "Informazioni sensibili crittografate",
|
||||||
|
syncSelectionSyncCredentials: "Credenziali salvate dei servizi di sincronizzazione",
|
||||||
|
syncSelectionAiConfigs: "Configurazioni IA",
|
||||||
|
syncSelectionAiLocked: "Configurazioni IA remote (contenuto crittografato bloccato)",
|
||||||
|
syncSelectionPluginData: "Dati delle impostazioni dei plugin",
|
||||||
|
syncSelectionPluginLocked: "Impostazioni remote dei plugin (contenuto crittografato bloccato)",
|
||||||
|
syncSelectionNoPluginData: "Nessun dato delle impostazioni dei plugin",
|
||||||
|
syncSelectionNoEncrypted: "Lo snapshot remoto non contiene informazioni sensibili crittografate.",
|
||||||
|
syncSelectionWorkspace: "Layout dell'area di lavoro",
|
||||||
|
syncSelectionSidebar: "Layout della barra laterale",
|
||||||
|
syncSelectionPinned: "Nodi fissati nell'albero",
|
||||||
|
syncSelectionCancel: "Annulla",
|
||||||
|
syncSelectionRestoreAction: "Ripristina selezionati",
|
||||||
|
syncSelectionUploadAction: "Salva selezionati",
|
||||||
syncWebDavWebDescription: "In modalità Web, il server DBX accede a WebDAV senza le limitazioni CORS del browser. Le password salvate restano nell'istanza DBX corrente.",
|
syncWebDavWebDescription: "In modalità Web, il server DBX accede a WebDAV senza le limitazioni CORS del browser. Le password salvate restano nell'istanza DBX corrente.",
|
||||||
syncEndpoint: "URL WebDAV",
|
syncEndpoint: "URL WebDAV",
|
||||||
syncUsername: "Nome utente",
|
syncUsername: "Nome utente",
|
||||||
|
|||||||
@@ -7581,6 +7581,36 @@ export default withEnglishFallback({
|
|||||||
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
||||||
syncWebDavTitle: "WebDAV同期",
|
syncWebDavTitle: "WebDAV同期",
|
||||||
syncWebDavDescription: "保存済みSQLライブラリを含むDBXスナップショットをWebDAV互換ストレージへアップロードまたは復元します。",
|
syncWebDavDescription: "保存済みSQLライブラリを含むDBXスナップショットをWebDAV互換ストレージへアップロードまたは復元します。",
|
||||||
|
syncSelectionUploadTitle: "バックアップする内容を選択",
|
||||||
|
syncSelectionRestoreTitle: "復元する内容を選択",
|
||||||
|
syncSelectionBackupNote: "機密性の高い認証情報とプラグインデータは、暗号化されたスナップショットにのみ保存されます。",
|
||||||
|
syncSelectionRestoreNote: "選択されていないローカルデータは保持されます。",
|
||||||
|
syncSelectionConnections: "接続情報とSSH",
|
||||||
|
syncSelectionConnectionSecrets: "パスワード、SSHパスワード/鍵のパスフレーズ、接続認証情報",
|
||||||
|
syncSelectionNoConnections: "接続情報はありません",
|
||||||
|
syncSelectionTunnels: "共有トンネルプロファイル",
|
||||||
|
syncSelectionTunnelSecrets: "トンネル認証情報",
|
||||||
|
syncSelectionNoTunnels: "トンネルプロファイルはありません",
|
||||||
|
syncSelectionSavedSql: "保存済みSQL",
|
||||||
|
syncSelectionFolders: "SQLフォルダー",
|
||||||
|
syncSelectionFiles: "SQLファイル",
|
||||||
|
syncSelectionPersonalSettings: "個人設定",
|
||||||
|
syncSelectionDesktopSettings: "デスクトップ設定",
|
||||||
|
syncSelectionEditorSettings: "エディター設定",
|
||||||
|
syncSelectionEncrypted: "暗号化された機密情報",
|
||||||
|
syncSelectionSyncCredentials: "保存済みの同期サービス認証情報",
|
||||||
|
syncSelectionAiConfigs: "AI設定",
|
||||||
|
syncSelectionAiLocked: "リモートAI設定(暗号化された内容はロック中)",
|
||||||
|
syncSelectionPluginData: "プラグイン設定データ",
|
||||||
|
syncSelectionPluginLocked: "リモートプラグイン設定(暗号化された内容はロック中)",
|
||||||
|
syncSelectionNoPluginData: "プラグイン設定データはありません",
|
||||||
|
syncSelectionNoEncrypted: "リモートスナップショットに暗号化された機密情報はありません。",
|
||||||
|
syncSelectionWorkspace: "ワークスペースレイアウト",
|
||||||
|
syncSelectionSidebar: "サイドバーのレイアウト",
|
||||||
|
syncSelectionPinned: "ツリーの固定ノード",
|
||||||
|
syncSelectionCancel: "キャンセル",
|
||||||
|
syncSelectionRestoreAction: "選択した項目を復元",
|
||||||
|
syncSelectionUploadAction: "選択した項目をバックアップ",
|
||||||
syncWebDavWebDescription: "WebモードではDBXサーバーがWebDAVへ接続するため、ブラウザーのCORS制限を受けません。保存したパスワードは現在のDBXインスタンス内に保持されます。",
|
syncWebDavWebDescription: "WebモードではDBXサーバーがWebDAVへ接続するため、ブラウザーのCORS制限を受けません。保存したパスワードは現在のDBXインスタンス内に保持されます。",
|
||||||
syncEndpoint: "WebDAV URL",
|
syncEndpoint: "WebDAV URL",
|
||||||
syncUsername: "ユーザー名",
|
syncUsername: "ユーザー名",
|
||||||
|
|||||||
@@ -7331,6 +7331,36 @@ export default withEnglishFallback({
|
|||||||
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
||||||
syncWebDavTitle: "WebDAV 동기화",
|
syncWebDavTitle: "WebDAV 동기화",
|
||||||
syncWebDavDescription: "WebDAV 호환 저장 서비스에서 DBX 스냅샷을 업로드하거나 복원합니다(저장된 SQL 라이브러리 항목 포함).",
|
syncWebDavDescription: "WebDAV 호환 저장 서비스에서 DBX 스냅샷을 업로드하거나 복원합니다(저장된 SQL 라이브러리 항목 포함).",
|
||||||
|
syncSelectionUploadTitle: "백업할 콘텐츠 선택",
|
||||||
|
syncSelectionRestoreTitle: "복원할 콘텐츠 선택",
|
||||||
|
syncSelectionBackupNote: "민감한 자격 증명과 플러그인 데이터는 암호화된 스냅샷에만 저장됩니다.",
|
||||||
|
syncSelectionRestoreNote: "선택하지 않은 로컬 콘텐츠는 유지됩니다.",
|
||||||
|
syncSelectionConnections: "연결 정보 및 SSH",
|
||||||
|
syncSelectionConnectionSecrets: "비밀번호, SSH 비밀번호/키 암호 및 연결 자격 증명",
|
||||||
|
syncSelectionNoConnections: "연결 정보가 없습니다",
|
||||||
|
syncSelectionTunnels: "공유 터널 프로필",
|
||||||
|
syncSelectionTunnelSecrets: "터널 자격 증명",
|
||||||
|
syncSelectionNoTunnels: "터널 프로필이 없습니다",
|
||||||
|
syncSelectionSavedSql: "저장된 SQL",
|
||||||
|
syncSelectionFolders: "SQL 폴더",
|
||||||
|
syncSelectionFiles: "SQL 파일",
|
||||||
|
syncSelectionPersonalSettings: "개인 설정",
|
||||||
|
syncSelectionDesktopSettings: "데스크톱 설정",
|
||||||
|
syncSelectionEditorSettings: "편집기 설정",
|
||||||
|
syncSelectionEncrypted: "암호화된 민감 정보",
|
||||||
|
syncSelectionSyncCredentials: "저장된 동기화 서비스 자격 증명",
|
||||||
|
syncSelectionAiConfigs: "AI 구성",
|
||||||
|
syncSelectionAiLocked: "원격 AI 구성 (암호화된 콘텐츠 잠김)",
|
||||||
|
syncSelectionPluginData: "플러그인 설정 데이터",
|
||||||
|
syncSelectionPluginLocked: "원격 플러그인 설정 (암호화된 콘텐츠 잠김)",
|
||||||
|
syncSelectionNoPluginData: "플러그인 설정 데이터가 없습니다",
|
||||||
|
syncSelectionNoEncrypted: "원격 스냅샷에 암호화된 민감 정보가 없습니다.",
|
||||||
|
syncSelectionWorkspace: "작업 공간 레이아웃",
|
||||||
|
syncSelectionSidebar: "사이드바 레이아웃",
|
||||||
|
syncSelectionPinned: "고정된 트리 노드",
|
||||||
|
syncSelectionCancel: "취소",
|
||||||
|
syncSelectionRestoreAction: "선택 항목 복원",
|
||||||
|
syncSelectionUploadAction: "선택 항목 백업",
|
||||||
syncWebDavWebDescription: "Web 모드에서는 DBX 서버가 WebDAV에 연결하므로 브라우저 CORS 제한을 받지 않습니다. 저장된 비밀번호는 현재 DBX 인스턴스에 유지됩니다.",
|
syncWebDavWebDescription: "Web 모드에서는 DBX 서버가 WebDAV에 연결하므로 브라우저 CORS 제한을 받지 않습니다. 저장된 비밀번호는 현재 DBX 인스턴스에 유지됩니다.",
|
||||||
syncEndpoint: "WebDAV URL",
|
syncEndpoint: "WebDAV URL",
|
||||||
syncUsername: "사용자 이름",
|
syncUsername: "사용자 이름",
|
||||||
|
|||||||
@@ -7566,6 +7566,36 @@ export default withEnglishFallback({
|
|||||||
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
sqlShortcutsSelectLimitHint: "At run time, SQL is generated for the active connection dialect.",
|
||||||
syncWebDavTitle: "Sincronização WebDAV",
|
syncWebDavTitle: "Sincronização WebDAV",
|
||||||
syncWebDavDescription: "Envie ou restaure um snapshot do DBX, incluindo a biblioteca SQL salva, a partir de um serviço de armazenamento compatível com WebDAV.",
|
syncWebDavDescription: "Envie ou restaure um snapshot do DBX, incluindo a biblioteca SQL salva, a partir de um serviço de armazenamento compatível com WebDAV.",
|
||||||
|
syncSelectionUploadTitle: "Selecionar conteúdo para backup",
|
||||||
|
syncSelectionRestoreTitle: "Selecionar conteúdo para restauração",
|
||||||
|
syncSelectionBackupNote: "Credenciais confidenciais e dados de plugins são incluídos somente em snapshots criptografados.",
|
||||||
|
syncSelectionRestoreNote: "O conteúdo local não selecionado será mantido.",
|
||||||
|
syncSelectionConnections: "Conexões e SSH",
|
||||||
|
syncSelectionConnectionSecrets: "Senhas, senhas SSH/frases secretas de chaves e credenciais de conexão",
|
||||||
|
syncSelectionNoConnections: "Nenhuma conexão",
|
||||||
|
syncSelectionTunnels: "Perfis de túnel compartilhados",
|
||||||
|
syncSelectionTunnelSecrets: "Credenciais do túnel",
|
||||||
|
syncSelectionNoTunnels: "Nenhum perfil de túnel",
|
||||||
|
syncSelectionSavedSql: "SQL salvo",
|
||||||
|
syncSelectionFolders: "Pastas SQL",
|
||||||
|
syncSelectionFiles: "Arquivos SQL",
|
||||||
|
syncSelectionPersonalSettings: "Configurações pessoais",
|
||||||
|
syncSelectionDesktopSettings: "Configurações da área de trabalho",
|
||||||
|
syncSelectionEditorSettings: "Configurações do editor",
|
||||||
|
syncSelectionEncrypted: "Informações confidenciais criptografadas",
|
||||||
|
syncSelectionSyncCredentials: "Credenciais salvas dos serviços de sincronização",
|
||||||
|
syncSelectionAiConfigs: "Configurações de IA",
|
||||||
|
syncSelectionAiLocked: "Configurações remotas de IA (conteúdo criptografado bloqueado)",
|
||||||
|
syncSelectionPluginData: "Dados de configurações de plugins",
|
||||||
|
syncSelectionPluginLocked: "Configurações remotas de plugins (conteúdo criptografado bloqueado)",
|
||||||
|
syncSelectionNoPluginData: "Nenhum dado de configurações de plugins",
|
||||||
|
syncSelectionNoEncrypted: "O snapshot remoto não contém informações confidenciais criptografadas.",
|
||||||
|
syncSelectionWorkspace: "Layout do espaço de trabalho",
|
||||||
|
syncSelectionSidebar: "Layout da barra lateral",
|
||||||
|
syncSelectionPinned: "Nós fixados na árvore",
|
||||||
|
syncSelectionCancel: "Cancelar",
|
||||||
|
syncSelectionRestoreAction: "Restaurar selecionados",
|
||||||
|
syncSelectionUploadAction: "Fazer backup dos selecionados",
|
||||||
syncWebDavWebDescription: "No modo Web, o servidor DBX acessa o WebDAV sem as restrições de CORS do navegador. As senhas salvas permanecem na instância DBX atual.",
|
syncWebDavWebDescription: "No modo Web, o servidor DBX acessa o WebDAV sem as restrições de CORS do navegador. As senhas salvas permanecem na instância DBX atual.",
|
||||||
syncEndpoint: "URL do WebDAV",
|
syncEndpoint: "URL do WebDAV",
|
||||||
syncUsername: "Nome de usuário",
|
syncUsername: "Nome de usuário",
|
||||||
|
|||||||
@@ -8796,6 +8796,36 @@ export default withEnglishFallback({
|
|||||||
sqlShortcutsSelectLimitHint: "Во время выполнения SQL формируется для диалекта активного подключения.",
|
sqlShortcutsSelectLimitHint: "Во время выполнения SQL формируется для диалекта активного подключения.",
|
||||||
syncWebDavTitle: "Синхронизация WebDAV",
|
syncWebDavTitle: "Синхронизация WebDAV",
|
||||||
syncWebDavDescription: "Загружать или восстанавливать снимок DBX, включая сохранённые записи библиотеки SQL, из совместимого с WebDAV хранилища.",
|
syncWebDavDescription: "Загружать или восстанавливать снимок DBX, включая сохранённые записи библиотеки SQL, из совместимого с WebDAV хранилища.",
|
||||||
|
syncSelectionUploadTitle: "Выберите данные для резервного копирования",
|
||||||
|
syncSelectionRestoreTitle: "Выберите данные для восстановления",
|
||||||
|
syncSelectionBackupNote: "Конфиденциальные учетные данные и данные плагинов сохраняются только в зашифрованных снимках.",
|
||||||
|
syncSelectionRestoreNote: "Невыбранные локальные данные останутся без изменений.",
|
||||||
|
syncSelectionConnections: "Подключения и SSH",
|
||||||
|
syncSelectionConnectionSecrets: "Пароли, пароли SSH/парольные фразы ключей и учетные данные подключений",
|
||||||
|
syncSelectionNoConnections: "Нет подключений",
|
||||||
|
syncSelectionTunnels: "Общие профили туннелей",
|
||||||
|
syncSelectionTunnelSecrets: "Учетные данные туннеля",
|
||||||
|
syncSelectionNoTunnels: "Нет профилей туннелей",
|
||||||
|
syncSelectionSavedSql: "Сохраненные SQL-запросы",
|
||||||
|
syncSelectionFolders: "Папки SQL",
|
||||||
|
syncSelectionFiles: "Файлы SQL",
|
||||||
|
syncSelectionPersonalSettings: "Личные настройки",
|
||||||
|
syncSelectionDesktopSettings: "Настройки рабочего стола",
|
||||||
|
syncSelectionEditorSettings: "Настройки редактора",
|
||||||
|
syncSelectionEncrypted: "Зашифрованная конфиденциальная информация",
|
||||||
|
syncSelectionSyncCredentials: "Сохраненные учетные данные служб синхронизации",
|
||||||
|
syncSelectionAiConfigs: "Конфигурации ИИ",
|
||||||
|
syncSelectionAiLocked: "Удаленные конфигурации ИИ (зашифрованные данные заблокированы)",
|
||||||
|
syncSelectionPluginData: "Данные настроек плагинов",
|
||||||
|
syncSelectionPluginLocked: "Удаленные настройки плагинов (зашифрованные данные заблокированы)",
|
||||||
|
syncSelectionNoPluginData: "Нет данных настроек плагинов",
|
||||||
|
syncSelectionNoEncrypted: "В удаленном снимке нет зашифрованной конфиденциальной информации.",
|
||||||
|
syncSelectionWorkspace: "Макет рабочего пространства",
|
||||||
|
syncSelectionSidebar: "Макет боковой панели",
|
||||||
|
syncSelectionPinned: "Закрепленные узлы дерева",
|
||||||
|
syncSelectionCancel: "Отмена",
|
||||||
|
syncSelectionRestoreAction: "Восстановить выбранное",
|
||||||
|
syncSelectionUploadAction: "Сохранить выбранное",
|
||||||
syncWebDavWebDescription: "В веб-режиме сервер DBX обращается к WebDAV без ограничений CORS браузера. Сохранённые пароли остаются в текущем экземпляре DBX.",
|
syncWebDavWebDescription: "В веб-режиме сервер DBX обращается к WebDAV без ограничений CORS браузера. Сохранённые пароли остаются в текущем экземпляре DBX.",
|
||||||
syncEndpoint: "URL WebDAV",
|
syncEndpoint: "URL WebDAV",
|
||||||
syncUsername: "Имя пользователя",
|
syncUsername: "Имя пользователя",
|
||||||
|
|||||||
@@ -8258,6 +8258,36 @@ export default withEnglishFallback({
|
|||||||
sqlShortcutsSelectLimitHint: "执行时会按当前连接的数据库类型生成 SQL。",
|
sqlShortcutsSelectLimitHint: "执行时会按当前连接的数据库类型生成 SQL。",
|
||||||
syncWebDavTitle: "WebDAV 同步",
|
syncWebDavTitle: "WebDAV 同步",
|
||||||
syncWebDavDescription: "将包含 SQL 库的 DBX 快照上传到兼容 WebDAV 的存储服务,或从远端恢复。",
|
syncWebDavDescription: "将包含 SQL 库的 DBX 快照上传到兼容 WebDAV 的存储服务,或从远端恢复。",
|
||||||
|
syncSelectionUploadTitle: "选择备份内容",
|
||||||
|
syncSelectionRestoreTitle: "选择恢复内容",
|
||||||
|
syncSelectionBackupNote: "敏感凭据和插件数据只会写入加密快照。",
|
||||||
|
syncSelectionRestoreNote: "未勾选的本地内容会保留。",
|
||||||
|
syncSelectionConnections: "连接信息与 SSH",
|
||||||
|
syncSelectionConnectionSecrets: "密码、SSH 密码/密钥口令及连接凭据",
|
||||||
|
syncSelectionNoConnections: "无连接项目",
|
||||||
|
syncSelectionTunnels: "共享隧道配置",
|
||||||
|
syncSelectionTunnelSecrets: "隧道凭据",
|
||||||
|
syncSelectionNoTunnels: "无隧道配置",
|
||||||
|
syncSelectionSavedSql: "保存的 SQL",
|
||||||
|
syncSelectionFolders: "SQL 文件夹",
|
||||||
|
syncSelectionFiles: "SQL 文件",
|
||||||
|
syncSelectionPersonalSettings: "个人设置",
|
||||||
|
syncSelectionDesktopSettings: "桌面设置",
|
||||||
|
syncSelectionEditorSettings: "编辑器设置",
|
||||||
|
syncSelectionEncrypted: "加密敏感信息",
|
||||||
|
syncSelectionSyncCredentials: "已保存的同步服务凭据",
|
||||||
|
syncSelectionAiConfigs: "AI 配置",
|
||||||
|
syncSelectionAiLocked: "远端 AI 配置(加密目录未解锁)",
|
||||||
|
syncSelectionPluginData: "插件设置数据",
|
||||||
|
syncSelectionPluginLocked: "远端插件设置数据(加密目录未解锁)",
|
||||||
|
syncSelectionNoPluginData: "无插件设置数据",
|
||||||
|
syncSelectionNoEncrypted: "远端快照不含加密敏感信息。",
|
||||||
|
syncSelectionWorkspace: "工作区布局",
|
||||||
|
syncSelectionSidebar: "侧边栏布局",
|
||||||
|
syncSelectionPinned: "固定的树节点",
|
||||||
|
syncSelectionCancel: "取消",
|
||||||
|
syncSelectionRestoreAction: "恢复所选",
|
||||||
|
syncSelectionUploadAction: "备份所选",
|
||||||
syncWebDavWebDescription: "Web 模式下由 DBX 服务端访问 WebDAV,不受浏览器 CORS 限制;保存的密码会留在当前 DBX 实例中。",
|
syncWebDavWebDescription: "Web 模式下由 DBX 服务端访问 WebDAV,不受浏览器 CORS 限制;保存的密码会留在当前 DBX 实例中。",
|
||||||
syncEndpoint: "WebDAV 地址",
|
syncEndpoint: "WebDAV 地址",
|
||||||
syncUsername: "用户名",
|
syncUsername: "用户名",
|
||||||
|
|||||||
@@ -6883,6 +6883,36 @@ export default withEnglishFallback({
|
|||||||
sqlShortcutsSelectLimitHint: "執行時會依目前連線的資料庫類型產生 SQL。",
|
sqlShortcutsSelectLimitHint: "執行時會依目前連線的資料庫類型產生 SQL。",
|
||||||
syncWebDavTitle: "WebDAV 同步",
|
syncWebDavTitle: "WebDAV 同步",
|
||||||
syncWebDavDescription: "上傳包含 SQL 庫的 DBX 快照到相容 WebDAV 的儲存服務,或從該服務還原快照。",
|
syncWebDavDescription: "上傳包含 SQL 庫的 DBX 快照到相容 WebDAV 的儲存服務,或從該服務還原快照。",
|
||||||
|
syncSelectionUploadTitle: "選擇備份內容",
|
||||||
|
syncSelectionRestoreTitle: "選擇還原內容",
|
||||||
|
syncSelectionBackupNote: "敏感憑證與外掛資料只會寫入加密快照。",
|
||||||
|
syncSelectionRestoreNote: "未勾選的本機內容會保留。",
|
||||||
|
syncSelectionConnections: "連線資訊與 SSH",
|
||||||
|
syncSelectionConnectionSecrets: "密碼、SSH 密碼/金鑰密語及連線憑證",
|
||||||
|
syncSelectionNoConnections: "沒有連線項目",
|
||||||
|
syncSelectionTunnels: "共用通道設定",
|
||||||
|
syncSelectionTunnelSecrets: "通道憑證",
|
||||||
|
syncSelectionNoTunnels: "沒有通道設定",
|
||||||
|
syncSelectionSavedSql: "已儲存的 SQL",
|
||||||
|
syncSelectionFolders: "SQL 資料夾",
|
||||||
|
syncSelectionFiles: "SQL 檔案",
|
||||||
|
syncSelectionPersonalSettings: "個人設定",
|
||||||
|
syncSelectionDesktopSettings: "桌面設定",
|
||||||
|
syncSelectionEditorSettings: "編輯器設定",
|
||||||
|
syncSelectionEncrypted: "加密的敏感資訊",
|
||||||
|
syncSelectionSyncCredentials: "已儲存的同步服務憑證",
|
||||||
|
syncSelectionAiConfigs: "AI 設定",
|
||||||
|
syncSelectionAiLocked: "遠端 AI 設定(加密內容未解鎖)",
|
||||||
|
syncSelectionPluginData: "外掛設定資料",
|
||||||
|
syncSelectionPluginLocked: "遠端外掛設定(加密內容未解鎖)",
|
||||||
|
syncSelectionNoPluginData: "沒有外掛設定資料",
|
||||||
|
syncSelectionNoEncrypted: "遠端快照不含加密的敏感資訊。",
|
||||||
|
syncSelectionWorkspace: "工作區版面配置",
|
||||||
|
syncSelectionSidebar: "側邊欄版面配置",
|
||||||
|
syncSelectionPinned: "釘選的樹狀節點",
|
||||||
|
syncSelectionCancel: "取消",
|
||||||
|
syncSelectionRestoreAction: "還原所選項目",
|
||||||
|
syncSelectionUploadAction: "備份所選項目",
|
||||||
syncWebDavWebDescription: "Web 模式由 DBX 伺服器端存取 WebDAV,不受瀏覽器 CORS 限制;儲存的密碼會保留在目前 DBX 執行個體中。",
|
syncWebDavWebDescription: "Web 模式由 DBX 伺服器端存取 WebDAV,不受瀏覽器 CORS 限制;儲存的密碼會保留在目前 DBX 執行個體中。",
|
||||||
syncEndpoint: "WebDAV 地址",
|
syncEndpoint: "WebDAV 地址",
|
||||||
syncUsername: "使用者名稱",
|
syncUsername: "使用者名稱",
|
||||||
|
|||||||
@@ -74,6 +74,49 @@ describe("WebDAV sync HTTP API", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("requests a selectable catalog and sends the selected snapshot items", async () => {
|
||||||
|
const fetchMock = stubFetch({ connections: [{ id: "db-1", label: "Production" }] });
|
||||||
|
const { cloudSyncLocalCatalog, webdavSyncInspect, webdavSyncUpload, webdavSyncDownload } = await import("@/lib/backend/http");
|
||||||
|
const editorSettings = { theme: "dark" };
|
||||||
|
const catalog = await cloudSyncLocalCatalog(editorSettings);
|
||||||
|
expect(catalog.connections).toEqual([{ id: "db-1", label: "Production" }]);
|
||||||
|
expect(lastCall(fetchMock)).toEqual({ url: "/api/cloud-sync/catalog/local", body: { editorSettings } });
|
||||||
|
|
||||||
|
await webdavSyncInspect(config, "sync-password");
|
||||||
|
expect(lastCall(fetchMock)).toEqual({
|
||||||
|
url: "/api/cloud-sync/webdav/inspect",
|
||||||
|
body: { config, secretsPassphrase: "sync-password" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const selection = {
|
||||||
|
connections: ["db-1"],
|
||||||
|
connectionSecrets: ["db-1"],
|
||||||
|
tunnelProfiles: [],
|
||||||
|
tunnelSecrets: [],
|
||||||
|
savedSqlFolders: [],
|
||||||
|
savedSqlFiles: [],
|
||||||
|
desktopSettings: ["iconTheme"],
|
||||||
|
editorSettings: ["theme"],
|
||||||
|
aiConfigs: [],
|
||||||
|
pluginUiStorage: [],
|
||||||
|
sidebarLayout: false,
|
||||||
|
pinnedTreeNodeIds: false,
|
||||||
|
includeSecrets: true,
|
||||||
|
syncCredentials: false,
|
||||||
|
};
|
||||||
|
await webdavSyncUpload(config, editorSettings, "sync-password", true, selection);
|
||||||
|
expect(lastCall(fetchMock)).toEqual({
|
||||||
|
url: "/api/cloud-sync/webdav/upload",
|
||||||
|
body: { config, editorSettings, secretsPassphrase: "sync-password", includeSecrets: true, selection },
|
||||||
|
});
|
||||||
|
|
||||||
|
await webdavSyncDownload(config, "sync-password", true, selection);
|
||||||
|
expect(lastCall(fetchMock)).toEqual({
|
||||||
|
url: "/api/cloud-sync/webdav/download",
|
||||||
|
body: { config, secretsPassphrase: "sync-password", restoreSecrets: true, selection },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("accepts the migration cleanup endpoint's empty 204 response", async () => {
|
it("accepts the migration cleanup endpoint's empty 204 response", async () => {
|
||||||
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
|
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
|
||||||
vi.stubGlobal("fetch", fetchMock);
|
vi.stubGlobal("fetch", fetchMock);
|
||||||
|
|||||||
@@ -420,6 +420,8 @@ export const forgetWebdavSavedPassword = forward("forgetWebdavSavedPassword");
|
|||||||
export const webdavSyncSecretsStatus = forward("webdavSyncSecretsStatus");
|
export const webdavSyncSecretsStatus = forward("webdavSyncSecretsStatus");
|
||||||
export const saveWebdavSyncSecretsPreference = forward("saveWebdavSyncSecretsPreference");
|
export const saveWebdavSyncSecretsPreference = forward("saveWebdavSyncSecretsPreference");
|
||||||
export const forgetWebdavSyncSecretsPassphrase = forward("forgetWebdavSyncSecretsPassphrase");
|
export const forgetWebdavSyncSecretsPassphrase = forward("forgetWebdavSyncSecretsPassphrase");
|
||||||
|
export const cloudSyncLocalCatalog = forward("cloudSyncLocalCatalog");
|
||||||
|
export const webdavSyncInspect = forward("webdavSyncInspect");
|
||||||
export const webdavSyncUpload = forward("webdavSyncUpload");
|
export const webdavSyncUpload = forward("webdavSyncUpload");
|
||||||
export const webdavSyncDownload = forward("webdavSyncDownload");
|
export const webdavSyncDownload = forward("webdavSyncDownload");
|
||||||
export const snippetSyncTest = forward("snippetSyncTest");
|
export const snippetSyncTest = forward("snippetSyncTest");
|
||||||
@@ -427,6 +429,7 @@ export const snippetTokenStatus = forward("snippetTokenStatus");
|
|||||||
export const saveSnippetSavedToken = forward("saveSnippetSavedToken");
|
export const saveSnippetSavedToken = forward("saveSnippetSavedToken");
|
||||||
export const forgetSnippetSavedToken = forward("forgetSnippetSavedToken");
|
export const forgetSnippetSavedToken = forward("forgetSnippetSavedToken");
|
||||||
export const snippetSyncSettings = forward("snippetSyncSettings");
|
export const snippetSyncSettings = forward("snippetSyncSettings");
|
||||||
|
export const snippetSyncInspect = forward("snippetSyncInspect");
|
||||||
export const saveSnippetSyncId = forward("saveSnippetSyncId");
|
export const saveSnippetSyncId = forward("saveSnippetSyncId");
|
||||||
export const retrySnippetLegacyCleanup = forward("retrySnippetLegacyCleanup");
|
export const retrySnippetLegacyCleanup = forward("retrySnippetLegacyCleanup");
|
||||||
export const snippetSyncUpload = forward("snippetSyncUpload");
|
export const snippetSyncUpload = forward("snippetSyncUpload");
|
||||||
@@ -996,6 +999,10 @@ export type {
|
|||||||
WebDavConfig,
|
WebDavConfig,
|
||||||
WebDavPasswordStatus,
|
WebDavPasswordStatus,
|
||||||
WebDavSyncSummary,
|
WebDavSyncSummary,
|
||||||
|
SyncCatalogItem,
|
||||||
|
PluginUiStorageItemRef,
|
||||||
|
SyncSelection,
|
||||||
|
SyncSnapshotCatalog,
|
||||||
WebDavDownloadResult,
|
WebDavDownloadResult,
|
||||||
SnippetProvider,
|
SnippetProvider,
|
||||||
SnippetSyncConfig,
|
SnippetSyncConfig,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRest
|
|||||||
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
|
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
|
||||||
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
|
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
|
||||||
import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";
|
import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";
|
||||||
|
import type { PluginUiStorageItemRef, SyncCatalogItem, SyncSelection, SyncSnapshotCatalog } from "@/lib/backend/tauri";
|
||||||
|
|
||||||
export function databaseBackupCommand<T = unknown>(command: DatabaseBackupCommand): Promise<T> {
|
export function databaseBackupCommand<T = unknown>(command: DatabaseBackupCommand): Promise<T> {
|
||||||
return post("/api/database-backups", command);
|
return post("/api/database-backups", command);
|
||||||
@@ -2443,6 +2444,8 @@ export interface WebDavSyncSummary {
|
|||||||
appVersion?: string;
|
appVersion?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type { PluginUiStorageItemRef, SyncCatalogItem, SyncSelection, SyncSnapshotCatalog };
|
||||||
|
|
||||||
export interface WebDavDownloadResult {
|
export interface WebDavDownloadResult {
|
||||||
summary: WebDavSyncSummary;
|
summary: WebDavSyncSummary;
|
||||||
editorSettings?: unknown;
|
editorSettings?: unknown;
|
||||||
@@ -2528,17 +2531,26 @@ export async function forgetWebdavSyncSecretsPassphrase(): Promise<void> {
|
|||||||
return post("/api/cloud-sync/webdav/forget-sync-secrets-passphrase", {});
|
return post("/api/cloud-sync/webdav/forget-sync-secrets-passphrase", {});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false): Promise<WebDavSyncSummary> {
|
export async function cloudSyncLocalCatalog(editorSettings?: unknown): Promise<SyncSnapshotCatalog> {
|
||||||
|
return post("/api/cloud-sync/catalog/local", { editorSettings });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function webdavSyncInspect(config: WebDavConfig, secretsPassphrase?: string): Promise<SyncSnapshotCatalog> {
|
||||||
|
return post("/api/cloud-sync/webdav/inspect", { config, secretsPassphrase });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false, selection?: SyncSelection): Promise<WebDavSyncSummary> {
|
||||||
return post("/api/cloud-sync/webdav/upload", {
|
return post("/api/cloud-sync/webdav/upload", {
|
||||||
config,
|
config,
|
||||||
editorSettings,
|
editorSettings,
|
||||||
secretsPassphrase,
|
secretsPassphrase,
|
||||||
includeSecrets,
|
includeSecrets,
|
||||||
|
selection,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true): Promise<WebDavDownloadResult> {
|
export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true, selection?: SyncSelection): Promise<WebDavDownloadResult> {
|
||||||
return post("/api/cloud-sync/webdav/download", { config, secretsPassphrase, restoreSecrets });
|
return post("/api/cloud-sync/webdav/download", { config, secretsPassphrase, restoreSecrets, selection });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function snippetSyncTest(config: SnippetSyncConfig): Promise<void> {
|
export async function snippetSyncTest(config: SnippetSyncConfig): Promise<void> {
|
||||||
@@ -2569,22 +2581,28 @@ export async function retrySnippetLegacyCleanup(config: SnippetSyncConfig): Prom
|
|||||||
return post("/api/cloud-sync/snippet/retry-legacy-cleanup", { config });
|
return post("/api/cloud-sync/snippet/retry-legacy-cleanup", { config });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function snippetSyncUpload(config: SnippetSyncConfig, editorSettings?: unknown, snippetPassphrase?: string, includeSecrets = false, secretsPassphrase?: string): Promise<SnippetSyncSummary> {
|
export async function snippetSyncInspect(config: SnippetSyncConfig, snippetPassphrase?: string, secretsPassphrase?: string): Promise<SyncSnapshotCatalog> {
|
||||||
|
return post("/api/cloud-sync/snippet/inspect", { config, snippetPassphrase, secretsPassphrase });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function snippetSyncUpload(config: SnippetSyncConfig, editorSettings?: unknown, snippetPassphrase?: string, includeSecrets = false, secretsPassphrase?: string, selection?: SyncSelection): Promise<SnippetSyncSummary> {
|
||||||
return post("/api/cloud-sync/snippet/upload", {
|
return post("/api/cloud-sync/snippet/upload", {
|
||||||
config,
|
config,
|
||||||
editorSettings,
|
editorSettings,
|
||||||
snippetPassphrase,
|
snippetPassphrase,
|
||||||
includeSecrets,
|
includeSecrets,
|
||||||
secretsPassphrase,
|
secretsPassphrase,
|
||||||
|
selection,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function snippetSyncDownload(config: SnippetSyncConfig, snippetPassphrase?: string, restoreSecrets = false, secretsPassphrase?: string): Promise<SnippetDownloadResult> {
|
export async function snippetSyncDownload(config: SnippetSyncConfig, snippetPassphrase?: string, restoreSecrets = false, secretsPassphrase?: string, selection?: SyncSelection): Promise<SnippetDownloadResult> {
|
||||||
return post("/api/cloud-sync/snippet/download", {
|
return post("/api/cloud-sync/snippet/download", {
|
||||||
config,
|
config,
|
||||||
snippetPassphrase,
|
snippetPassphrase,
|
||||||
restoreSecrets,
|
restoreSecrets,
|
||||||
secretsPassphrase,
|
secretsPassphrase,
|
||||||
|
selection,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -389,6 +389,55 @@ export interface WebDavSyncSummary {
|
|||||||
appVersion?: string;
|
appVersion?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SyncCatalogItem {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PluginUiStorageItemRef {
|
||||||
|
pluginId: string;
|
||||||
|
key: string;
|
||||||
|
pluginName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SyncSelection {
|
||||||
|
connections?: string[];
|
||||||
|
connectionSecrets?: string[];
|
||||||
|
tunnelProfiles?: string[];
|
||||||
|
tunnelSecrets?: string[];
|
||||||
|
savedSqlFolders?: string[];
|
||||||
|
savedSqlFiles?: string[];
|
||||||
|
desktopSettings?: string[];
|
||||||
|
editorSettings?: string[];
|
||||||
|
aiConfigs?: string[];
|
||||||
|
pluginUiStorage?: PluginUiStorageItemRef[];
|
||||||
|
sidebarLayout?: boolean;
|
||||||
|
pinnedTreeNodeIds?: boolean;
|
||||||
|
includeSecrets: boolean;
|
||||||
|
syncCredentials: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SyncSnapshotCatalog {
|
||||||
|
exportedAt: string;
|
||||||
|
appVersion: string;
|
||||||
|
hasEncryptedSecrets: boolean;
|
||||||
|
connections: SyncCatalogItem[];
|
||||||
|
connectionSecrets: string[];
|
||||||
|
tunnelProfiles: SyncCatalogItem[];
|
||||||
|
tunnelSecrets: string[];
|
||||||
|
savedSqlFolders: SyncCatalogItem[];
|
||||||
|
savedSqlFiles: SyncCatalogItem[];
|
||||||
|
desktopSettings: SyncCatalogItem[];
|
||||||
|
editorSettings: SyncCatalogItem[];
|
||||||
|
aiConfigs: SyncCatalogItem[];
|
||||||
|
aiConfigsLocked: boolean;
|
||||||
|
pluginUiStorage: PluginUiStorageItemRef[];
|
||||||
|
pluginUiStorageLocked: boolean;
|
||||||
|
hasSidebarLayout: boolean;
|
||||||
|
hasPinnedTreeNodeIds: boolean;
|
||||||
|
selection?: SyncSelection;
|
||||||
|
}
|
||||||
|
|
||||||
export interface WebDavDownloadResult {
|
export interface WebDavDownloadResult {
|
||||||
summary: WebDavSyncSummary;
|
summary: WebDavSyncSummary;
|
||||||
editorSettings?: unknown;
|
editorSettings?: unknown;
|
||||||
@@ -1061,17 +1110,26 @@ export async function forgetWebdavSyncSecretsPassphrase(): Promise<void> {
|
|||||||
return invoke("forget_webdav_sync_secrets_passphrase");
|
return invoke("forget_webdav_sync_secrets_passphrase");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false): Promise<WebDavSyncSummary> {
|
export async function cloudSyncLocalCatalog(editorSettings?: unknown): Promise<SyncSnapshotCatalog> {
|
||||||
|
return invoke("cloud_sync_local_catalog", { editorSettings });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function webdavSyncInspect(config: WebDavConfig, secretsPassphrase?: string): Promise<SyncSnapshotCatalog> {
|
||||||
|
return invoke("webdav_sync_inspect", { config, secretsPassphrase });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false, selection?: SyncSelection): Promise<WebDavSyncSummary> {
|
||||||
return invoke("webdav_sync_upload", {
|
return invoke("webdav_sync_upload", {
|
||||||
config,
|
config,
|
||||||
editorSettings,
|
editorSettings,
|
||||||
secretsPassphrase,
|
secretsPassphrase,
|
||||||
includeSecrets,
|
includeSecrets,
|
||||||
|
selection,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true): Promise<WebDavDownloadResult> {
|
export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true, selection?: SyncSelection): Promise<WebDavDownloadResult> {
|
||||||
return invoke("webdav_sync_download", { config, secretsPassphrase, restoreSecrets });
|
return invoke("webdav_sync_download", { config, secretsPassphrase, restoreSecrets, selection });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function snippetSyncTest(config: SnippetSyncConfig): Promise<void> {
|
export async function snippetSyncTest(config: SnippetSyncConfig): Promise<void> {
|
||||||
@@ -1102,18 +1160,23 @@ export async function retrySnippetLegacyCleanup(config: SnippetSyncConfig): Prom
|
|||||||
return invoke("retry_snippet_legacy_cleanup", { config });
|
return invoke("retry_snippet_legacy_cleanup", { config });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function snippetSyncUpload(config: SnippetSyncConfig, editorSettings?: unknown, snippetPassphrase?: string, includeSecrets = false, secretsPassphrase?: string): Promise<SnippetSyncSummary> {
|
export async function snippetSyncInspect(config: SnippetSyncConfig, snippetPassphrase?: string, secretsPassphrase?: string): Promise<SyncSnapshotCatalog> {
|
||||||
|
return invoke("snippet_sync_inspect", { config, snippetPassphrase, secretsPassphrase });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function snippetSyncUpload(config: SnippetSyncConfig, editorSettings?: unknown, snippetPassphrase?: string, includeSecrets = false, secretsPassphrase?: string, selection?: SyncSelection): Promise<SnippetSyncSummary> {
|
||||||
return invoke("snippet_sync_upload", {
|
return invoke("snippet_sync_upload", {
|
||||||
config,
|
config,
|
||||||
editorSettings,
|
editorSettings,
|
||||||
snippetPassphrase,
|
snippetPassphrase,
|
||||||
includeSecrets,
|
includeSecrets,
|
||||||
secretsPassphrase,
|
secretsPassphrase,
|
||||||
|
selection,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function snippetSyncDownload(config: SnippetSyncConfig, snippetPassphrase?: string, restoreSecrets = false, secretsPassphrase?: string): Promise<SnippetDownloadResult> {
|
export async function snippetSyncDownload(config: SnippetSyncConfig, snippetPassphrase?: string, restoreSecrets = false, secretsPassphrase?: string, selection?: SyncSelection): Promise<SnippetDownloadResult> {
|
||||||
return invoke("snippet_sync_download", { config, snippetPassphrase, restoreSecrets, secretsPassphrase });
|
return invoke("snippet_sync_download", { config, snippetPassphrase, restoreSecrets, secretsPassphrase, selection });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadPinnedTreeNodeIds(): Promise<string[]> {
|
export async function loadPinnedTreeNodeIds(): Promise<string[]> {
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import type { WebDavConfig } from "@/lib/backend/api";
|
import type { SyncSelection, WebDavConfig } from "@/lib/backend/api";
|
||||||
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
|
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
|
||||||
|
|
||||||
export const WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS = ["dbx-webdav-endpoint", "dbx-webdav-username", "dbx-webdav-remote-path", "dbx-webdav-auto-upload-enabled", "dbx-webdav-auto-upload-interval-minutes"] as const;
|
export const WEB_DAV_BACKUP_SELECTION_STORAGE_KEY = "dbx-webdav-backup-selection";
|
||||||
|
export const WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS = ["dbx-webdav-endpoint", "dbx-webdav-username", "dbx-webdav-remote-path", "dbx-webdav-auto-upload-enabled", "dbx-webdav-auto-upload-interval-minutes", WEB_DAV_BACKUP_SELECTION_STORAGE_KEY] as const;
|
||||||
|
|
||||||
export const DEFAULT_WEB_DAV_REMOTE_PATH = "DBX/sync/snapshot.json";
|
export const DEFAULT_WEB_DAV_REMOTE_PATH = "DBX/sync/snapshot.json";
|
||||||
export const DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES = 30;
|
export const DEFAULT_WEB_DAV_AUTO_UPLOAD_INTERVAL_MINUTES = 30;
|
||||||
@@ -43,3 +44,20 @@ export function writeWebDavAutoUploadFields(config: WebDavConfig, autoUpload: {
|
|||||||
safeLocalStorageSet("dbx-webdav-auto-upload-enabled", String(autoUpload.enabled));
|
safeLocalStorageSet("dbx-webdav-auto-upload-enabled", String(autoUpload.enabled));
|
||||||
safeLocalStorageSet("dbx-webdav-auto-upload-interval-minutes", String(normalizedWebDavAutoUploadInterval(autoUpload.intervalMinutes)));
|
safeLocalStorageSet("dbx-webdav-auto-upload-interval-minutes", String(normalizedWebDavAutoUploadInterval(autoUpload.intervalMinutes)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function readWebDavBackupSelection(): SyncSelection | undefined {
|
||||||
|
const serialized = safeLocalStorageGet(WEB_DAV_BACKUP_SELECTION_STORAGE_KEY);
|
||||||
|
if (!serialized) return undefined;
|
||||||
|
try {
|
||||||
|
const selection = JSON.parse(serialized) as SyncSelection;
|
||||||
|
if (typeof selection !== "object" || selection === null || typeof selection.includeSecrets !== "boolean") return undefined;
|
||||||
|
return selection;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeWebDavBackupSelection(selection: SyncSelection) {
|
||||||
|
safeLocalStorageSet(WEB_DAV_BACKUP_SELECTION_STORAGE_KEY, JSON.stringify(selection));
|
||||||
|
if (typeof window !== "undefined") window.dispatchEvent(new Event("dbx:webdav-auto-upload-config-changed"));
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -319,19 +319,28 @@ pub struct MigrationReport {
|
|||||||
/// re-encryption inside the storage boundary.
|
/// re-encryption inside the storage boundary.
|
||||||
pub(crate) struct SyncImportPlan {
|
pub(crate) struct SyncImportPlan {
|
||||||
pub connections: Vec<ConnectionConfig>,
|
pub connections: Vec<ConnectionConfig>,
|
||||||
|
pub merge_connections: bool,
|
||||||
pub tunnel_profiles: Option<Vec<TransportLayerConfig>>,
|
pub tunnel_profiles: Option<Vec<TransportLayerConfig>>,
|
||||||
pub tunnel_secret_profiles: Option<Vec<TransportLayerConfig>>,
|
pub tunnel_secret_profiles: Option<Vec<TransportLayerConfig>>,
|
||||||
|
pub merge_tunnel_profiles: bool,
|
||||||
pub sidebar_layout: Option<serde_json::Value>,
|
pub sidebar_layout: Option<serde_json::Value>,
|
||||||
pub pinned_tree_node_ids: Vec<String>,
|
pub pinned_tree_node_ids: Option<Vec<String>>,
|
||||||
pub saved_sql: SavedSqlLibrary,
|
pub saved_sql: SavedSqlLibrary,
|
||||||
|
pub merge_saved_sql: bool,
|
||||||
pub desktop_settings: DesktopSettings,
|
pub desktop_settings: DesktopSettings,
|
||||||
|
pub desktop_settings_keys: Option<Vec<String>>,
|
||||||
pub editor_settings: Option<serde_json::Value>,
|
pub editor_settings: Option<serde_json::Value>,
|
||||||
|
pub merge_editor_settings: bool,
|
||||||
|
pub editor_settings_keys: Option<Vec<String>>,
|
||||||
pub connection_secrets: Option<Vec<SyncImportSecret>>,
|
pub connection_secrets: Option<Vec<SyncImportSecret>>,
|
||||||
|
pub connection_secret_ids: Option<Vec<String>>,
|
||||||
|
pub preserve_local_connection_strings: Vec<String>,
|
||||||
/// Keep destination plugin credentials when the transport payload
|
/// Keep destination plugin credentials when the transport payload
|
||||||
/// intentionally omitted plugin secrets.
|
/// intentionally omitted plugin secrets.
|
||||||
pub preserve_plugin_secrets: bool,
|
pub preserve_plugin_secrets: bool,
|
||||||
pub sync_credentials: Option<Vec<SyncImportCredential>>,
|
pub sync_credentials: Option<Vec<SyncImportCredential>>,
|
||||||
pub ai_configs: Option<Vec<AiConfigItem>>,
|
pub ai_configs: Option<Vec<AiConfigItem>>,
|
||||||
|
pub merge_ai_configs: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct SyncImportSecret {
|
pub(crate) struct SyncImportSecret {
|
||||||
@@ -5924,25 +5933,47 @@ impl Storage {
|
|||||||
self.with_conn(move |conn| {
|
self.with_conn(move |conn| {
|
||||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
|
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
apply_sync_connections_in_tx(&tx, &codec, &plan.connections)?;
|
apply_sync_connections_in_tx(&tx, &codec, &plan.connections, plan.merge_connections)?;
|
||||||
if let Some(profiles) = &plan.tunnel_profiles {
|
if let Some(profiles) = &plan.tunnel_profiles {
|
||||||
apply_sync_tunnel_profiles_in_tx(&tx, &codec, profiles, plan.tunnel_secret_profiles.as_deref())?;
|
apply_sync_tunnel_profiles_in_tx(
|
||||||
|
&tx,
|
||||||
|
&codec,
|
||||||
|
profiles,
|
||||||
|
plan.tunnel_secret_profiles.as_deref(),
|
||||||
|
plan.merge_tunnel_profiles,
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
if let Some(layout) = &plan.sidebar_layout {
|
if let Some(layout) = &plan.sidebar_layout {
|
||||||
let json = serde_json::to_string(layout).map_err(|e| e.to_string())?;
|
let json = serde_json::to_string(layout).map_err(|e| e.to_string())?;
|
||||||
tx.execute("INSERT OR REPLACE INTO sidebar_layout (id, layout_json) VALUES (1, ?1)", [json])
|
tx.execute("INSERT OR REPLACE INTO sidebar_layout (id, layout_json) VALUES (1, ?1)", [json])
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
let pinned = serde_json::to_string(&plan.pinned_tree_node_ids).map_err(|e| e.to_string())?;
|
if let Some(pinned_tree_node_ids) = &plan.pinned_tree_node_ids {
|
||||||
update_app_settings_key_in_tx(
|
let pinned = serde_json::to_string(pinned_tree_node_ids).map_err(|e| e.to_string())?;
|
||||||
&tx,
|
update_app_settings_key_in_tx(
|
||||||
"pinned_tree_node_ids",
|
&tx,
|
||||||
serde_json::from_str(&pinned).map_err(|e| e.to_string())?,
|
"pinned_tree_node_ids",
|
||||||
)?;
|
serde_json::from_str(&pinned).map_err(|e| e.to_string())?,
|
||||||
apply_saved_sql_in_tx(&tx, &plan.saved_sql)?;
|
)?;
|
||||||
apply_desktop_settings_in_tx(&tx, &plan.desktop_settings)?;
|
}
|
||||||
|
apply_saved_sql_in_tx(&tx, &plan.saved_sql, plan.merge_saved_sql)?;
|
||||||
|
apply_desktop_settings_in_tx(&tx, &plan.desktop_settings, plan.desktop_settings_keys.as_deref())?;
|
||||||
if let Some(editor_settings) = &plan.editor_settings {
|
if let Some(editor_settings) = &plan.editor_settings {
|
||||||
let value = serde_json::to_string(editor_settings).map_err(|e| e.to_string())?;
|
let mut value = editor_settings.clone();
|
||||||
|
if plan.merge_editor_settings {
|
||||||
|
let current = tx
|
||||||
|
.query_row(
|
||||||
|
"SELECT value_json FROM app_state WHERE key = ?1",
|
||||||
|
[APP_STATE_EDITOR_SETTINGS_KEY],
|
||||||
|
|row| row.get::<_, String>(0),
|
||||||
|
)
|
||||||
|
.optional()
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.and_then(|json| serde_json::from_str::<serde_json::Value>(&json).ok())
|
||||||
|
.unwrap_or_else(|| serde_json::json!({}));
|
||||||
|
value = merge_json_object_fields(current, value, plan.editor_settings_keys.as_deref());
|
||||||
|
}
|
||||||
|
let value = serde_json::to_string(&value).map_err(|e| e.to_string())?;
|
||||||
tx.execute(
|
tx.execute(
|
||||||
"INSERT OR REPLACE INTO app_state (key, value_json) VALUES (?1, ?2)",
|
"INSERT OR REPLACE INTO app_state (key, value_json) VALUES (?1, ?2)",
|
||||||
params![APP_STATE_EDITOR_SETTINGS_KEY, value],
|
params![APP_STATE_EDITOR_SETTINGS_KEY, value],
|
||||||
@@ -5950,10 +5981,15 @@ impl Storage {
|
|||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
if let Some(ai_configs) = &plan.ai_configs {
|
if let Some(ai_configs) = &plan.ai_configs {
|
||||||
apply_ai_configs_in_tx(&tx, &codec, ai_configs)?;
|
apply_ai_configs_in_tx(&tx, &codec, ai_configs, plan.merge_ai_configs)?;
|
||||||
}
|
}
|
||||||
if let Some(secrets) = &plan.connection_secrets {
|
if let Some(secrets) = &plan.connection_secrets {
|
||||||
clear_sync_connection_secrets_in_tx(&tx, &plan.connections, plan.preserve_plugin_secrets)?;
|
clear_sync_connection_secrets_in_tx(
|
||||||
|
&tx,
|
||||||
|
plan.connection_secret_ids.as_deref().unwrap_or(&[]),
|
||||||
|
&plan.preserve_local_connection_strings,
|
||||||
|
plan.preserve_plugin_secrets,
|
||||||
|
)?;
|
||||||
for secret in secrets {
|
for secret in secrets {
|
||||||
if secret.secret.is_empty() {
|
if secret.secret.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
@@ -7949,12 +7985,17 @@ fn apply_sync_connections_in_tx(
|
|||||||
tx: &Transaction<'_>,
|
tx: &Transaction<'_>,
|
||||||
codec: &SecretCodec,
|
codec: &SecretCodec,
|
||||||
configs: &[ConnectionConfig],
|
configs: &[ConnectionConfig],
|
||||||
|
merge_existing: bool,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let replacement_ids = configs.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
|
let mut retained_ids = if merge_existing {
|
||||||
let mut retained_ids = preserve_unreadable_connections_for_replacement(tx, &replacement_ids)?;
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
let replacement_ids = configs.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
|
||||||
|
preserve_unreadable_connections_for_replacement(tx, &replacement_ids)?
|
||||||
|
};
|
||||||
for config in configs {
|
for config in configs {
|
||||||
let config = config.canonicalized();
|
let config = config.canonicalized();
|
||||||
if !config.save_password {
|
if !config.save_password && !merge_existing {
|
||||||
persist_secret_in_tx(tx, codec, &config.id, "password", "")?;
|
persist_secret_in_tx(tx, codec, &config.id, "password", "")?;
|
||||||
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
|
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
|
||||||
}
|
}
|
||||||
@@ -7965,29 +8006,51 @@ fn apply_sync_connections_in_tx(
|
|||||||
}
|
}
|
||||||
let sanitized = sanitized_connection_config(&config);
|
let sanitized = sanitized_connection_config(&config);
|
||||||
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
|
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
|
||||||
tx.execute("INSERT INTO connections (id, config_json) VALUES (?1, ?2)", params![config.id, json])
|
tx.execute("INSERT OR REPLACE INTO connections (id, config_json) VALUES (?1, ?2)", params![config.id, json])
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
retained_ids.extend(configs.iter().map(|config| config.id.clone()));
|
retained_ids.extend(configs.iter().map(|config| config.id.clone()));
|
||||||
delete_unreferenced_connection_secrets_in_tx(tx, &retained_ids)
|
if merge_existing {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
delete_unreferenced_connection_secrets_in_tx(tx, &retained_ids)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn clear_sync_connection_secrets_in_tx(
|
fn clear_sync_connection_secrets_in_tx(
|
||||||
tx: &Transaction<'_>,
|
tx: &Transaction<'_>,
|
||||||
configs: &[ConnectionConfig],
|
connection_ids: &[String],
|
||||||
|
preserve_connection_strings: &[String],
|
||||||
preserve_plugin_secrets: bool,
|
preserve_plugin_secrets: bool,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
for config in configs {
|
let preserve_connection_strings = preserve_connection_strings.iter().map(String::as_str).collect::<HashSet<_>>();
|
||||||
if preserve_plugin_secrets {
|
for connection_id in connection_ids {
|
||||||
|
let preserve_connection_string = preserve_connection_strings.contains(connection_id.as_str());
|
||||||
|
if preserve_plugin_secrets && preserve_connection_string {
|
||||||
|
tx.execute(
|
||||||
|
"DELETE FROM connection_secrets
|
||||||
|
WHERE connection_id = ?1
|
||||||
|
AND key NOT LIKE 'plugin_connection.%'
|
||||||
|
AND key <> 'connection_string'",
|
||||||
|
[connection_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
} else if preserve_plugin_secrets {
|
||||||
tx.execute(
|
tx.execute(
|
||||||
"DELETE FROM connection_secrets
|
"DELETE FROM connection_secrets
|
||||||
WHERE connection_id = ?1
|
WHERE connection_id = ?1
|
||||||
AND key NOT LIKE 'plugin_connection.%'",
|
AND key NOT LIKE 'plugin_connection.%'",
|
||||||
[&config.id],
|
[connection_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
} else if preserve_connection_string {
|
||||||
|
tx.execute(
|
||||||
|
"DELETE FROM connection_secrets WHERE connection_id = ?1 AND key <> 'connection_string'",
|
||||||
|
[connection_id],
|
||||||
)
|
)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
} else {
|
} else {
|
||||||
tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1", [&config.id])
|
tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1", [connection_id])
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7999,6 +8062,7 @@ fn apply_sync_tunnel_profiles_in_tx(
|
|||||||
codec: &SecretCodec,
|
codec: &SecretCodec,
|
||||||
profiles: &[TransportLayerConfig],
|
profiles: &[TransportLayerConfig],
|
||||||
secret_profiles: Option<&[TransportLayerConfig]>,
|
secret_profiles: Option<&[TransportLayerConfig]>,
|
||||||
|
merge_existing: bool,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let mut existing = HashMap::<String, TransportLayerConfig>::new();
|
let mut existing = HashMap::<String, TransportLayerConfig>::new();
|
||||||
let mut statement = tx.prepare("SELECT id, config_json FROM tunnel_profiles").map_err(|e| e.to_string())?;
|
let mut statement = tx.prepare("SELECT id, config_json FROM tunnel_profiles").map_err(|e| e.to_string())?;
|
||||||
@@ -8029,6 +8093,9 @@ fn apply_sync_tunnel_profiles_in_tx(
|
|||||||
Some(profile) => (profile, true),
|
Some(profile) => (profile, true),
|
||||||
None => (profile.clone(), false),
|
None => (profile.clone(), false),
|
||||||
};
|
};
|
||||||
|
if let Some(previous) = existing.get(profile.id()) {
|
||||||
|
preserve_tunnel_profile_local_paths(&mut profile, previous);
|
||||||
|
}
|
||||||
if !has_synced_secrets {
|
if !has_synced_secrets {
|
||||||
if let Some(previous) = existing.get(profile.id()) {
|
if let Some(previous) = existing.get(profile.id()) {
|
||||||
merge_missing_tunnel_profile_secrets(&mut profile, previous);
|
merge_missing_tunnel_profile_secrets(&mut profile, previous);
|
||||||
@@ -8037,10 +8104,19 @@ fn apply_sync_tunnel_profiles_in_tx(
|
|||||||
effective.push(profile);
|
effective.push(profile);
|
||||||
}
|
}
|
||||||
|
|
||||||
tx.execute("DELETE FROM tunnel_profiles", []).map_err(|e| e.to_string())?;
|
if !merge_existing {
|
||||||
tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'tunnel_profile.%'", [])
|
tx.execute("DELETE FROM tunnel_profiles", []).map_err(|e| e.to_string())?;
|
||||||
.map_err(|e| e.to_string())?;
|
tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'tunnel_profile.%'", [])
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
for profile in effective {
|
for profile in effective {
|
||||||
|
if merge_existing {
|
||||||
|
tx.execute(
|
||||||
|
"DELETE FROM connection_secrets WHERE connection_id = ?1",
|
||||||
|
[format!("{TUNNEL_SECRET_NAMESPACE_PREFIX}{}", profile.id())],
|
||||||
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
let mut sanitized = profile.clone();
|
let mut sanitized = profile.clone();
|
||||||
sanitized.scrub_secrets();
|
sanitized.scrub_secrets();
|
||||||
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
|
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
|
||||||
@@ -8059,14 +8135,64 @@ fn apply_sync_tunnel_profiles_in_tx(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_ai_configs_in_tx(tx: &Transaction<'_>, codec: &SecretCodec, configs: &[AiConfigItem]) -> Result<(), String> {
|
fn preserve_tunnel_profile_local_paths(remote: &mut TransportLayerConfig, local: &TransportLayerConfig) {
|
||||||
tx.execute("DELETE FROM ai_configs", []).map_err(|e| e.to_string())?;
|
if let (TransportLayerConfig::Ssh(remote), TransportLayerConfig::Ssh(local)) = (remote, local) {
|
||||||
tx.execute("DELETE FROM ai_config", []).map_err(|e| e.to_string())?;
|
if remote.key_path.is_empty() {
|
||||||
tx.execute("DELETE FROM ai_provider_configs", []).map_err(|e| e.to_string())?;
|
remote.key_path.clone_from(&local.key_path);
|
||||||
tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'ai_config.%'", [])
|
}
|
||||||
.map_err(|e| e.to_string())?;
|
if remote.ssh_agent_sock_path.is_empty() {
|
||||||
|
remote.ssh_agent_sock_path.clone_from(&local.ssh_agent_sock_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_ai_configs_in_tx(
|
||||||
|
tx: &Transaction<'_>,
|
||||||
|
codec: &SecretCodec,
|
||||||
|
configs: &[AiConfigItem],
|
||||||
|
merge_existing: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let existing_configs = {
|
||||||
|
let mut statement = tx.prepare("SELECT id, config_json FROM ai_configs").map_err(|error| error.to_string())?;
|
||||||
|
let rows = statement
|
||||||
|
.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
|
||||||
|
.map_err(|error| error.to_string())?
|
||||||
|
.collect::<Result<Vec<_>, _>>()
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
let mut existing = HashMap::with_capacity(rows.len());
|
||||||
|
for (id, json) in rows {
|
||||||
|
let config: AiConfig = serde_json::from_str(&json).map_err(|error| error.to_string())?;
|
||||||
|
existing.insert(id, config);
|
||||||
|
}
|
||||||
|
existing
|
||||||
|
};
|
||||||
|
if !merge_existing {
|
||||||
|
tx.execute("DELETE FROM ai_configs", []).map_err(|e| e.to_string())?;
|
||||||
|
tx.execute("DELETE FROM ai_config", []).map_err(|e| e.to_string())?;
|
||||||
|
tx.execute("DELETE FROM ai_provider_configs", []).map_err(|e| e.to_string())?;
|
||||||
|
tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'ai_config.%'", [])
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
for item in configs {
|
for item in configs {
|
||||||
let (sanitized, secrets) = split_ai_config_secrets(&item.config)?;
|
if merge_existing {
|
||||||
|
tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1", [format!("ai_config.{}", item.id)])
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if item.is_default {
|
||||||
|
tx.execute("UPDATE ai_configs SET is_default = 0", []).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut config = item.config.clone();
|
||||||
|
clear_ai_config_device_paths(&mut config);
|
||||||
|
let local = existing_configs.get(&item.id).or_else(|| {
|
||||||
|
let mut matching_provider =
|
||||||
|
existing_configs.values().filter(|local| local.provider.as_str() == config.provider.as_str());
|
||||||
|
let candidate = matching_provider.next()?;
|
||||||
|
matching_provider.next().is_none().then_some(candidate)
|
||||||
|
});
|
||||||
|
if let Some(local) = local {
|
||||||
|
preserve_ai_config_device_paths(&mut config, local);
|
||||||
|
}
|
||||||
|
let (sanitized, secrets) = split_ai_config_secrets(&config)?;
|
||||||
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
|
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
|
||||||
let models_json = serde_json::to_string(&sanitized.models).map_err(|e| e.to_string())?;
|
let models_json = serde_json::to_string(&sanitized.models).map_err(|e| e.to_string())?;
|
||||||
tx.execute(
|
tx.execute(
|
||||||
@@ -8087,6 +8213,39 @@ fn apply_ai_configs_in_tx(tx: &Transaction<'_>, codec: &SecretCodec, configs: &[
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn clear_ai_config_device_paths(config: &mut AiConfig) {
|
||||||
|
config.codex_cli_path = None;
|
||||||
|
config.claude_code_cli_path = None;
|
||||||
|
config.pi_agent_cli_path = None;
|
||||||
|
config.opencode_cli_path = None;
|
||||||
|
config.cursor_cli_path = None;
|
||||||
|
config.grok_cli_path = None;
|
||||||
|
config.codebuddy_cli_path = None;
|
||||||
|
config.qoder_cli_path = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preserve_ai_config_device_paths(remote: &mut AiConfig, local: &AiConfig) {
|
||||||
|
match (&remote.provider, &local.provider) {
|
||||||
|
(AiProvider::CodexCli, AiProvider::CodexCli) => remote.codex_cli_path.clone_from(&local.codex_cli_path),
|
||||||
|
(AiProvider::ClaudeCodeCli, AiProvider::ClaudeCodeCli) => {
|
||||||
|
remote.claude_code_cli_path.clone_from(&local.claude_code_cli_path)
|
||||||
|
}
|
||||||
|
(AiProvider::PiAgentCli, AiProvider::PiAgentCli) => {
|
||||||
|
remote.pi_agent_cli_path.clone_from(&local.pi_agent_cli_path)
|
||||||
|
}
|
||||||
|
(AiProvider::OpenCodeCli, AiProvider::OpenCodeCli) => {
|
||||||
|
remote.opencode_cli_path.clone_from(&local.opencode_cli_path)
|
||||||
|
}
|
||||||
|
(AiProvider::CursorCli, AiProvider::CursorCli) => remote.cursor_cli_path.clone_from(&local.cursor_cli_path),
|
||||||
|
(AiProvider::GrokCli, AiProvider::GrokCli) => remote.grok_cli_path.clone_from(&local.grok_cli_path),
|
||||||
|
(AiProvider::CodeBuddyCli, AiProvider::CodeBuddyCli) => {
|
||||||
|
remote.codebuddy_cli_path.clone_from(&local.codebuddy_cli_path)
|
||||||
|
}
|
||||||
|
(AiProvider::QoderCli, AiProvider::QoderCli) => remote.qoder_cli_path.clone_from(&local.qoder_cli_path),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn update_app_settings_key_in_tx(tx: &Transaction<'_>, key: &str, value: serde_json::Value) -> Result<(), String> {
|
fn update_app_settings_key_in_tx(tx: &Transaction<'_>, key: &str, value: serde_json::Value) -> Result<(), String> {
|
||||||
let current: Option<String> = tx
|
let current: Option<String> = tx
|
||||||
.query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))
|
.query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))
|
||||||
@@ -8107,7 +8266,27 @@ fn update_app_settings_key_in_tx(tx: &Transaction<'_>, key: &str, value: serde_j
|
|||||||
.map_err(|e| e.to_string())
|
.map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_desktop_settings_in_tx(tx: &Transaction<'_>, settings: &DesktopSettings) -> Result<(), String> {
|
fn merge_json_object_fields(
|
||||||
|
local: serde_json::Value,
|
||||||
|
remote: serde_json::Value,
|
||||||
|
selected_keys: Option<&[String]>,
|
||||||
|
) -> serde_json::Value {
|
||||||
|
let Some(remote) = remote.as_object() else { return remote };
|
||||||
|
let mut merged = local.as_object().cloned().unwrap_or_default();
|
||||||
|
for (key, value) in remote {
|
||||||
|
if selected_keys.is_some_and(|keys| !keys.iter().any(|selected| selected == key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
merged.insert(key.clone(), value.clone());
|
||||||
|
}
|
||||||
|
serde_json::Value::Object(merged)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_desktop_settings_in_tx(
|
||||||
|
tx: &Transaction<'_>,
|
||||||
|
settings: &DesktopSettings,
|
||||||
|
selected_keys: Option<&[String]>,
|
||||||
|
) -> Result<(), String> {
|
||||||
let mut values = serde_json::Map::new();
|
let mut values = serde_json::Map::new();
|
||||||
values.insert("show_tray_icon".to_string(), serde_json::Value::Bool(settings.show_tray_icon));
|
values.insert("show_tray_icon".to_string(), serde_json::Value::Bool(settings.show_tray_icon));
|
||||||
values.insert("icon_theme".to_string(), serde_json::to_value(settings.icon_theme).map_err(|e| e.to_string())?);
|
values.insert("icon_theme".to_string(), serde_json::to_value(settings.icon_theme).map_err(|e| e.to_string())?);
|
||||||
@@ -8158,6 +8337,9 @@ fn apply_desktop_settings_in_tx(tx: &Transaction<'_>, settings: &DesktopSettings
|
|||||||
.transpose()?
|
.transpose()?
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
|
if selected_keys.is_some_and(|keys| !keys.iter().any(|selected| selected == &key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
merged.insert(key, value);
|
merged.insert(key, value);
|
||||||
}
|
}
|
||||||
tx.execute(
|
tx.execute(
|
||||||
@@ -8168,19 +8350,34 @@ fn apply_desktop_settings_in_tx(tx: &Transaction<'_>, settings: &DesktopSettings
|
|||||||
.map_err(|e| e.to_string())
|
.map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_saved_sql_in_tx(tx: &Transaction<'_>, library: &SavedSqlLibrary) -> Result<(), String> {
|
fn apply_saved_sql_in_tx(tx: &Transaction<'_>, library: &SavedSqlLibrary, merge_existing: bool) -> Result<(), String> {
|
||||||
tx.execute("DELETE FROM saved_sql_files", []).map_err(|e| e.to_string())?;
|
let mut folder_ids = HashSet::with_capacity(library.folders.len());
|
||||||
tx.execute("DELETE FROM saved_sql_folders", []).map_err(|e| e.to_string())?;
|
for folder in &library.folders {
|
||||||
|
if !folder_ids.insert(folder.id.as_str()) {
|
||||||
|
return Err(format!("duplicate saved SQL folder id: {}", folder.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut file_ids = HashSet::with_capacity(library.files.len());
|
||||||
|
for file in &library.files {
|
||||||
|
if !file_ids.insert(file.id.as_str()) {
|
||||||
|
return Err(format!("duplicate saved SQL file id: {}", file.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !merge_existing {
|
||||||
|
tx.execute("DELETE FROM saved_sql_files", []).map_err(|e| e.to_string())?;
|
||||||
|
tx.execute("DELETE FROM saved_sql_folders", []).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
for folder in &library.folders {
|
for folder in &library.folders {
|
||||||
tx.execute(
|
tx.execute(
|
||||||
"INSERT INTO saved_sql_folders (id, connection_id, parent_folder_id, name, order_index, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
"INSERT OR REPLACE INTO saved_sql_folders (id, connection_id, parent_folder_id, name, order_index, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
params![folder.id, folder.connection_id, folder.parent_folder_id, folder.name, folder.order_index, folder.created_at, folder.updated_at],
|
params![folder.id, folder.connection_id, folder.parent_folder_id, folder.name, folder.order_index, folder.created_at, folder.updated_at],
|
||||||
)
|
)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
for file in &library.files {
|
for file in &library.files {
|
||||||
tx.execute(
|
tx.execute(
|
||||||
"INSERT INTO saved_sql_files (id, connection_id, folder_id, name, database_name, catalog_name, schema_name, sql_text, order_index, open_count, opened_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
"INSERT OR REPLACE INTO saved_sql_files (id, connection_id, folder_id, name, database_name, catalog_name, schema_name, sql_text, order_index, open_count, opened_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
params![file.id, file.connection_id, file.folder_id, file.name, file.database, file.catalog, file.schema, file.sql, file.order_index, file.open_count, file.opened_at, file.created_at, file.updated_at],
|
params![file.id, file.connection_id, file.folder_id, file.name, file.database, file.catalog, file.schema, file.sql, file.order_index, file.open_count, file.opened_at, file.created_at, file.updated_at],
|
||||||
)
|
)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
@@ -13402,10 +13599,12 @@ mod tests {
|
|||||||
incoming.url_params = Some("applicationName=dbx&sslmode=require".to_string());
|
incoming.url_params = Some("applicationName=dbx&sslmode=require".to_string());
|
||||||
let plan = SyncImportPlan {
|
let plan = SyncImportPlan {
|
||||||
connections: vec![incoming],
|
connections: vec![incoming],
|
||||||
|
merge_connections: false,
|
||||||
tunnel_profiles: Some(Vec::new()),
|
tunnel_profiles: Some(Vec::new()),
|
||||||
tunnel_secret_profiles: None,
|
tunnel_secret_profiles: None,
|
||||||
|
merge_tunnel_profiles: false,
|
||||||
sidebar_layout: None,
|
sidebar_layout: None,
|
||||||
pinned_tree_node_ids: Vec::new(),
|
pinned_tree_node_ids: Some(Vec::new()),
|
||||||
saved_sql: SavedSqlLibrary {
|
saved_sql: SavedSqlLibrary {
|
||||||
folders: vec![
|
folders: vec![
|
||||||
SavedSqlFolder {
|
SavedSqlFolder {
|
||||||
@@ -13429,12 +13628,19 @@ mod tests {
|
|||||||
],
|
],
|
||||||
files: Vec::new(),
|
files: Vec::new(),
|
||||||
},
|
},
|
||||||
|
merge_saved_sql: false,
|
||||||
desktop_settings: settings,
|
desktop_settings: settings,
|
||||||
|
desktop_settings_keys: None,
|
||||||
editor_settings: None,
|
editor_settings: None,
|
||||||
|
merge_editor_settings: false,
|
||||||
|
editor_settings_keys: None,
|
||||||
connection_secrets: None,
|
connection_secrets: None,
|
||||||
|
connection_secret_ids: None,
|
||||||
|
preserve_local_connection_strings: Vec::new(),
|
||||||
preserve_plugin_secrets: false,
|
preserve_plugin_secrets: false,
|
||||||
sync_credentials: None,
|
sync_credentials: None,
|
||||||
ai_configs: None,
|
ai_configs: None,
|
||||||
|
merge_ai_configs: false,
|
||||||
};
|
};
|
||||||
assert!(storage.apply_sync_import_transaction(plan).await.is_err());
|
assert!(storage.apply_sync_import_transaction(plan).await.is_err());
|
||||||
let connections = storage.load_connections().await.unwrap();
|
let connections = storage.load_connections().await.unwrap();
|
||||||
|
|||||||
@@ -1337,6 +1337,8 @@ async fn serve() {
|
|||||||
post(routes::cloud_sync::forget_webdav_sync_secrets_passphrase),
|
post(routes::cloud_sync::forget_webdav_sync_secrets_passphrase),
|
||||||
)
|
)
|
||||||
.route("/cloud-sync/webdav/upload", post(routes::cloud_sync::webdav_sync_upload))
|
.route("/cloud-sync/webdav/upload", post(routes::cloud_sync::webdav_sync_upload))
|
||||||
|
.route("/cloud-sync/catalog/local", post(routes::cloud_sync::cloud_sync_local_catalog))
|
||||||
|
.route("/cloud-sync/webdav/inspect", post(routes::cloud_sync::webdav_sync_inspect))
|
||||||
.route("/cloud-sync/webdav/download", post(routes::cloud_sync::webdav_sync_download))
|
.route("/cloud-sync/webdav/download", post(routes::cloud_sync::webdav_sync_download))
|
||||||
.route("/cloud-sync/snippet/test", post(routes::cloud_sync::snippet_sync_test))
|
.route("/cloud-sync/snippet/test", post(routes::cloud_sync::snippet_sync_test))
|
||||||
.route("/cloud-sync/snippet/token-status", post(routes::cloud_sync::snippet_token_status))
|
.route("/cloud-sync/snippet/token-status", post(routes::cloud_sync::snippet_token_status))
|
||||||
@@ -1346,6 +1348,7 @@ async fn serve() {
|
|||||||
.route("/cloud-sync/snippet/save-id", post(routes::cloud_sync::save_snippet_sync_id))
|
.route("/cloud-sync/snippet/save-id", post(routes::cloud_sync::save_snippet_sync_id))
|
||||||
.route("/cloud-sync/snippet/retry-legacy-cleanup", post(routes::cloud_sync::retry_snippet_legacy_cleanup))
|
.route("/cloud-sync/snippet/retry-legacy-cleanup", post(routes::cloud_sync::retry_snippet_legacy_cleanup))
|
||||||
.route("/cloud-sync/snippet/upload", post(routes::cloud_sync::snippet_sync_upload))
|
.route("/cloud-sync/snippet/upload", post(routes::cloud_sync::snippet_sync_upload))
|
||||||
|
.route("/cloud-sync/snippet/inspect", post(routes::cloud_sync::snippet_sync_inspect))
|
||||||
.route("/cloud-sync/snippet/download", post(routes::cloud_sync::snippet_sync_download));
|
.route("/cloud-sync/snippet/download", post(routes::cloud_sync::snippet_sync_download));
|
||||||
|
|
||||||
// Do not expose DuckDB-only handlers from builds that omit DuckDB sidecar support.
|
// Do not expose DuckDB-only handlers from builds that omit DuckDB sidecar support.
|
||||||
|
|||||||
@@ -3,15 +3,16 @@ use std::sync::Arc;
|
|||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use axum::Json;
|
use axum::Json;
|
||||||
use dbx_core::cloud_sync::{
|
use dbx_core::cloud_sync::{
|
||||||
apply_sync_snapshot, build_sync_snapshot_with_options, finalize_snippet_migration, forget_snippet_token,
|
apply_sync_snapshot_with_selection, build_sync_snapshot_with_selection, describe_local_sync_state,
|
||||||
forget_webdav_password, forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase,
|
describe_sync_snapshot, finalize_snippet_migration, forget_snippet_token, forget_webdav_password,
|
||||||
resolve_snippet_token, resolve_webdav_password, resolve_webdav_sync_secrets_passphrase,
|
forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase, resolve_snippet_token,
|
||||||
retry_pending_snippet_cleanup, save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token,
|
resolve_webdav_password, resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup,
|
||||||
save_webdav_password, save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference,
|
save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token, save_webdav_password,
|
||||||
snippet_saved_token_status, snippet_sync_settings_for_instance as core_snippet_sync_settings,
|
save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference, snippet_saved_token_status,
|
||||||
webdav_saved_password_status, webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions,
|
snippet_sync_settings_for_instance as core_snippet_sync_settings, webdav_saved_password_status,
|
||||||
ApplySnapshotSummary, SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings,
|
webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions, ApplySnapshotSummary,
|
||||||
SnippetSyncSummary, SnippetTokenStatus, WebDavClient, WebDavConfig, WebDavPasswordStatus, WebDavSyncSecretsStatus,
|
SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings, SnippetSyncSummary, SnippetTokenStatus,
|
||||||
|
SyncSelection, SyncSnapshotCatalog, WebDavClient, WebDavConfig, WebDavPasswordStatus, WebDavSyncSecretsStatus,
|
||||||
WebDavSyncSummary,
|
WebDavSyncSummary,
|
||||||
};
|
};
|
||||||
use dbx_core::storage::DesktopSettings;
|
use dbx_core::storage::DesktopSettings;
|
||||||
@@ -60,6 +61,8 @@ pub struct WebDavUploadRequest {
|
|||||||
/// Explicit opt-in for exporting credentials.
|
/// Explicit opt-in for exporting credentials.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub include_secrets: bool,
|
pub include_secrets: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub selection: Option<SyncSelection>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
@@ -72,6 +75,21 @@ pub struct WebDavDownloadRequest {
|
|||||||
/// restore behavior.
|
/// restore behavior.
|
||||||
#[serde(default = "default_restore_secrets")]
|
#[serde(default = "default_restore_secrets")]
|
||||||
pub restore_secrets: bool,
|
pub restore_secrets: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub selection: Option<SyncSelection>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct WebDavInspectRequest {
|
||||||
|
pub config: WebDavConfig,
|
||||||
|
pub secrets_passphrase: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct LocalCatalogRequest {
|
||||||
|
pub editor_settings: Option<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_restore_secrets() -> bool {
|
fn default_restore_secrets() -> bool {
|
||||||
@@ -107,6 +125,8 @@ pub struct SnippetUploadRequest {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub include_secrets: bool,
|
pub include_secrets: bool,
|
||||||
pub secrets_passphrase: Option<String>,
|
pub secrets_passphrase: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub selection: Option<SyncSelection>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
@@ -117,6 +137,16 @@ pub struct SnippetDownloadRequest {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub restore_secrets: bool,
|
pub restore_secrets: bool,
|
||||||
pub secrets_passphrase: Option<String>,
|
pub secrets_passphrase: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub selection: Option<SyncSelection>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct SnippetInspectRequest {
|
||||||
|
pub config: SnippetSyncConfig,
|
||||||
|
pub snippet_passphrase: Option<String>,
|
||||||
|
pub secrets_passphrase: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
@@ -202,7 +232,7 @@ pub async fn webdav_sync_upload(
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
let passphrase = explicit_passphrase.or(saved_passphrase.as_deref());
|
let passphrase = explicit_passphrase.or(saved_passphrase.as_deref());
|
||||||
let snapshot = build_sync_snapshot_with_options(
|
let snapshot = build_sync_snapshot_with_selection(
|
||||||
&state.app.storage,
|
&state.app.storage,
|
||||||
env!("CARGO_PKG_VERSION"),
|
env!("CARGO_PKG_VERSION"),
|
||||||
req.editor_settings,
|
req.editor_settings,
|
||||||
@@ -213,12 +243,39 @@ pub async fn webdav_sync_upload(
|
|||||||
include_tunnel_secrets: req.include_secrets,
|
include_tunnel_secrets: req.include_secrets,
|
||||||
include_plugin_secrets: req.include_secrets,
|
include_plugin_secrets: req.include_secrets,
|
||||||
},
|
},
|
||||||
|
req.selection.as_ref(),
|
||||||
|
Some(&state.app.plugins),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(AppError::from)?;
|
.map_err(AppError::from)?;
|
||||||
WebDavClient::new(req.config).put_snapshot(&snapshot).await.map(Json).map_err(AppError::from)
|
WebDavClient::new(req.config).put_snapshot(&snapshot).await.map(Json).map_err(AppError::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn cloud_sync_local_catalog(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<LocalCatalogRequest>,
|
||||||
|
) -> Result<Json<SyncSnapshotCatalog>, AppError> {
|
||||||
|
describe_local_sync_state(&state.app.storage, req.editor_settings, Some(&state.app.plugins))
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(AppError::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn webdav_sync_inspect(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(mut req): Json<WebDavInspectRequest>,
|
||||||
|
) -> Result<Json<SyncSnapshotCatalog>, AppError> {
|
||||||
|
resolve_webdav_password(&state.app.storage, &mut req.config).await.map_err(AppError::from)?;
|
||||||
|
let (snapshot, _) = WebDavClient::new(req.config).get_snapshot().await.map_err(AppError::from)?;
|
||||||
|
let explicit = req.secrets_passphrase.as_deref().map(str::trim).filter(|value| !value.is_empty());
|
||||||
|
let saved = if explicit.is_none() {
|
||||||
|
resolve_webdav_sync_secrets_passphrase(&state.app.storage).await.map_err(AppError::from)?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
describe_sync_snapshot(&snapshot, explicit.or(saved.as_deref())).map(Json).map_err(AppError::from)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn webdav_sync_download(
|
pub async fn webdav_sync_download(
|
||||||
State(state): State<Arc<WebState>>,
|
State(state): State<Arc<WebState>>,
|
||||||
Json(mut req): Json<WebDavDownloadRequest>,
|
Json(mut req): Json<WebDavDownloadRequest>,
|
||||||
@@ -231,20 +288,22 @@ pub async fn webdav_sync_download(
|
|||||||
} else {
|
} else {
|
||||||
resolve_webdav_sync_secrets_passphrase(&state.app.storage).await.map_err(AppError::from)?
|
resolve_webdav_sync_secrets_passphrase(&state.app.storage).await.map_err(AppError::from)?
|
||||||
};
|
};
|
||||||
let apply_summary = apply_sync_snapshot(
|
let apply_summary = apply_sync_snapshot_with_selection(
|
||||||
&state.app.storage,
|
&state.app.storage,
|
||||||
&snapshot,
|
&snapshot,
|
||||||
ApplySnapshotOptions {
|
ApplySnapshotOptions {
|
||||||
secrets_passphrase: explicit_passphrase.or(saved_passphrase.as_deref()),
|
secrets_passphrase: explicit_passphrase.or(saved_passphrase.as_deref()),
|
||||||
restore_secrets: req.restore_secrets,
|
restore_secrets: req.restore_secrets,
|
||||||
},
|
},
|
||||||
|
req.selection.as_ref(),
|
||||||
|
Some(&state.app.plugins),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(AppError::from)?;
|
.map_err(AppError::from)?;
|
||||||
Ok(Json(WebDavDownloadResult {
|
Ok(Json(WebDavDownloadResult {
|
||||||
summary,
|
summary,
|
||||||
editor_settings: snapshot.editor_settings,
|
editor_settings: state.app.storage.load_editor_settings().await.map_err(AppError::from)?,
|
||||||
desktop_settings: snapshot.desktop_settings,
|
desktop_settings: state.app.storage.load_desktop_settings().await.map_err(AppError::from)?,
|
||||||
apply_summary,
|
apply_summary,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@@ -328,7 +387,7 @@ pub async fn snippet_sync_upload(
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
let include_secrets = req.include_secrets;
|
let include_secrets = req.include_secrets;
|
||||||
let snapshot = build_sync_snapshot_with_options(
|
let snapshot = build_sync_snapshot_with_selection(
|
||||||
&state.app.storage,
|
&state.app.storage,
|
||||||
env!("CARGO_PKG_VERSION"),
|
env!("CARGO_PKG_VERSION"),
|
||||||
req.editor_settings,
|
req.editor_settings,
|
||||||
@@ -339,6 +398,8 @@ pub async fn snippet_sync_upload(
|
|||||||
include_tunnel_secrets: include_secrets,
|
include_tunnel_secrets: include_secrets,
|
||||||
include_plugin_secrets: include_secrets,
|
include_plugin_secrets: include_secrets,
|
||||||
},
|
},
|
||||||
|
req.selection.as_ref(),
|
||||||
|
Some(&state.app.plugins),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(AppError::from)?;
|
.map_err(AppError::from)?;
|
||||||
@@ -361,24 +422,45 @@ pub async fn snippet_sync_download(
|
|||||||
.get_snapshot(req.snippet_passphrase.as_deref())
|
.get_snapshot(req.snippet_passphrase.as_deref())
|
||||||
.await
|
.await
|
||||||
.map_err(AppError::from)?;
|
.map_err(AppError::from)?;
|
||||||
let apply_summary = apply_sync_snapshot(
|
let apply_summary = apply_sync_snapshot_with_selection(
|
||||||
&state.app.storage,
|
&state.app.storage,
|
||||||
&snapshot,
|
&snapshot,
|
||||||
ApplySnapshotOptions {
|
ApplySnapshotOptions {
|
||||||
secrets_passphrase: req.secrets_passphrase.as_deref(),
|
secrets_passphrase: req.secrets_passphrase.as_deref(),
|
||||||
restore_secrets: req.restore_secrets,
|
restore_secrets: req.restore_secrets,
|
||||||
},
|
},
|
||||||
|
req.selection.as_ref(),
|
||||||
|
Some(&state.app.plugins),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(AppError::from)?;
|
.map_err(AppError::from)?;
|
||||||
Ok(Json(SnippetDownloadResult {
|
Ok(Json(SnippetDownloadResult {
|
||||||
summary,
|
summary,
|
||||||
editor_settings: snapshot.editor_settings,
|
editor_settings: state.app.storage.load_editor_settings().await.map_err(AppError::from)?,
|
||||||
desktop_settings: snapshot.desktop_settings,
|
desktop_settings: state.app.storage.load_desktop_settings().await.map_err(AppError::from)?,
|
||||||
apply_summary,
|
apply_summary,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn snippet_sync_inspect(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(mut req): Json<SnippetInspectRequest>,
|
||||||
|
) -> Result<Json<SyncSnapshotCatalog>, AppError> {
|
||||||
|
resolve_snippet_token(&state.app.storage, &mut req.config).await.map_err(AppError::from)?;
|
||||||
|
let (snapshot, _) = SnippetSyncClient::new(req.config)
|
||||||
|
.map_err(AppError::from)?
|
||||||
|
.get_snapshot(req.snippet_passphrase.as_deref())
|
||||||
|
.await
|
||||||
|
.map_err(AppError::from)?;
|
||||||
|
let explicit = req.secrets_passphrase.as_deref().map(str::trim).filter(|value| !value.is_empty());
|
||||||
|
let saved = if explicit.is_none() {
|
||||||
|
resolve_webdav_sync_secrets_passphrase(&state.app.storage).await.map_err(AppError::from)?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
describe_sync_snapshot(&snapshot, explicit.or(saved.as_deref())).map(Json).map_err(AppError::from)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use dbx_core::cloud_sync::{
|
use dbx_core::cloud_sync::{
|
||||||
apply_sync_snapshot, build_sync_snapshot_with_options, finalize_snippet_migration, forget_snippet_token,
|
apply_sync_snapshot_with_selection, build_sync_snapshot_with_selection, describe_local_sync_state,
|
||||||
forget_webdav_password, forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase,
|
describe_sync_snapshot, finalize_snippet_migration, forget_snippet_token, forget_webdav_password,
|
||||||
resolve_snippet_token, resolve_webdav_password, resolve_webdav_sync_secrets_passphrase,
|
forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase, resolve_snippet_token,
|
||||||
retry_pending_snippet_cleanup, save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token,
|
resolve_webdav_password, resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup,
|
||||||
save_webdav_password, save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference,
|
save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token, save_webdav_password,
|
||||||
snippet_saved_token_status, snippet_sync_settings_for_instance as core_snippet_sync_settings,
|
save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference, snippet_saved_token_status,
|
||||||
webdav_saved_password_status, webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions,
|
snippet_sync_settings_for_instance as core_snippet_sync_settings, webdav_saved_password_status,
|
||||||
ApplySnapshotSummary, SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings,
|
webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions, ApplySnapshotSummary,
|
||||||
SnippetSyncSummary, SnippetTokenStatus, SyncExportOptions, WebDavClient, WebDavConfig, WebDavPasswordStatus,
|
SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings, SnippetSyncSummary, SnippetTokenStatus,
|
||||||
|
SyncExportOptions, SyncSelection, SyncSnapshotCatalog, WebDavClient, WebDavConfig, WebDavPasswordStatus,
|
||||||
WebDavSyncSecretsStatus, WebDavSyncSummary,
|
WebDavSyncSecretsStatus, WebDavSyncSummary,
|
||||||
};
|
};
|
||||||
use dbx_core::storage::DesktopSettings;
|
use dbx_core::storage::DesktopSettings;
|
||||||
@@ -121,6 +122,7 @@ pub async fn webdav_sync_upload(
|
|||||||
editor_settings: Option<serde_json::Value>,
|
editor_settings: Option<serde_json::Value>,
|
||||||
secrets_passphrase: Option<String>,
|
secrets_passphrase: Option<String>,
|
||||||
include_secrets: bool,
|
include_secrets: bool,
|
||||||
|
selection: Option<SyncSelection>,
|
||||||
) -> Result<WebDavSyncSummary, String> {
|
) -> Result<WebDavSyncSummary, String> {
|
||||||
resolve_webdav_password(&state.storage, &mut config).await?;
|
resolve_webdav_password(&state.storage, &mut config).await?;
|
||||||
let explicit_passphrase = secrets_passphrase.as_deref().and_then(|value| {
|
let explicit_passphrase = secrets_passphrase.as_deref().and_then(|value| {
|
||||||
@@ -133,7 +135,7 @@ pub async fn webdav_sync_upload(
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
let passphrase = explicit_passphrase.or(saved_passphrase.as_deref());
|
let passphrase = explicit_passphrase.or(saved_passphrase.as_deref());
|
||||||
let snapshot = build_sync_snapshot_with_options(
|
let snapshot = build_sync_snapshot_with_selection(
|
||||||
&state.storage,
|
&state.storage,
|
||||||
env!("CARGO_PKG_VERSION"),
|
env!("CARGO_PKG_VERSION"),
|
||||||
editor_settings,
|
editor_settings,
|
||||||
@@ -144,6 +146,8 @@ pub async fn webdav_sync_upload(
|
|||||||
include_tunnel_secrets: include_secrets,
|
include_tunnel_secrets: include_secrets,
|
||||||
include_plugin_secrets: include_secrets,
|
include_plugin_secrets: include_secrets,
|
||||||
},
|
},
|
||||||
|
selection.as_ref(),
|
||||||
|
Some(&state.plugins),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
WebDavClient::new(config).put_snapshot(&snapshot).await
|
WebDavClient::new(config).put_snapshot(&snapshot).await
|
||||||
@@ -155,6 +159,7 @@ pub async fn webdav_sync_download(
|
|||||||
mut config: WebDavConfig,
|
mut config: WebDavConfig,
|
||||||
secrets_passphrase: Option<String>,
|
secrets_passphrase: Option<String>,
|
||||||
restore_secrets: bool,
|
restore_secrets: bool,
|
||||||
|
selection: Option<SyncSelection>,
|
||||||
) -> Result<WebDavDownloadResult, String> {
|
) -> Result<WebDavDownloadResult, String> {
|
||||||
resolve_webdav_password(&state.storage, &mut config).await?;
|
resolve_webdav_password(&state.storage, &mut config).await?;
|
||||||
let (snapshot, summary) = WebDavClient::new(config).get_snapshot().await?;
|
let (snapshot, summary) = WebDavClient::new(config).get_snapshot().await?;
|
||||||
@@ -164,23 +169,46 @@ pub async fn webdav_sync_download(
|
|||||||
} else {
|
} else {
|
||||||
resolve_webdav_sync_secrets_passphrase(&state.storage).await?
|
resolve_webdav_sync_secrets_passphrase(&state.storage).await?
|
||||||
};
|
};
|
||||||
let apply_summary = apply_sync_snapshot(
|
let apply_summary = apply_sync_snapshot_with_selection(
|
||||||
&state.storage,
|
&state.storage,
|
||||||
&snapshot,
|
&snapshot,
|
||||||
ApplySnapshotOptions {
|
ApplySnapshotOptions {
|
||||||
secrets_passphrase: explicit_passphrase.or(saved_passphrase.as_deref()),
|
secrets_passphrase: explicit_passphrase.or(saved_passphrase.as_deref()),
|
||||||
restore_secrets,
|
restore_secrets,
|
||||||
},
|
},
|
||||||
|
selection.as_ref(),
|
||||||
|
Some(&state.plugins),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(WebDavDownloadResult {
|
Ok(WebDavDownloadResult {
|
||||||
summary,
|
summary,
|
||||||
editor_settings: snapshot.editor_settings,
|
editor_settings: state.storage.load_editor_settings().await?,
|
||||||
desktop_settings: snapshot.desktop_settings,
|
desktop_settings: state.storage.load_desktop_settings().await?,
|
||||||
apply_summary,
|
apply_summary,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn cloud_sync_local_catalog(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
editor_settings: Option<serde_json::Value>,
|
||||||
|
) -> Result<SyncSnapshotCatalog, String> {
|
||||||
|
describe_local_sync_state(&state.storage, editor_settings, Some(&state.plugins)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn webdav_sync_inspect(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
mut config: WebDavConfig,
|
||||||
|
secrets_passphrase: Option<String>,
|
||||||
|
) -> Result<SyncSnapshotCatalog, String> {
|
||||||
|
resolve_webdav_password(&state.storage, &mut config).await?;
|
||||||
|
let (snapshot, _) = WebDavClient::new(config).get_snapshot().await?;
|
||||||
|
let explicit = secrets_passphrase.as_deref().map(str::trim).filter(|value| !value.is_empty());
|
||||||
|
let saved = if explicit.is_none() { resolve_webdav_sync_secrets_passphrase(&state.storage).await? } else { None };
|
||||||
|
describe_sync_snapshot(&snapshot, explicit.or(saved.as_deref()))
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn snippet_sync_test(state: State<'_, Arc<AppState>>, mut config: SnippetSyncConfig) -> Result<(), String> {
|
pub async fn snippet_sync_test(state: State<'_, Arc<AppState>>, mut config: SnippetSyncConfig) -> Result<(), String> {
|
||||||
resolve_snippet_token(&state.storage, &mut config).await?;
|
resolve_snippet_token(&state.storage, &mut config).await?;
|
||||||
@@ -250,6 +278,7 @@ pub async fn snippet_sync_upload(
|
|||||||
snippet_passphrase: Option<String>,
|
snippet_passphrase: Option<String>,
|
||||||
include_secrets: bool,
|
include_secrets: bool,
|
||||||
secrets_passphrase: Option<String>,
|
secrets_passphrase: Option<String>,
|
||||||
|
selection: Option<SyncSelection>,
|
||||||
) -> Result<SnippetSyncSummary, String> {
|
) -> Result<SnippetSyncSummary, String> {
|
||||||
resolve_snippet_token(&state.storage, &mut config).await?;
|
resolve_snippet_token(&state.storage, &mut config).await?;
|
||||||
let secrets_passphrase = if include_secrets {
|
let secrets_passphrase = if include_secrets {
|
||||||
@@ -263,7 +292,7 @@ pub async fn snippet_sync_upload(
|
|||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
let snapshot = build_sync_snapshot_with_options(
|
let snapshot = build_sync_snapshot_with_selection(
|
||||||
&state.storage,
|
&state.storage,
|
||||||
env!("CARGO_PKG_VERSION"),
|
env!("CARGO_PKG_VERSION"),
|
||||||
editor_settings,
|
editor_settings,
|
||||||
@@ -274,6 +303,8 @@ pub async fn snippet_sync_upload(
|
|||||||
include_tunnel_secrets: include_secrets,
|
include_tunnel_secrets: include_secrets,
|
||||||
include_plugin_secrets: include_secrets,
|
include_plugin_secrets: include_secrets,
|
||||||
},
|
},
|
||||||
|
selection.as_ref(),
|
||||||
|
Some(&state.plugins),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
let client = SnippetSyncClient::new(config)?;
|
let client = SnippetSyncClient::new(config)?;
|
||||||
@@ -289,23 +320,40 @@ pub async fn snippet_sync_download(
|
|||||||
snippet_passphrase: Option<String>,
|
snippet_passphrase: Option<String>,
|
||||||
restore_secrets: bool,
|
restore_secrets: bool,
|
||||||
secrets_passphrase: Option<String>,
|
secrets_passphrase: Option<String>,
|
||||||
|
selection: Option<SyncSelection>,
|
||||||
) -> Result<SnippetDownloadResult, String> {
|
) -> Result<SnippetDownloadResult, String> {
|
||||||
resolve_snippet_token(&state.storage, &mut config).await?;
|
resolve_snippet_token(&state.storage, &mut config).await?;
|
||||||
let (snapshot, summary) = SnippetSyncClient::new(config)?.get_snapshot(snippet_passphrase.as_deref()).await?;
|
let (snapshot, summary) = SnippetSyncClient::new(config)?.get_snapshot(snippet_passphrase.as_deref()).await?;
|
||||||
let apply_summary = apply_sync_snapshot(
|
let apply_summary = apply_sync_snapshot_with_selection(
|
||||||
&state.storage,
|
&state.storage,
|
||||||
&snapshot,
|
&snapshot,
|
||||||
ApplySnapshotOptions { secrets_passphrase: secrets_passphrase.as_deref(), restore_secrets },
|
ApplySnapshotOptions { secrets_passphrase: secrets_passphrase.as_deref(), restore_secrets },
|
||||||
|
selection.as_ref(),
|
||||||
|
Some(&state.plugins),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(SnippetDownloadResult {
|
Ok(SnippetDownloadResult {
|
||||||
summary,
|
summary,
|
||||||
editor_settings: snapshot.editor_settings,
|
editor_settings: state.storage.load_editor_settings().await?,
|
||||||
desktop_settings: snapshot.desktop_settings,
|
desktop_settings: state.storage.load_desktop_settings().await?,
|
||||||
apply_summary,
|
apply_summary,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn snippet_sync_inspect(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
mut config: SnippetSyncConfig,
|
||||||
|
snippet_passphrase: Option<String>,
|
||||||
|
secrets_passphrase: Option<String>,
|
||||||
|
) -> Result<SyncSnapshotCatalog, String> {
|
||||||
|
resolve_snippet_token(&state.storage, &mut config).await?;
|
||||||
|
let (snapshot, _) = SnippetSyncClient::new(config)?.get_snapshot(snippet_passphrase.as_deref()).await?;
|
||||||
|
let explicit = secrets_passphrase.as_deref().map(str::trim).filter(|value| !value.is_empty());
|
||||||
|
let saved = if explicit.is_none() { resolve_webdav_sync_secrets_passphrase(&state.storage).await? } else { None };
|
||||||
|
describe_sync_snapshot(&snapshot, explicit.or(saved.as_deref()))
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|||||||
@@ -1902,6 +1902,8 @@ pub fn run() {
|
|||||||
commands::cloud_sync::forget_webdav_sync_secrets_passphrase,
|
commands::cloud_sync::forget_webdav_sync_secrets_passphrase,
|
||||||
commands::cloud_sync::webdav_sync_upload,
|
commands::cloud_sync::webdav_sync_upload,
|
||||||
commands::cloud_sync::webdav_sync_download,
|
commands::cloud_sync::webdav_sync_download,
|
||||||
|
commands::cloud_sync::webdav_sync_inspect,
|
||||||
|
commands::cloud_sync::cloud_sync_local_catalog,
|
||||||
commands::cloud_sync::snippet_sync_test,
|
commands::cloud_sync::snippet_sync_test,
|
||||||
commands::cloud_sync::snippet_token_status,
|
commands::cloud_sync::snippet_token_status,
|
||||||
commands::cloud_sync::save_snippet_saved_token,
|
commands::cloud_sync::save_snippet_saved_token,
|
||||||
@@ -1911,6 +1913,7 @@ pub fn run() {
|
|||||||
commands::cloud_sync::retry_snippet_legacy_cleanup,
|
commands::cloud_sync::retry_snippet_legacy_cleanup,
|
||||||
commands::cloud_sync::snippet_sync_upload,
|
commands::cloud_sync::snippet_sync_upload,
|
||||||
commands::cloud_sync::snippet_sync_download,
|
commands::cloud_sync::snippet_sync_download,
|
||||||
|
commands::cloud_sync::snippet_sync_inspect,
|
||||||
commands::connection::test_connection,
|
commands::connection::test_connection,
|
||||||
commands::connection::test_connection_with_info,
|
commands::connection::test_connection_with_info,
|
||||||
commands::connection::test_ssh_tunnel,
|
commands::connection::test_ssh_tunnel,
|
||||||
|
|||||||
Reference in new issue
Block a user