An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Add unified data migration interface https://github.com/siyuan-note/siyuan/issues/18267
Daniele03e2bea9005
diff --git a/app/appearance/icons/index.html b/app/appearance/icons/index.htmlindex 015f41ee10..1263267492 100644--- a/app/appearance/icons/index.html+++ b/app/appearance/icons/index.html@@ -28,6 +28,12 @@<body><h2>SiYuan</h2><div class="fn__clear">+ <div>+ <svg>+ <use xlink:href="#iconDatabaseBackup"></use>+ </svg>+ iconDatabaseBackup+ </div><div><svg><use xlink:href="#iconObsidian"></use>diff --git a/app/appearance/icons/litheness/icon.js b/app/appearance/icons/litheness/icon.jsindex 745f93f128..bcf98177a1 100644--- a/app/appearance/icons/litheness/icon.js+++ b/app/appearance/icons/litheness/icon.js@@ -1,5 +1,8 @@document.body.insertAdjacentHTML('afterbegin', `<svg id="iconsLitheness" style="position: absolute; width: 0; height: 0; overflow: hidden;"><defs>+ <symbol id="iconDatabaseBackup" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">+ <ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 12a9 3 0 0 0 5 2.69"/><path d="M21 9.3V5"/><path d="M3 5v14a9 3 0 0 0 6.47 2.88"/><path d="M12 12v4h4"/><path d="M13 20a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L12 16"/>+ </symbol><symbol id="iconObsidian" viewBox="0 0 256 256" fill="#9974F8"><path d="M94.82 149.44c6.53-1.94 17.13-4.9 29.26-5.71a102.97 102.97 0 0 1-7.64-48.84c1.63-16.51 7.54-30.38 13.25-42.1l3.47-7.14 4.48-9.18c2.35-5 4.08-9.38 4.9-13.56.81-4.07.81-7.64-.2-11.11-1.03-3.47-3.07-7.14-7.15-11.21a17.02 17.02 0 0 0-15.8 3.77l-52.81 47.5a17.12 17.12 0 0 0-5.5 10.2l-4.5 30.18a149.26 149.26 0 0 1 38.24 57.2ZM54.45 106l-1.02 3.06-27.94 62.2a17.33 17.33 0 0 0 3.27 18.96l43.94 45.16a88.7 88.7 0 0 0 8.97-88.5A139.47 139.47 0 0 0 54.45 106Z"/><path d="m82.9 240.79 2.34.2c8.26.2 22.33 1.02 33.64 3.06 9.28 1.73 27.73 6.83 42.82 11.21 11.52 3.47 23.45-5.8 25.08-17.73 1.23-8.67 3.57-18.46 7.75-27.53a94.81 94.81 0 0 0-25.9-40.99 56.48 56.48 0 0 0-29.56-13.35 96.55 96.55 0 0 0-40.99 4.79 98.89 98.89 0 0 1-15.29 80.34h.1Z"/><path d="M201.87 197.76a574.87 574.87 0 0 0 19.78-31.6 8.67 8.67 0 0 0-.61-9.48 185.58 185.58 0 0 1-21.82-35.9c-5.91-14.16-6.73-36.08-6.83-46.69 0-4.07-1.22-8.05-3.77-11.21l-34.16-43.33c0 1.94-.4 3.87-.81 5.81a76.42 76.42 0 0 1-5.71 15.9l-4.7 9.8-3.36 6.72a111.95 111.95 0 0 0-12.03 38.23 93.9 93.9 0 0 0 8.67 47.92 67.9 67.9 0 0 1 39.56 16.52 99.4 99.4 0 0 1 25.8 37.31Z"/></symbol>diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex f1ffda27b0..ad69f19062 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,7 @@{+ "targetNotebook": "دفتر الملاحظات الهدف",+ "dataMigration": "ترحيل البيانات",+ "settingsAndSync": "الإعدادات والمزامنة","onboardingWelcome": "مرحبًا بك في SiYuan","onboardingDescription": "دفتر ملاحظاتك الأول جاهز! دوّن ما يدور في ذهنك الآن.","importExistingData": "استيراد البيانات الموجودة",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 53fafaa6b9..b28292b2d1 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Zielnotizbuch",+ "dataMigration": "Datenmigration",+ "settingsAndSync": "Einstellungen und Synchronisierung","onboardingWelcome": "Willkommen bei SiYuan","onboardingDescription": "Ihr erstes Notizbuch ist bereit. Halten Sie fest, was Ihnen gerade durch den Kopf geht!","importExistingData": "Vorhandene Daten importieren",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex ec171df3d8..74f83f4781 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Target notebook",+ "dataMigration": "Data migration",+ "settingsAndSync": "Settings and sync","onboardingWelcome": "Welcome to SiYuan","onboardingDescription": "Your first notebook is ready. Write down what's on your mind!","importExistingData": "Import existing data",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex ea69db2df2..ead3a62dd3 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Cuaderno de destino",+ "dataMigration": "Migración de datos",+ "settingsAndSync": "Ajustes y sincronización","onboardingWelcome": "Te damos la bienvenida a SiYuan","onboardingDescription": "Tu primer cuaderno ya está listo. ¡Anota lo que tienes en mente!","importExistingData": "Importar datos existentes",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex f8167a9cc6..1fe7065694 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Carnet cible",+ "dataMigration": "Migration des données",+ "settingsAndSync": "Paramètres et synchronisation","onboardingWelcome": "Bienvenue dans SiYuan","onboardingDescription": "Votre premier carnet est prêt. Notez ce qui vous passe par la tête !","importExistingData": "Importer des données existantes",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex bc24815b27..0131074643 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,7 @@{+ "targetNotebook": "מחברת יעד",+ "dataMigration": "העברת נתונים",+ "settingsAndSync": "הגדרות וסנכרון","onboardingWelcome": "ברוכים הבאים ל-SiYuan","onboardingDescription": "המחברת הראשונה שלך מוכנה. זה הזמן לכתוב את מה שעובר לך בראש!","importExistingData": "ייבוא נתונים קיימים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 087db6fdeb..815df3580d 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,7 @@{+ "targetNotebook": "लक्ष्य नोटबुक",+ "dataMigration": "डेटा माइग्रेशन",+ "settingsAndSync": "सेटिंग्स और सिंक","onboardingWelcome": "SiYuan में आपका स्वागत है","onboardingDescription": "आपकी पहली नोटबुक तैयार है। अभी मन में चल रहे विचार लिखें!","importExistingData": "मौजूदा डेटा आयात करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 5c16f3544f..2d1a03b829 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Buku catatan tujuan",+ "dataMigration": "Migrasi data",+ "settingsAndSync": "Pengaturan dan sinkronisasi","onboardingWelcome": "Selamat datang di SiYuan","onboardingDescription": "Buku catatan pertama Anda sudah siap. Tuliskan apa yang sedang Anda pikirkan!","importExistingData": "Impor data yang ada",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex b62c372ad7..9d90ca674b 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Taccuino di destinazione",+ "dataMigration": "Migrazione dei dati",+ "settingsAndSync": "Impostazioni e sincronizzazione","onboardingWelcome": "Benvenuto in SiYuan","onboardingDescription": "Il tuo primo taccuino è pronto. Scrivi ciò che hai in mente!","importExistingData": "Importa dati esistenti",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex c390aea9cc..49a470558b 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,7 @@{+ "targetNotebook": "対象ノートブック",+ "dataMigration": "データ移行",+ "settingsAndSync": "設定と同期","onboardingWelcome": "SiYuanへようこそ","onboardingDescription": "最初のノートブックができました。今のアイデアを書き留めてみましょう!","importExistingData": "既存データをインポート",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 701472fa5f..b70f3f4f65 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,7 @@{+ "targetNotebook": "대상 노트북",+ "dataMigration": "데이터 마이그레이션",+ "settingsAndSync": "설정 및 동기화","onboardingWelcome": "SiYuan에 오신 것을 환영합니다","onboardingDescription": "첫 번째 노트북이 준비됐어요. 지금 떠오르는 생각을 적어 보세요!","importExistingData": "기존 데이터 가져오기",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 2ea305cb14..87fca51b8b 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Doelnotitieboek",+ "dataMigration": "Gegevensmigratie",+ "settingsAndSync": "Instellingen en synchronisatie","onboardingWelcome": "Welkom bij SiYuan","onboardingDescription": "Je eerste notitieboek is klaar. Schrijf op wat er nu in je opkomt!","importExistingData": "Bestaande gegevens importeren",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 312fdf9e8a..f66bcfca82 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Notatnik docelowy",+ "dataMigration": "Migracja danych",+ "settingsAndSync": "Ustawienia i synchronizacja","onboardingWelcome": "Witamy w SiYuan","onboardingDescription": "Twój pierwszy notatnik jest już gotowy. Zapisz to, co chodzi Ci teraz po głowie!","importExistingData": "Importuj istniejące dane",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex fb707b213a..5ff81cd96d 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Caderno de destino",+ "dataMigration": "Migração de dados",+ "settingsAndSync": "Configurações e sincronização","onboardingWelcome": "Boas-vindas ao SiYuan","onboardingDescription": "Seu primeiro caderno está pronto. Anote o que está passando pela sua cabeça!","importExistingData": "Importar dados existentes",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex bdcefa4d6e..25970452e8 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Целевой блокнот",+ "dataMigration": "Миграция данных",+ "settingsAndSync": "Настройки и синхронизация","onboardingWelcome": "Добро пожаловать в SiYuan","onboardingDescription": "Ваш первый блокнот готов. Запишите то, что сейчас у вас на уме!","importExistingData": "Импортировать существующие данные",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex afb5651cef..cb8f68ebce 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Cieľový zápisník",+ "dataMigration": "Migrácia údajov",+ "settingsAndSync": "Nastavenia a synchronizácia","onboardingWelcome": "Vitajte v SiYuan","onboardingDescription": "Váš prvý zápisník je pripravený. Zapíšte si, čo vám práve napadlo!","importExistingData": "Importovať existujúce údaje",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 7575a34e5f..6aa79622c2 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,7 @@{+ "targetNotebook": "สมุดบันทึกเป้าหมาย",+ "dataMigration": "การย้ายข้อมูล",+ "settingsAndSync": "การตั้งค่าและการซิงค์","onboardingWelcome": "ยินดีต้อนรับสู่ SiYuan","onboardingDescription": "สมุดบันทึกแรกของคุณพร้อมแล้ว มาเขียนสิ่งที่กำลังคิดอยู่กันเถอะ!","importExistingData": "นำเข้าข้อมูลที่มีอยู่",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 828793b3a5..9494bc3e7a 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Hedef not defteri",+ "dataMigration": "Veri taşıma",+ "settingsAndSync": "Ayarlar ve eşitleme","onboardingWelcome": "SiYuan'a hoş geldiniz","onboardingDescription": "İlk not defteriniz hazır. Şu anda aklınızdakileri yazın!","importExistingData": "Mevcut verileri içe aktar",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex b1513162d8..56ca4ec89e 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,7 @@{+ "targetNotebook": "Цільовий нотатник",+ "dataMigration": "Перенесення даних",+ "settingsAndSync": "Налаштування та синхронізація","onboardingWelcome": "Ласкаво просимо до SiYuan","onboardingDescription": "Ваш перший нотатник готовий. Запишіть те, що зараз у вас на думці!","importExistingData": "Імпортувати наявні дані",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 36bcb33a8b..6b4cb4628b 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,7 @@{+ "targetNotebook": "目标笔记本",+ "dataMigration": "数据迁移",+ "settingsAndSync": "设置与同步","onboardingWelcome": "欢迎使用思源","onboardingDescription": "你的第一个笔记本已经准备好啦,写下此刻的想法吧!","importExistingData": "导入已有数据",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 95690ef038..a8dbd552c5 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,7 @@{+ "targetNotebook": "目標筆記本",+ "dataMigration": "資料遷移",+ "settingsAndSync": "設定與同步","onboardingWelcome": "歡迎使用思源","onboardingDescription": "你的第一個筆記本已經準備好啦,寫下此刻的想法吧!","importExistingData": "匯入已有資料",diff --git a/app/src/assets/scss/business/_config.scss b/app/src/assets/scss/business/_config.scssindex afb358d39f..964f822564 100644--- a/app/src/assets/scss/business/_config.scss+++ b/app/src/assets/scss/business/_config.scss@@ -483,3 +483,57 @@margin-right: auto;padding: 16px 0;}++.data-migration {+ overflow-x: hidden;+}++.data-migration__item {+ min-width: 0;+}++.data-migration__disabled {+ cursor: not-allowed;+ opacity: .38;+}++.data-migration__actions {+ display: flex;+ flex-wrap: wrap;+ justify-content: flex-end;+ max-width: 100%;+ align-items: center;+ opacity: 0;+ pointer-events: none;+ transition: opacity .15s linear;+}++.data-migration__toggle {+ box-sizing: border-box;+ padding-left: 0;+ position: relative;++ & > .b3-list-item__text {+ color: var(--b3-theme-on-surface);+ }++ & > .b3-list-item__toggle {+ position: absolute;+ left: -20px;+ top: 50%;+ transform: translateY(-50%);+ }+}++.data-migration__item:hover .data-migration__actions,+.data-migration__item:has(:focus-visible) .data-migration__actions {+ opacity: 1;+ pointer-events: auto;+}++@media (hover: none) {+ .data-migration__actions {+ opacity: 1;+ pointer-events: auto;+ }+}diff --git a/app/src/menus/importData.ts b/app/src/menus/importData.tsindex 08c941ba15..a487970218 100644--- a/app/src/menus/importData.ts+++ b/app/src/menus/importData.ts@@ -5,16 +5,87 @@ import {fetchPost} from "../util/fetch";import {confirmDialog} from "../dialog/confirmDialog";import {showMessage} from "../dialog/message";import {importObsidianVault} from "./importObsidian";+import {saveExportFile, writeText} from "../protyle/util/compatibility";+import {exitSiYuan} from "../dialog/processSystem";+/// #if !MOBILE+import {exportLayout} from "../layout/util";+/// #endif/// #if !BROWSERimport {ipcRenderer} from "electron";+import * as path from "path";+import {afterExport} from "../protyle/export/util";/// #endif-interface IImportDataOptions {+interface IDataMigrationOptions {+ mode?: "manage" | "onboarding";notebookID?: string;- onComplete?: () => void;+ onContentComplete?: () => void;}-export const openImportData = (options: IImportDataOptions = {}) => {+const getExportButton = (action: string, mode: IDataMigrationOptions["mode"]) => mode === "manage" ?+ `<span class="fn__space"></span><button class="b3-button b3-button--outline" data-action="${action}"><svg><use xlink:href="#iconUpload"></use></svg>${window.siyuan.languages.export}</button>` : "";++const getImportButton = (type: string, accept: string) => `<button class="b3-button b3-button--outline" style="position:relative">+ <input class="b3-form__upload" data-type="${type}" type="file" accept="${accept}">+ <svg><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.import}+</button>`;++const openRepoKeyImport = (onComplete?: () => void) => {+ const dialog = new Dialog({+ title: `🔑 ${window.siyuan.languages.key}`,+ content: `<div class="b3-dialog__content" style="display:flex">+ <textarea spellcheck="false" style="resize:none;flex:1" class="b3-text-field fn__block" placeholder="${window.siyuan.languages.keyPlaceholder}"></textarea>+</div>+<div class="b3-dialog__action">+ <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>+ <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>+</div>`,+ width: "520px",+ height: "260px",+ });+ dialog.element.setAttribute("data-key", Constants.DIALOG_PASSWORD);+ const textAreaElement = dialog.element.querySelector("textarea") as HTMLTextAreaElement;+ const buttons = dialog.element.querySelectorAll(".b3-button");+ textAreaElement.focus();+ buttons[0].addEventListener("click", () => dialog.destroy());+ buttons[1].addEventListener("click", () => {+ fetchPost("/api/repo/importRepoKey", {key: textAreaElement.value}, (response) => {+ window.siyuan.config.repo.key = response.data.key;+ dialog.destroy();+ showMessage(window.siyuan.languages.imported);+ onComplete?.();+ });+ });+};++const exportData = async () => {+ /// #if BROWSER+ fetchPost("/api/export/exportData", {}, (response) => {+ if (response.code !== 0) {+ showMessage(response.msg, response.data?.closeTimeout || 0, "error");+ return;+ }+ void saveExportFile(response.data.zip);+ });+ /// #else+ const result = await ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "showOpenDialog",+ title: `${window.siyuan.languages.export} Data`,+ properties: ["createDirectory", "openDirectory"],+ });+ if (result.canceled || result.filePaths.length === 0) {+ return;+ }+ const msgId = showMessage(window.siyuan.languages.exporting, -1);+ fetchPost("/api/export/exportDataInFolder", {folder: result.filePaths[0]}, (response) => {+ afterExport(path.join(result.filePaths[0], response.data.name), msgId);+ });+ /// #endif+};++export const openDataMigration = (options: IDataMigrationOptions = {}) => {+ const mode = options.mode || "manage";+ const hasRepoKey = Boolean(window.siyuan.config.repo.key);const helpNotebookIDs = Object.values(Constants.HELP_PATH);const notebooks = window.siyuan.notebooks.filter((item) => !item.closed && !helpNotebookIDs.includes(item.id));const selectedNotebookID = notebooks.some((item) => item.id === options.notebookID) ? options.notebookID : notebooks[0]?.id;@@ -22,28 +93,22 @@ export const openImportData = (options: IImportDataOptions = {}) => {`<option value="${item.id}"${item.id === selectedNotebookID ? " selected" : ""}>${escapeHtml(item.name)}</option>`).join("");let nativeImportHTML = "";/// #if !BROWSER- nativeImportHTML = `<button class="b3-list-item" data-type="markdown-file">+ nativeImportHTML = `<button class="b3-list-item fn__block" data-type="markdown-file"${notebooks.length === 0 ? " disabled" : ""}><svg class="b3-list-item__graphic"><use xlink:href="#iconMarkdown"></use></svg><span class="b3-list-item__text">Markdown ${window.siyuan.languages.doc}</span></button>-<button class="b3-list-item" data-type="markdown-folder">+<button class="b3-list-item fn__block" data-type="markdown-folder"${notebooks.length === 0 ? " disabled" : ""}><svg class="b3-list-item__graphic"><use xlink:href="#iconFolder"></use></svg><span class="b3-list-item__text">Markdown ${window.siyuan.languages.folder}</span></button>-<button class="b3-list-item" data-type="obsidian">+<button class="b3-list-item fn__block" data-type="obsidian"><svg class="b3-list-item__graphic"><use xlink:href="#iconObsidian"></use></svg>- <span class="b3-list-item__text">${window.siyuan.languages.obsidianVaultImport}</span>+ <span class="b3-list-item__text">Obsidian Vault</span></button>`;/// #endifconst dialog = new Dialog({- title: window.siyuan.languages.import,- content: `<div class="b3-dialog__content">- <label class="fn__flex b3-label">- <span class="b3-label__text">${window.siyuan.languages.currentNotebook}</span>- <span class="fn__space"></span>- <select class="b3-select fn__flex-1" data-type="notebook"${notebooks.length === 0 ? " disabled" : ""}>${notebookOptions || `<option>${window.siyuan.languages.newFileTip}</option>`}</select>- </label>- <div class="fn__hr"></div>+ title: window.siyuan.languages.dataMigration,+ content: `<div class="b3-dialog__content data-migration"><div class="b3-label__text">SiYuan</div><div class="b3-list b3-list--background"><label class="b3-list-item">@@ -51,84 +116,221 @@ export const openImportData = (options: IImportDataOptions = {}) => {<span class="b3-list-item__text">SiYuan .sy.zip</span><input class="b3-form__upload" data-type="siyuan" type="file" accept="application/zip"></label>- <label class="b3-list-item b3-list-item--warning">+ <div class="b3-list-item b3-list-item--warning fn__flex-wrap data-migration__item"><svg class="b3-list-item__graphic"><use xlink:href="#iconDatabase"></use></svg><span class="b3-list-item__text">Data.zip</span>- <input class="b3-form__upload" data-type="data" type="file" accept="application/zip">- </label>+ <span class="data-migration__actions">+ ${getImportButton("data", "application/zip")}+ ${getExportButton("export-data", mode)}+ </span>+ </div></div><div class="fn__hr"></div><div class="b3-label__text">${window.siyuan.languages.importFromMoreApps}</div><div class="b3-list b3-list--background">- <label class="b3-list-item">+ <label class="b3-list-item${notebooks.length === 0 ? " data-migration__disabled" : ""}"><svg class="b3-list-item__graphic"><use xlink:href="#iconMarkdown"></use></svg><span class="b3-list-item__text">Markdown .zip</span>- <input class="b3-form__upload" data-type="markdown-zip" type="file" accept="application/zip">+ <input class="b3-form__upload" data-type="markdown-zip" type="file" accept="application/zip"${notebooks.length === 0 ? " disabled" : ""}></label>${nativeImportHTML}</div>+ <div class="fn__hr"></div>+ <button class="b3-list-item fn__block data-migration__toggle" data-type="advanced-toggle" aria-expanded="false">+ <span class="b3-list-item__toggle"><svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg></span>+ <span class="b3-list-item__text">${window.siyuan.languages.settingsAndSync}</span>+ </button>+ <div class="fn__none" data-type="advanced">+ <div class="b3-list b3-list--background">+ <div class="b3-list-item fn__flex-wrap data-migration__item">+ <svg class="b3-list-item__graphic"><use xlink:href="#iconSettings"></use></svg>+ <span class="b3-list-item__text">${window.siyuan.languages.config}</span>+ <span class="data-migration__actions">+ ${getImportButton("conf", "application/zip,application/json")}+ ${getExportButton("export-conf", mode)}+ </span>+ </div>+ <div class="b3-list-item fn__flex-wrap data-migration__item">+ <svg class="b3-list-item__graphic"><use xlink:href="#iconCloud"></use></svg>+ <span class="b3-list-item__text">S3</span>+ <span class="data-migration__actions">+ ${getImportButton("s3", "application/zip")}+ ${getExportButton("export-s3", mode)}+ </span>+ </div>+ <div class="b3-list-item fn__flex-wrap data-migration__item">+ <svg class="b3-list-item__graphic"><use xlink:href="#iconCloud"></use></svg>+ <span class="b3-list-item__text">WebDAV</span>+ <span class="data-migration__actions">+ ${getImportButton("webdav", "application/zip")}+ ${getExportButton("export-webdav", mode)}+ </span>+ </div>+ ${mode === "onboarding" && hasRepoKey ? "" : `<div class="b3-list-item fn__flex-wrap data-migration__item" data-type="repo-key">+ <svg class="b3-list-item__graphic"><use xlink:href="#iconKey"></use></svg>+ <span class="b3-list-item__text">${window.siyuan.languages.dataRepoKey}</span>+ <span class="data-migration__actions">+ ${hasRepoKey ? `<button class="b3-button b3-button--outline" data-action="copy-key"><svg><use xlink:href="#iconCopy"></use></svg>${window.siyuan.languages.copy}</button>` : `<button class="b3-button b3-button--outline" data-action="import-key"><svg><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.import}</button>`}+ </span>+ </div>`}+ </div>+ </div></div>`,- width: "520px",+ width: "560px",});- const complete = () => {+ const completeContent = () => {dialog.destroy();- options.onComplete?.();+ options.onContentComplete?.();};- const getNotebookID = () => notebooks.length > 0 ?- (dialog.element.querySelector('[data-type="notebook"]') as HTMLSelectElement).value : "";- const getRequiredNotebookID = () => {- const notebookID = getNotebookID();- if (!notebookID) {+ let targetNotebookID = selectedNotebookID || "";+ const selectTargetNotebook = (callback: (notebookID: string) => void, onCancel?: () => void) => {+ if (notebooks.length === 0) {+ onCancel?.();showMessage(window.siyuan.languages.newFileTip);+ return;}- return notebookID;+ const targetDialog = new Dialog({+ title: window.siyuan.languages.targetNotebook,+ content: `<div class="b3-dialog__content">+ <select class="b3-select fn__block">${notebookOptions}</select>+</div>+<div class="b3-dialog__action">+ <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>+ <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>+</div>`,+ width: "420px",+ destroyCallback: () => {+ if (!targetDialog.data?.confirmed) {+ onCancel?.();+ }+ },+ });+ const selectElement = targetDialog.element.querySelector("select") as HTMLSelectElement;+ selectElement.value = targetNotebookID;+ const buttons = targetDialog.element.querySelectorAll(".b3-button");+ buttons[0].addEventListener("click", () => targetDialog.destroy());+ buttons[1].addEventListener("click", () => {+ targetNotebookID = selectElement.value;+ targetDialog.data = {confirmed: true};+ targetDialog.destroy();+ callback(targetNotebookID);+ });};- const postFile = (url: string, file: File, extra: Record<string, string> = {}) => {+ const postFile = (url: string, file: File, extra: Record<string, string> = {},+ callback: (response: IWebSocketData) => void = completeContent) => {const formData = new FormData();formData.append("file", file);Object.entries(extra).forEach(([key, value]) => formData.append(key, value));- fetchPost(url, formData, complete);+ fetchPost(url, formData, callback);+ };+ const bindFileInput = (type: string, callback: (file: File, input: HTMLInputElement) => void) => {+ dialog.element.querySelector(`[data-type="${type}"]`)?.addEventListener("change", (event: Event) => {+ const input = event.target as HTMLInputElement;+ const file = input.files?.[0];+ if (file) {+ callback(file, input);+ }+ });};- dialog.element.querySelector('[data-type="siyuan"]').addEventListener("change", (event: InputEvent & {- target: HTMLInputElement- }) => {- const file = event.target.files?.[0];- if (file) {- event.target.value = "";- postFile("/api/import/importSYAuto", file, {notebook: getNotebookID(), toPath: "/"});- }- });- dialog.element.querySelector('[data-type="markdown-zip"]').addEventListener("change", (event: InputEvent & {- target: HTMLInputElement- }) => {- const file = event.target.files?.[0];- if (file) {- const notebookID = getRequiredNotebookID();- event.target.value = "";- if (notebookID) {- postFile("/api/import/importZipMd", file, {notebook: notebookID, toPath: "/"});+ bindFileInput("siyuan", (file, input) => {+ input.value = "";+ postFile("/api/import/importSYAuto", file, {notebook: "", toPath: "/"}, (response) => {+ const token = response.data?.token as string | undefined;+ if (response.data?.type !== "document" || !token) {+ completeContent();+ return;}- }+ selectTargetNotebook((notebookID) => {+ fetchPost("/api/import/continueImportSY", {token, notebook: notebookID}, completeContent);+ }, () => {+ fetchPost("/api/import/cancelImportSY", {token});+ });+ });});- dialog.element.querySelector('[data-type="data"]').addEventListener("change", (event: InputEvent & {- target: HTMLInputElement- }) => {- const file = event.target.files?.[0];- if (!file) {- return;- }+ bindFileInput("markdown-zip", (file, input) => {+ input.value = "";+ selectTargetNotebook((notebookID) => {+ postFile("/api/import/importZipMd", file, {notebook: notebookID, toPath: "/"});+ });+ });+ bindFileInput("data", (file, input) => {confirmDialog(`${window.siyuan.languages.import} Data`, window.siyuan.languages.importDataTip, () => {postFile("/api/import/importData", file);});- event.target.value = "";+ input.value = "";+ });+ bindFileInput("conf", (file, input) => {+ input.value = "";+ postFile("/api/system/importConf", file, {}, (response) => {+ if (response.code !== 0) {+ showMessage(response.msg);+ return;+ }+ showMessage(window.siyuan.languages.imported);+ /// #if MOBILE+ void exitSiYuan();+ /// #else+ void exportLayout({errorExit: true, cb: exitSiYuan});+ /// #endif+ });+ });+ ["s3", "webdav"].forEach((provider) => {+ bindFileInput(provider, (file, input) => {+ input.value = "";+ const isS3 = provider === "s3";+ postFile(isS3 ? "/api/sync/importSyncProviderS3" : "/api/sync/importSyncProviderWebDAV", file, {}, (response) => {+ if (isS3) {+ window.siyuan.config.sync.s3 = response.data.s3;+ } else {+ window.siyuan.config.sync.webdav = response.data.webdav;+ }+ showMessage(window.siyuan.languages.imported);+ });+ });+ });++ dialog.element.querySelector('[data-type="advanced-toggle"]').addEventListener("click", (event) => {+ const toggleElement = event.currentTarget as HTMLElement;+ const expanded = toggleElement.getAttribute("aria-expanded") === "true";+ toggleElement.setAttribute("aria-expanded", String(!expanded));+ toggleElement.querySelector(".b3-list-item__arrow")?.classList.toggle("b3-list-item__arrow--open", !expanded);+ dialog.element.querySelector('[data-type="advanced"]')?.classList.toggle("fn__none", expanded);+ });+ dialog.element.addEventListener("click", (event) => {+ const action = (event.target as HTMLElement).closest<HTMLElement>("[data-action]")?.dataset.action;+ const exports: Record<string, string> = {+ "export-conf": "/api/system/exportConf",+ "export-s3": "/api/sync/exportSyncProviderS3",+ "export-webdav": "/api/sync/exportSyncProviderWebDAV",+ };+ if (action === "export-data") {+ void exportData();+ } else if (action && exports[action]) {+ fetchPost(exports[action], {}, (response) => void saveExportFile(response.data.zip));+ } else if (action === "import-key") {+ openRepoKeyImport(() => {+ const repoKeyElement = dialog.element.querySelector('[data-type="repo-key"]');+ if (mode === "onboarding") {+ repoKeyElement?.remove();+ return;+ }+ const actionsElement = repoKeyElement?.querySelector(".data-migration__actions");+ if (actionsElement) {+ actionsElement.innerHTML = `<button class="b3-button b3-button--outline" data-action="copy-key"><svg><use xlink:href="#iconCopy"></use></svg>${window.siyuan.languages.copy}</button>`;+ }+ });+ } else if (action === "copy-key") {+ writeText(window.siyuan.config.repo.key);+ showMessage(window.siyuan.languages.copied);+ }});/// #if !BROWSERconst importMarkdown = async (isFile: boolean) => {- const notebookID = getRequiredNotebookID();- if (!notebookID) {+ if (notebooks.length === 0) {+ showMessage(window.siyuan.languages.newFileTip);return;}const localPath = await ipcRenderer.invoke(Constants.SIYUAN_GET, {@@ -140,18 +342,16 @@ export const openImportData = (options: IImportDataOptions = {}) => {if (localPath.filePaths.length === 0) {return;}- fetchPost("/api/import/importStdMd", {- notebook: notebookID,- localPath: localPath.filePaths[0],- toPath: "/",- }, complete);+ selectTargetNotebook((notebookID) => {+ fetchPost("/api/import/importStdMd", {+ notebook: notebookID,+ localPath: localPath.filePaths[0],+ toPath: "/",+ }, completeContent);+ });};- dialog.element.querySelector('[data-type="markdown-file"]')?.addEventListener("click", () => {- void importMarkdown(true);- });- dialog.element.querySelector('[data-type="markdown-folder"]')?.addEventListener("click", () => {- void importMarkdown(false);- });+ dialog.element.querySelector('[data-type="markdown-file"]')?.addEventListener("click", () => void importMarkdown(true));+ dialog.element.querySelector('[data-type="markdown-folder"]')?.addEventListener("click", () => void importMarkdown(false));dialog.element.querySelector('[data-type="obsidian"]')?.addEventListener("click", async () => {const localPath = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "showOpenDialog",@@ -162,8 +362,8 @@ export const openImportData = (options: IImportDataOptions = {}) => {if (localPath.filePaths.length === 0) {return;}- complete();- await importObsidianVault(localPath.filePaths[0]);+ dialog.destroy();+ await importObsidianVault(localPath.filePaths[0], options.onContentComplete);});/// #endif};diff --git a/app/src/menus/importObsidian.ts b/app/src/menus/importObsidian.tsindex caaba6952e..ece8cdfe13 100644--- a/app/src/menus/importObsidian.ts+++ b/app/src/menus/importObsidian.ts@@ -172,7 +172,7 @@ const showFailure = (task: IObsidianTask) => {});};-const showConfirmation = (taskID: string, analysis: IObsidianAnalysis) => {+const showConfirmation = (taskID: string, analysis: IObsidianAnalysis, onComplete?: () => void) => {const skippedCount = analysis.skippedHiddenCount + analysis.skippedLinkCount + analysis.skippedSpecialCount + analysis.skippedNestedVaultCount;const warnings = analysis.warnings || [];const basicStats = formatBasicStats(analysis);@@ -225,13 +225,14 @@ const showConfirmation = (taskID: string, analysis: IObsidianAnalysis) => {const task = await showProgress(taskID, true);if (task?.state === "completed" && task.result) {showMessage(window.siyuan.languages.imported);+ onComplete?.();} else if (task?.state === "failed") {showFailure(task);}});};-export const importObsidianVault = async (localPath: string) => {+export const importObsidianVault = async (localPath: string, onComplete?: () => void) => {const response = await fetchSyncPost("/api/import/startObsidianVaultAnalysis", {localPath});if (response.code !== 0) {return;@@ -239,7 +240,7 @@ export const importObsidianVault = async (localPath: string) => {const startedTask = response.data as IObsidianTask;const task = await showProgress(startedTask.taskID, false);if (task?.state === "ready" && task.analysis) {- showConfirmation(task.taskID, task.analysis);+ showConfirmation(task.taskID, task.analysis, onComplete);} else if (task?.state === "failed") {showFailure(task);}diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.tsindex 57060aab5e..64d8480188 100644--- a/app/src/menus/workspace.ts+++ b/app/src/menus/workspace.ts@@ -27,7 +27,7 @@ import {isBrowser} from "../util/functions";import {openRecentDocs} from "../business/openRecentDocs";import * as dayjs from "dayjs";import {upDownHint} from "../util/upDownHint";-import {openImportData} from "./importData";+import {openDataMigration} from "./importData";const editLayout = (layoutName?: string) => {const dialog = new Dialog({@@ -538,10 +538,10 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {if (!window.siyuan.config.readonly) {window.siyuan.menus.menu.append(new MenuItem({id: "importData",- label: window.siyuan.languages.import,- icon: "iconDownload",+ label: window.siyuan.languages.dataMigration,+ icon: "iconDatabaseBackup",click: () => {- openImportData();+ openDataMigration();}}).element);}diff --git a/app/src/mobile/menu/index.ts b/app/src/mobile/menu/index.tsindex 7dc14af646..675e779e4b 100644--- a/app/src/mobile/menu/index.ts+++ b/app/src/mobile/menu/index.ts@@ -18,7 +18,7 @@ import {bindSettingSaveDelegation} from "../../config/setting/save";import {isMobile} from "../../util/functions";import {openModel} from "./model";import {getCurrentEditor} from "../editor";-import {openImportData} from "../../menus/importData";+import {openDataMigration} from "../../menus/importData";const getSettingTabFromMenuTarget = (target: HTMLElement): ISettingTabShell<TSettingTab> | undefined => {const item = target.closest(".b3-menu__item") as HTMLElement | null;@@ -71,7 +71,7 @@ export const initRightMenu = (app: App) => {<svg class="b3-menu__icon"><use xlink:href="#iconLock"></use></svg><span class="b3-menu__label">${window.siyuan.languages.newEncryptedNotebook}</span></div><div class="b3-menu__item${window.siyuan.config.readonly ? " fn__none" : ""}" id="menuImport">- <svg class="b3-menu__icon"><use xlink:href="#iconDownload"></use></svg><span class="b3-menu__label">${window.siyuan.languages.import}</span>+ <svg class="b3-menu__icon"><use xlink:href="#iconDatabaseBackup"></use></svg><span class="b3-menu__label">${window.siyuan.languages.dataMigration}</span></div><div class="b3-menu__separator"></div><div id="menuNewDaily" class="b3-menu__item${window.siyuan.config.readonly ? " fn__none" : ""}">@@ -159,7 +159,7 @@ export const initRightMenu = (app: App) => {break;} else if (target.id === "menuImport") {closePanel();- openImportData();+ openDataMigration();event.preventDefault();event.stopPropagation();break;diff --git a/app/src/onboarding/index.ts b/app/src/onboarding/index.tsindex d5ebafffd8..b6e3e7eb14 100644--- a/app/src/onboarding/index.ts+++ b/app/src/onboarding/index.ts@@ -1,6 +1,6 @@import {Constants} from "../constants";import {fetchPost, fetchSyncPost} from "../util/fetch";-import {openImportData} from "../menus/importData";+import {openDataMigration} from "../menus/importData";import {mountHelp} from "../util/mount";import {syncGuide} from "../sync/syncGuide";import {openSetting} from "../config";@@ -123,9 +123,10 @@ const renderOnboarding = (app: App) => {dismissOnboarding();break;case "import":- openImportData({+ openDataMigration({+ mode: "onboarding",notebookID: window.siyuan.config.onboarding.notebookID,- onComplete: dismissOnboarding,+ onContentComplete: dismissOnboarding,});break;case "sync":diff --git a/kernel/api/import.go b/kernel/api/import.goindex 8597587c74..6eeed57e18 100644--- a/kernel/api/import.go+++ b/kernel/api/import.go@@ -25,6 +25,8 @@ import ("os""path/filepath""strings"+ "sync"+ "time""github.com/88250/gulu""github.com/gin-gonic/gin"@@ -33,6 +35,10 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+const stagedSYImportTTL = 30 * time.Minute++var stagedSYImportLock sync.Mutex+func importSY(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(200, ret)@@ -133,6 +139,16 @@ func importSYAuto(c *gin.Context) {toPath = values[0]}createdBoxID, createdNotebook, err := model.ImportSYAuto(writePath, notebook, toPath)+ if errors.Is(err, model.ErrSYTargetNotebookRequired) {+ token, stageErr := stageSYImport(writePath)+ if stageErr != nil {+ ret.Code = -1+ ret.Msg = stageErr.Error()+ return+ }+ ret.Data = map[string]any{"type": "document", "token": token}+ return+ }if err != nil {ret.Code = -1ret.Msg = err.Error()@@ -161,6 +177,139 @@ func importSYAuto(c *gin.Context) {util.PushEvent(event)}+func continueImportSY(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ var token, notebook string+ if !util.ParseJsonArgs(arg, ret,+ util.BindJsonArg("token", &token, true, true),+ util.BindJsonArg("notebook", ¬ebook, true, true)) {+ return+ }+ zipPath, err := claimStagedSYImport(token)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ defer os.Remove(zipPath)+ if err = model.ImportSY(zipPath, notebook, "/"); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = map[string]any{"type": "document"}+}++func cancelImportSY(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ var token string+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("token", &token, true, true)) {+ return+ }+ if !isValidSYImportToken(token) {+ ret.Code = -1+ ret.Msg = "invalid import token"+ return+ }+ stagedSYImportLock.Lock()+ defer stagedSYImportLock.Unlock()+ cleanupStagedSYImports()+ if err := os.Remove(stagedSYImportPath(token)); err != nil && !os.IsNotExist(err) {+ ret.Code = -1+ ret.Msg = err.Error()+ }+}++func stageSYImport(srcPath string) (token string, err error) {+ stagedSYImportLock.Lock()+ defer stagedSYImportLock.Unlock()+ cleanupStagedSYImports()+ if err = os.MkdirAll(stagedSYImportDir(), 0755); err != nil {+ return+ }+ for {+ token = gulu.Rand.String(32)+ _, statErr := os.Stat(stagedSYImportPath(token))+ if os.IsNotExist(statErr) {+ break+ }+ if statErr != nil {+ return "", statErr+ }+ }+ err = os.Rename(srcPath, stagedSYImportPath(token))+ return+}++func claimStagedSYImport(token string) (path string, err error) {+ if !isValidSYImportToken(token) {+ return "", errors.New("invalid import token")+ }+ stagedSYImportLock.Lock()+ defer stagedSYImportLock.Unlock()+ cleanupStagedSYImports()+ srcPath := stagedSYImportPath(token)+ if _, err = os.Stat(srcPath); err != nil {+ if os.IsNotExist(err) {+ err = errors.New("import task not found or expired")+ }+ return "", err+ }+ path = filepath.Join(stagedSYImportDir(), token+"-importing.zip")+ err = os.Rename(srcPath, path)+ return+}++func cleanupStagedSYImports() {+ entries, err := os.ReadDir(stagedSYImportDir())+ if err != nil {+ return+ }+ now := time.Now()+ for _, entry := range entries {+ name := entry.Name()+ if !strings.HasSuffix(name, ".zip") || !isValidSYImportToken(strings.TrimSuffix(name, ".zip")) {+ continue+ }+ info, infoErr := entry.Info()+ if infoErr == nil && now.Sub(info.ModTime()) > stagedSYImportTTL {+ _ = os.Remove(filepath.Join(stagedSYImportDir(), name))+ }+ }+}++func stagedSYImportDir() string {+ return filepath.Join(util.TempDir, "import", "sy")+}++func stagedSYImportPath(token string) string {+ return filepath.Join(stagedSYImportDir(), token+".zip")+}++func isValidSYImportToken(token string) bool {+ if len(token) != 32 {+ return false+ }+ for _, char := range token {+ if !(char >= 'a' && char <= 'z') && !(char >= 'A' && char <= 'Z') && !(char >= '0' && char <= '9') {+ return false+ }+ }+ return true+}+func saveImportUpload(c *gin.Context) (form *multipart.Form, writePath string, cleanup func(), err error) {form, err = c.MultipartForm()if err != nil {diff --git a/kernel/api/import_test.go b/kernel/api/import_test.gonew file mode 100644index 0000000000..e12a1d144f--- /dev/null+++ b/kernel/api/import_test.go@@ -0,0 +1,86 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestIsValidSYImportToken(t *testing.T) {+ tests := []struct {+ name string+ token string+ want bool+ }{+ {name: "valid", token: "0123456789abcdefghijklmnopqrstuv", want: true},+ {name: "too short", token: "0123456789abcdefghijklmnopqrstu"},+ {name: "path traversal", token: "../23456789abcdefghijklmnopqrstuv"},+ {name: "separator", token: "0123456789abcdefghij/klmnopqrstu"},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if got := isValidSYImportToken(test.token); got != test.want {+ t.Fatalf("isValidSYImportToken() = %v, want %v", got, test.want)+ }+ })+ }+}++func TestStageAndClaimSYImport(t *testing.T) {+ tempDir := t.TempDir()+ originalTempDir := util.TempDir+ util.TempDir = tempDir+ t.Cleanup(func() {+ util.TempDir = originalTempDir+ })++ srcPath := filepath.Join(tempDir, "document.sy.zip")+ data := []byte("archive")+ if err := os.WriteFile(srcPath, data, 0644); err != nil {+ t.Fatal(err)+ }+ token, err := stageSYImport(srcPath)+ if err != nil {+ t.Fatal(err)+ }+ if !isValidSYImportToken(token) {+ t.Fatalf("invalid staged token %q", token)+ }+ if _, err = os.Stat(srcPath); !os.IsNotExist(err) {+ t.Fatalf("source archive still exists: %v", err)+ }++ claimedPath, err := claimStagedSYImport(token)+ if err != nil {+ t.Fatal(err)+ }+ claimedData, err := os.ReadFile(claimedPath)+ if err != nil {+ t.Fatal(err)+ }+ if string(claimedData) != string(data) {+ t.Fatalf("claimed archive data = %q, want %q", claimedData, data)+ }+ if _, err = claimStagedSYImport(token); err == nil {+ t.Fatal("claimed import should not be claimable again")+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 06ef5300c7..a3d357ed8e 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -395,6 +395,8 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/import/importSY", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importSY)ginServer.Handle("POST", "/api/import/importSYNotebook", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importSYNotebook)ginServer.Handle("POST", "/api/import/importSYAuto", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importSYAuto)+ ginServer.Handle("POST", "/api/import/continueImportSY", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, continueImportSY)+ ginServer.Handle("POST", "/api/import/cancelImportSY", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, cancelImportSY)ginServer.Handle("POST", "/api/import/startObsidianVaultAnalysis", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, startObsidianVaultAnalysis)ginServer.Handle("POST", "/api/import/getObsidianVaultTask", model.CheckAuth, model.CheckAdminRole, getObsidianVaultTask)ginServer.Handle("POST", "/api/import/startObsidianVaultImport", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, startObsidianVaultImport)diff --git a/kernel/api/system.go b/kernel/api/system.goindex 4c92db7e3f..3562a8cf54 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -353,8 +353,27 @@ func exportConf(c *gin.Context) {clonedConf.Stat = nilclonedConf.Api = nilclonedConf.Repo = nil+ clonedConf.Secrets = nil+ clonedConf.NotebookCrypto = nil+ clonedConf.Onboarding = nilclonedConf.Publish = nil+ clonedConf.CookieKey = ""+ clonedConf.MCPOAuth = ""clonedConf.CloudRegion = 0+ if nil != clonedConf.AI {+ for _, provider := range clonedConf.AI.Providers {+ if nil != provider {+ provider.APIKey = ""+ }+ }+ if nil != clonedConf.AI.Embedding {+ clonedConf.AI.Embedding.APIKey = ""+ }+ if nil != clonedConf.AI.Rerank {+ clonedConf.AI.Rerank.APIKey = ""+ }+ clonedConf.AI.MCP = nil+ }data, err = gulu.JSON.MarshalIndentJSON(clonedConf, "", " ")if err != nil {@@ -518,6 +537,7 @@ func importConf(c *gin.Context) {ret.Msg = err.Error()return}+ preserveImportedAISecrets(importedConf.AI, model.Conf.AI)model.Conf.FileTree = importedConf.FileTreemodel.Conf.Tag = importedConf.Tag@@ -536,6 +556,41 @@ func importConf(c *gin.Context) {logging.LogInfof("imported conf")}+func preserveImportedAISecrets(imported, current *conf.AI) {+ if imported == nil || current == nil {+ return+ }++ currentProviders := map[string]*conf.Provider{}+ for _, provider := range current.Providers {+ if provider != nil && provider.ID != "" && provider.APIKey != "" {+ currentProviders[provider.ID] = provider+ }+ }+ for _, provider := range imported.Providers {+ if provider != nil && provider.APIKey == "" {+ if currentProvider := currentProviders[provider.ID]; currentProvider != nil &&+ currentProvider.BaseURL == provider.BaseURL && currentProvider.Protocol == provider.Protocol {+ provider.APIKey = currentProvider.APIKey+ }+ }+ }++ if imported.Embedding != nil && current.Embedding != nil && imported.Embedding.APIKey == "" &&+ imported.Embedding.ID != "" && imported.Embedding.ID == current.Embedding.ID &&+ imported.Embedding.BaseURL == current.Embedding.BaseURL {+ imported.Embedding.APIKey = current.Embedding.APIKey+ }+ if imported.Rerank != nil && current.Rerank != nil && imported.Rerank.APIKey == "" &&+ imported.Rerank.ID != "" && imported.Rerank.ID == current.Rerank.ID &&+ imported.Rerank.Endpoint == current.Rerank.Endpoint {+ imported.Rerank.APIKey = current.Rerank.APIKey+ }+ if imported.MCP == nil {+ imported.MCP = current.MCP+ }+}+func getConf(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/system_test.go b/kernel/api/system_test.gonew file mode 100644index 0000000000..4b6f5aff8c--- /dev/null+++ b/kernel/api/system_test.go@@ -0,0 +1,89 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+)++func TestPreserveImportedAISecrets(t *testing.T) {+ currentMCP := &conf.MCP{Servers: []conf.MCPServer{{ID: "server", Headers: map[string]string{"Authorization": "secret"}}}}+ current := &conf.AI{+ Providers: []*conf.Provider{+ {ID: "matching", APIKey: "local-key", BaseURL: "https://example.com", Protocol: "openai"},+ {ID: "changed-endpoint", APIKey: "endpoint-key", BaseURL: "https://local.example.com"},+ {ID: "removed", APIKey: "removed-key"},+ },+ Embedding: &conf.Embedding{ID: "embedding", APIKey: "embedding-key", BaseURL: "https://embedding.example.com"},+ Rerank: &conf.Rerank{ID: "rerank", APIKey: "rerank-key", Endpoint: "https://local.example.com/rerank"},+ MCP: currentMCP,+ }+ imported := &conf.AI{+ Providers: []*conf.Provider{+ {ID: "matching", BaseURL: "https://example.com", Protocol: "openai"},+ {ID: "changed-endpoint", BaseURL: "https://imported.example.com"},+ {ID: "different"},+ {ID: "provided", APIKey: "imported-key"},+ },+ Embedding: &conf.Embedding{ID: "embedding", BaseURL: "https://embedding.example.com"},+ Rerank: &conf.Rerank{ID: "rerank", Endpoint: "https://imported.example.com/rerank"},+ }++ preserveImportedAISecrets(imported, current)++ if imported.Providers[0].APIKey != "local-key" {+ t.Fatalf("matching provider key = %q, want local key", imported.Providers[0].APIKey)+ }+ if imported.Providers[1].APIKey != "" {+ t.Fatalf("changed endpoint provider key = %q, want empty", imported.Providers[1].APIKey)+ }+ if imported.Providers[2].APIKey != "" {+ t.Fatalf("different provider key = %q, want empty", imported.Providers[2].APIKey)+ }+ if imported.Providers[3].APIKey != "imported-key" {+ t.Fatalf("provided provider key = %q, want imported key", imported.Providers[3].APIKey)+ }+ if imported.Embedding.APIKey != "embedding-key" {+ t.Fatalf("embedding key = %q, want local key", imported.Embedding.APIKey)+ }+ if imported.Rerank.APIKey != "" {+ t.Fatalf("different rerank key = %q, want empty", imported.Rerank.APIKey)+ }+ if imported.MCP != currentMCP {+ t.Fatal("local MCP configuration was not preserved")+ }++ matchingRerank := &conf.AI{Rerank: &conf.Rerank{ID: "rerank", Endpoint: "https://local.example.com/rerank"}}+ preserveImportedAISecrets(matchingRerank, current)+ if matchingRerank.Rerank.APIKey != "rerank-key" {+ t.Fatalf("matching rerank key = %q, want local key", matchingRerank.Rerank.APIKey)+ }+}++func TestPreserveImportedMCPConfiguration(t *testing.T) {+ currentMCP := &conf.MCP{Servers: []conf.MCPServer{{ID: "current"}}}+ importedMCP := &conf.MCP{Servers: []conf.MCPServer{{ID: "imported"}}}+ imported := &conf.AI{MCP: importedMCP}++ preserveImportedAISecrets(imported, &conf.AI{MCP: currentMCP})++ if imported.MCP != importedMCP {+ t.Fatal("imported MCP configuration should take precedence")+ }+}diff --git a/kernel/model/import.go b/kernel/model/import.goindex 7ce68809fc..199dca80c2 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -123,6 +123,8 @@ func ImportSYNotebook(zipPath string) (boxID string, err error) {return importSY(zipPath, "", "/", true, false)}+var ErrSYTargetNotebookRequired = errors.New("target notebook required")+func ImportSYAuto(zipPath, boxID, toPath string) (createdBoxID string, notebook bool, err error) {createdBoxID, err = importSY(zipPath, boxID, toPath, false, true)notebook = err == nil && createdBoxID != boxID@@ -235,6 +237,10 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c}createNotebook = isSYNotebookExport(hasImportedBoxConf, hasImportedBoxDocMeta)}+ if autoDetect && !createNotebook && boxID == "" {+ err = ErrSYTargetNotebookRequired+ return+ }if !createNotebook && nil == Conf.Box(boxID) {err = errors.New(Conf.Language(0))return