Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve export file overwrite handling https://github.com/siyuan-note/siyuan/issues/18448

Daniel66c7c6e872f6
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 9e503ca0dd..451da3245f 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "تعذر حفظ الملف، تأكد من أنه غير مستخدم بواسطة برنامج آخر وأن موقع الوجهة قابل للكتابة",
"copyRichText": "نسخ النص المنسق/HTML",
"modelContextLengthTip": "اتركه فارغًا أو اضبطه على 0 لاستخدام دليل النماذج المدمج",
"modelContextLength": "طول سياق النموذج (Tokens)",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index c570e1a10a..1d374ccde7 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Die Datei kann nicht gespeichert werden: Stellen Sie sicher, dass sie nicht von einem anderen Programm verwendet wird und der Zielort beschreibbar ist",
"copyRichText": "Rich-Text/HTML kopieren",
"modelContextLengthTip": "Leer lassen oder auf 0 setzen, um den integrierten Modellkatalog zu verwenden",
"modelContextLength": "Modellkontextlänge (Tokens)",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 9e16817e24..d448443589 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Unable to save the file; make sure it is not in use by another program and the destination is writable",
"copyRichText": "Copy rich text/HTML",
"modelContextLengthTip": "Leave blank or set to 0 to use the built-in model catalog",
"modelContextLength": "Model Context Length (Tokens)",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 1871185102..02c9ec9604 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "No se pudo guardar el archivo; asegúrate de que ningún otro programa lo esté usando y de que se pueda escribir en la ubicación de destino",
"copyRichText": "Copiar texto enriquecido/HTML",
"modelContextLengthTip": "Déjalo en blanco o establece 0 para usar el catálogo de modelos integrado",
"modelContextLength": "Longitud del contexto del modelo (Tokens)",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index f622096733..c40783831e 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Impossible d’enregistrer le fichier ; vérifiez qu’il n’est pas utilisé par un autre programme et que l’emplacement de destination est accessible en écriture",
"copyRichText": "Copier le texte enrichi/HTML",
"modelContextLengthTip": "Laisser vide ou définir sur 0 pour utiliser le catalogue de modèles intégré",
"modelContextLength": "Longueur du contexte du modèle (Tokens)",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 2e9a568352..34b46f9eeb 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "לא ניתן לשמור את הקובץ; יש לוודא שהוא אינו בשימוש על ידי תוכנית אחרת ושניתן לכתוב במיקום היעד",
"copyRichText": "העתקת טקסט עשיר/HTML",
"modelContextLengthTip": "השאר ריק או הגדר ל-0 כדי להשתמש בקטלוג המודלים המובנה",
"modelContextLength": "אורך הקשר המודל (Tokens)",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 29afaeea54..8753e54d61 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "फ़ाइल सहेजी नहीं जा सकी; सुनिश्चित करें कि कोई अन्य प्रोग्राम इसका उपयोग नहीं कर रहा है और गंतव्य स्थान पर लिखा जा सकता है",
"copyRichText": "रिच टेक्स्ट/HTML कॉपी करें",
"modelContextLengthTip": "अंतर्निहित मॉडल कैटलॉग का उपयोग करने के लिए खाली छोड़ें या 0 पर सेट करें",
"modelContextLength": "मॉडल संदर्भ लंबाई (Tokens)",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index e25bd3792b..c156b9b5f9 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "File tidak dapat disimpan; pastikan file tidak sedang digunakan oleh program lain dan lokasi tujuan dapat ditulisi",
"copyRichText": "Salin teks kaya/HTML",
"modelContextLengthTip": "Kosongkan atau atur ke 0 untuk menggunakan katalog model bawaan",
"modelContextLength": "Panjang Konteks Model (Tokens)",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 8aac0b2f2b..5960614845 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Impossibile salvare il file; assicurati che non sia utilizzato da un altro programma e che il percorso di destinazione sia scrivibile",
"copyRichText": "Copia testo formattato/HTML",
"modelContextLengthTip": "Lascia vuoto o imposta 0 per usare il catalogo dei modelli integrato",
"modelContextLength": "Lunghezza del contesto del modello (Tokens)",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 062f982f54..6905aa296f 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "ファイルを保存できません。別のプログラムで使用されていないこと、および保存先に書き込み可能であることを確認してください",
"copyRichText": "リッチテキスト/HTMLとしてコピー",
"modelContextLengthTip": "空欄または 0 にすると内蔵モデルカタログを使用します",
"modelContextLength": "モデルのコンテキスト長(Tokens)",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 91b3efcbd6..d0d169264d 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "파일을 저장할 수 없습니다. 다른 프로그램에서 사용 중이지 않고 대상 위치에 쓰기 권한이 있는지 확인하세요",
"copyRichText": "서식 있는 텍스트/HTML 복사",
"modelContextLengthTip": "비워 두거나 0으로 설정하면 내장 모델 카탈로그를 사용합니다",
"modelContextLength": "모델 컨텍스트 길이 (Tokens)",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 73a436ec27..ffc42da244 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Kan het bestand niet opslaan; controleer of het niet door een ander programma wordt gebruikt en of de doellocatie beschrijfbaar is",
"copyRichText": "Rijke tekst/HTML kopiëren",
"modelContextLengthTip": "Laat leeg of stel in op 0 om de ingebouwde modelcatalogus te gebruiken",
"modelContextLength": "Modelcontextlengte (Tokens)",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 2566351110..1d7948cb38 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Nie można zapisać pliku; upewnij się, że nie jest używany przez inny program i że lokalizacja docelowa jest zapisywalna",
"copyRichText": "Kopiuj tekst sformatowany/HTML",
"modelContextLengthTip": "Pozostaw puste lub ustaw 0, aby użyć wbudowanego katalogu modeli",
"modelContextLength": "Długość kontekstu modelu (Tokens)",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 2e2d445586..b4ec0793fe 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Não foi possível salvar o arquivo; verifique se ele não está sendo usado por outro programa e se o local de destino permite gravação",
"copyRichText": "Copiar texto formatado/HTML",
"modelContextLengthTip": "Deixe em branco ou defina como 0 para usar o catálogo de modelos integrado",
"modelContextLength": "Tamanho do contexto do modelo (Tokens)",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 4094792463..0e65b72e15 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Не удалось сохранить файл; убедитесь, что он не используется другой программой и что в целевую папку разрешена запись",
"copyRichText": "Копировать форматированный текст/HTML",
"modelContextLengthTip": "Оставьте пустым или укажите 0, чтобы использовать встроенный каталог моделей",
"modelContextLength": "Длина контекста модели (Tokens)",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 6663c6ed6a..3a0459e1bb 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Súbor sa nepodarilo uložiť; uistite sa, že ho nepoužíva iný program a že cieľové umiestnenie je zapisovateľné",
"copyRichText": "Kopírovať formátovaný text/HTML",
"modelContextLengthTip": "Ponechajte prázdne alebo nastavte 0, aby sa použil vstavaný katalóg modelov",
"modelContextLength": "Dĺžka kontextu modelu (Tokens)",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 07f3cb59b8..2684459743 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "ไม่สามารถบันทึกไฟล์ได้ โปรดตรวจสอบว่าไฟล์ไม่ได้ถูกใช้งานโดยโปรแกรมอื่นและตำแหน่งปลายทางสามารถเขียนได้",
"copyRichText": "คัดลอกข้อความแบบ Rich Text/HTML",
"modelContextLengthTip": "เว้นว่างหรือตั้งค่าเป็น 0 เพื่อใช้แค็ตตาล็อกโมเดลในตัว",
"modelContextLength": "ความยาวบริบทของโมเดล (Tokens)",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index a52116fdf3..466689a0bd 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Dosya kaydedilemedi; başka bir program tarafından kullanılmadığından ve hedef konumun yazılabilir olduğundan emin olun",
"copyRichText": "Zengin metni/HTML'yi kopyala",
"modelContextLengthTip": "Yerleşik model kataloğunu kullanmak için boş bırakın veya 0 olarak ayarlayın",
"modelContextLength": "Model Bağlam Uzunluğu (Tokens)",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index d91061ba51..6e8b564052 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "Не вдалося зберегти файл; переконайтеся, що він не використовується іншою програмою і що в цільову папку дозволено запис",
"copyRichText": "Копіювати форматований текст/HTML",
"modelContextLengthTip": "Залиште порожнім або встановіть 0, щоб використовувати вбудований каталог моделей",
"modelContextLength": "Довжина контексту моделі (Tokens)",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 2519895406..d4874c65cb 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "无法保存文件,请确认该文件未被其他程序占用且目标位置可写",
"copyRichText": "复制富文本/HTML",
"modelContextLengthTip": "留空或设为 0 时使用内置模型表识别",
"modelContextLength": "模型上下文长度(Token)",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 55503e66de..03ad2a8bef 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "exportFileSaveFailed": "無法儲存檔案,請確認該檔案未被其他程式佔用且目標位置可寫入",
"copyRichText": "複製富文字/HTML",
"modelContextLengthTip": "留空或設為 0 時使用內建模型表識別",
"modelContextLength": "模型上下文長度(Token)",
diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.ts
index 27d971c520..cc583df622 100644
--- a/app/src/protyle/util/compatibility.ts
+++ b/app/src/protyle/util/compatibility.ts
@@ -114,7 +114,8 @@ export const saveExportFile = async (uri: string, msgId?: string) => {
if (msgId) {
hideMessage(msgId);
}
- showMessage("saveExportFile failed: " + e);
+ console.error("saveExportFile failed:", e);
+ showMessage(window.siyuan.languages.exportFileSaveFailed, 0, "error");
}
/// #else
try {
diff --git a/kernel/api/export.go b/kernel/api/export.go
index e5eb8be76f..a9a3bb3e70 100644
--- a/kernel/api/export.go
+++ b/kernel/api/export.go
@@ -17,6 +17,7 @@
package api
import (
+ "fmt"
"io"
"mime"
"net/http"
@@ -1072,10 +1073,64 @@ func copyExportFile(c *gin.Context) {
return
}
- if err := filelock.Copy(srcFullPath, dest); err != nil {
+ if err := copyExportFileToDestination(srcFullPath, dest); err != nil {
logging.LogErrorf("copy export file [%s] to [%s] failed: %s", srcFullPath, dest, err)
ret.Code = -1
ret.Msg = err.Error()
return
}
}
+
+func copyExportFileToDestination(src, dest string) (err error) {
+ filelock.Lock(src)
+ defer filelock.Unlock(src)
+
+ srcInfo, err := os.Lstat(src)
+ if err != nil {
+ return err
+ }
+ if !srcInfo.Mode().IsRegular() {
+ return fmt.Errorf("export source [%s] is not a regular file", src)
+ }
+
+ srcFile, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer srcFile.Close()
+
+ destDir := filepath.Dir(dest)
+ if err = os.MkdirAll(destDir, 0755); err != nil {
+ return err
+ }
+ tmpFile, err := os.CreateTemp(destDir, ".siyuan-export-*.tmp")
+ if err != nil {
+ return err
+ }
+ tmpPath := tmpFile.Name()
+ tmpClosed := false
+ defer func() {
+ if !tmpClosed {
+ _ = tmpFile.Close()
+ }
+ if removeErr := os.Remove(tmpPath); removeErr != nil && !os.IsNotExist(removeErr) {
+ logging.LogWarnf("remove temporary export file [%s] failed: %s", tmpPath, removeErr)
+ }
+ }()
+
+ if _, err = io.Copy(tmpFile, srcFile); err != nil {
+ return err
+ }
+ if err = tmpFile.Chmod(srcInfo.Mode().Perm()); err != nil {
+ return err
+ }
+ if err = tmpFile.Sync(); err != nil {
+ return err
+ }
+ if err = tmpFile.Close(); err != nil {
+ return err
+ }
+ tmpClosed = true
+
+ return os.Rename(tmpPath, dest)
+}
diff --git a/kernel/api/export_test.go b/kernel/api/export_test.go
new file mode 100644
index 0000000000..d48a1a9bbb
--- /dev/null
+++ b/kernel/api/export_test.go
@@ -0,0 +1,113 @@
+// 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"
+)
+
+func TestCopyExportFileToDestination(t *testing.T) {
+ dir := t.TempDir()
+ src := filepath.Join(dir, "source.zip")
+ dest := filepath.Join(dir, "destination.zip")
+
+ if err := os.WriteFile(src, []byte("new export"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(dest, []byte("old export"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := copyExportFileToDestination(src, dest); err != nil {
+ t.Fatal(err)
+ }
+
+ data, err := os.ReadFile(dest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := string(data), "new export"; got != want {
+ t.Fatalf("destination content = %q, want %q", got, want)
+ }
+ assertNoExportTempFiles(t, dir)
+}
+
+func TestCopyExportFileToDestinationCreatesParent(t *testing.T) {
+ dir := t.TempDir()
+ src := filepath.Join(dir, "source.zip")
+ dest := filepath.Join(dir, "new", "destination.zip")
+
+ if err := os.WriteFile(src, []byte("new export"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := copyExportFileToDestination(src, dest); err != nil {
+ t.Fatal(err)
+ }
+
+ data, err := os.ReadFile(dest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := string(data), "new export"; got != want {
+ t.Fatalf("destination content = %q, want %q", got, want)
+ }
+ assertNoExportTempFiles(t, filepath.Dir(dest))
+}
+
+func TestCopyExportFileToDestinationReplaceFailure(t *testing.T) {
+ dir := t.TempDir()
+ src := filepath.Join(dir, "source.zip")
+ dest := filepath.Join(dir, "destination.zip")
+
+ if err := os.WriteFile(src, []byte("new export"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(dest, 0755); err != nil {
+ t.Fatal(err)
+ }
+ marker := filepath.Join(dest, "marker")
+ if err := os.WriteFile(marker, []byte("old export"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := copyExportFileToDestination(src, dest); err == nil {
+ t.Fatal("expected replacing a directory to fail")
+ }
+
+ data, err := os.ReadFile(marker)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := string(data), "old export"; got != want {
+ t.Fatalf("existing destination content = %q, want %q", got, want)
+ }
+ assertNoExportTempFiles(t, dir)
+}
+
+func assertNoExportTempFiles(t *testing.T, dir string) {
+ t.Helper()
+
+ matches, err := filepath.Glob(filepath.Join(dir, ".siyuan-export-*.tmp"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(matches) != 0 {
+ t.Fatalf("temporary export files were not cleaned up: %v", matches)
+ }
+}
diff --git a/kernel/api/export_windows_test.go b/kernel/api/export_windows_test.go
new file mode 100644
index 0000000000..f3aa940e60
--- /dev/null
+++ b/kernel/api/export_windows_test.go
@@ -0,0 +1,79 @@
+// 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/>.
+
+//go:build windows
+
+package api
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "golang.org/x/sys/windows"
+)
+
+func TestCopyExportFileToOccupiedDestination(t *testing.T) {
+ dir := t.TempDir()
+ src := filepath.Join(dir, "source.zip")
+ dest := filepath.Join(dir, "destination.zip")
+
+ if err := os.WriteFile(src, []byte("new export"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(dest, []byte("old export"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ destUTF16, err := windows.UTF16PtrFromString(dest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ handle, err := windows.CreateFile(
+ destUTF16,
+ windows.GENERIC_READ,
+ 0,
+ nil,
+ windows.OPEN_EXISTING,
+ windows.FILE_ATTRIBUTE_NORMAL,
+ 0,
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ if handle != windows.InvalidHandle {
+ _ = windows.CloseHandle(handle)
+ }
+ }()
+
+ if err = copyExportFileToDestination(src, dest); err == nil {
+ t.Fatal("expected replacing an occupied destination to fail")
+ }
+ if err = windows.CloseHandle(handle); err != nil {
+ t.Fatal(err)
+ }
+ handle = windows.InvalidHandle
+
+ data, err := os.ReadFile(dest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := string(data), "old export"; got != want {
+ t.Fatalf("occupied destination content = %q, want %q", got, want)
+ }
+ assertNoExportTempFiles(t, dir)
+}