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: Support on-demand asset downloads during data sync https://github.com/siyuan-note/siyuan/issues/19149
Daniel7d9f55a0c4f8
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 1bfad1b42b..1b0efa8b49 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "يعتمد محتوى بعض الموارد على التخزين السحابي؛ هذه اللقطة المحلية غير مكتملة",+ "syncAssetDownloadMode": "تنزيل ملفات الموارد",+ "syncAssetDownloadModeTip": "ينطبق على هذا الجهاز فقط. تُنزَّل الموارد عند الطلب وقت استخدامها، ولا تتوفر دون اتصال حتى يتم تنزيلها. تُحفَظ الموارد المنزلة وتُحدَّث أثناء المزامنة. عند التبديل إلى تنزيل الكل، يتم تنزيل الموارد الناقصة أولاً",+ "syncAssetDownloadAll": "تنزيل الكل",+ "syncAssetDownloadOnDemand": "التنزيل عند الطلب",+ "syncAssetDownloadModeUpdating": "جارٍ تحديث وضع تنزيل الموارد...",+ "syncAssetDownloadModeFailed": "تعذر تحديث وضع تنزيل الموارد","globalDefaultFont": "الخط الافتراضي العام","globalDefaultFontTip": "يُستخدم للواجهة والمحتوى الذي لم يُحدَّد له خط منفصل؛ اترك الاختيار فارغًا لاستخدام الخط الافتراضي للسمة","mobileMultiSelectTip": "اضغط على الكتل لتحديدها أو إلغاء تحديدها",@@ -2696,6 +2703,8 @@"372": "تمت استعادة المفكرة وستظل مغلقة","373": "تحتوي هذه الحزمة المضغوطة على بيانات دفتر ملاحظات. يرجى استيرادها من [شجرة المستندات - المزيد - استيراد دفتر ملاحظات]","374": "قاعدة البيانات [%s]، حقل القالب [%s]، أول عنصر متأثر [%s] (معرّف العنصر: %s)، عدد العناصر المتأثرة: %d، الخطأ: %s",- "375": "دفتر حفظ الملاحظات السريعة غير متاح. اختر دفتر ملاحظات مفتوحًا وغير مشفر في الإعدادات - المستند"+ "375": "دفتر حفظ الملاحظات السريعة غير متاح. اختر دفتر ملاحظات مفتوحًا وغير مشفر في الإعدادات - المستند",+ "376": "لم يتم تنزيل المورد بعد ولا يمكن جلبه حالياً",+ "377": "يرجى التبديل إلى تنزيل الكل قبل تغيير مستودع البيانات أو إعادة تعيينه"}}diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 8fdf716793..86adf087e7 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Einige Ressourceninhalte sind vom Cloudspeicher abhängig; dieser lokale Schnappschuss ist unvollständig",+ "syncAssetDownloadMode": "Ressourcendownloads",+ "syncAssetDownloadModeTip": "Gilt nur für dieses Gerät. Ressourcen werden bei Bedarf heruntergeladen und sind bis dahin offline nicht verfügbar. Heruntergeladene Ressourcen bleiben gespeichert und werden bei der Synchronisierung aktualisiert. Beim Wechsel zu Alle herunterladen werden zuerst fehlende Ressourcen heruntergeladen",+ "syncAssetDownloadAll": "Alle herunterladen",+ "syncAssetDownloadOnDemand": "Bei Bedarf herunterladen",+ "syncAssetDownloadModeUpdating": "Downloadmodus für Ressourcen wird aktualisiert...",+ "syncAssetDownloadModeFailed": "Downloadmodus für Ressourcen konnte nicht aktualisiert werden","globalDefaultFont": "Globale Standardschrift","globalDefaultFontTip": "Für die Oberfläche und Inhalte ohne eigene Schrifteinstellung; ohne Auswahl wird die Standardschrift des Designs verwendet","mobileMultiSelectTip": "Tippe auf Blöcke, um sie auszuwählen oder die Auswahl aufzuheben",@@ -2696,6 +2703,8 @@"372": "Das Notizbuch wurde wiederhergestellt und bleibt geschlossen","373": "Dieses Archiv enthält Notizbuchdaten. Bitte importieren Sie es über [Dokumentenbaum - Mehr - Notizbuch importieren]","374": "Datenbank [%s], Vorlagenfeld [%s], erster betroffener Eintrag [%s] (Element-ID: %s), Anzahl betroffener Einträge: %d, Fehler: %s",- "375": "Das Notizbuch zum Speichern von Kurznotizen ist nicht verfügbar. Wählen Sie unter Einstellungen - Dokument ein geöffnetes, unverschlüsseltes Notizbuch"+ "375": "Das Notizbuch zum Speichern von Kurznotizen ist nicht verfügbar. Wählen Sie unter Einstellungen - Dokument ein geöffnetes, unverschlüsseltes Notizbuch",+ "376": "Die Ressource wurde noch nicht heruntergeladen und kann derzeit nicht abgerufen werden",+ "377": "Bitte wechseln Sie zu Alle herunterladen, bevor Sie das Datenrepository ändern oder zurücksetzen"}}diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex b5efea15e1..facc1d05ef 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Some asset content depends on cloud storage; this local snapshot is incomplete",+ "syncAssetDownloadMode": "Asset downloads",+ "syncAssetDownloadModeTip": "Applies only to this device. On-demand assets are downloaded when used and unavailable offline until downloaded. Downloaded assets are kept and updated during sync. Switching to Download all first downloads missing assets",+ "syncAssetDownloadAll": "Download all",+ "syncAssetDownloadOnDemand": "Download on demand",+ "syncAssetDownloadModeUpdating": "Updating asset download mode...",+ "syncAssetDownloadModeFailed": "Unable to update asset download mode","globalDefaultFont": "Global Default Font","globalDefaultFontTip": "Used for the interface and content without a separate font setting; leave empty to use the theme's default font","mobileMultiSelectTip": "Tap blocks to select or deselect them",@@ -2696,6 +2703,8 @@"372": "The notebook has been restored and remains closed","373": "This archive contains notebook data. Please import it from [Document Tree - More - Import Notebook]","374": "Database [%s], template field [%s], first affected item [%s] (item ID: %s), affected item count: %d, error: %s",- "375": "The shorthand save notebook is unavailable. Select an opened non-encrypted notebook in Settings - Document"+ "375": "The shorthand save notebook is unavailable. Select an opened non-encrypted notebook in Settings - Document",+ "376": "The asset has not been downloaded and cannot be retrieved right now",+ "377": "Please switch to Download all before changing or resetting the data repository"}}diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex eac924d691..c4afb23c88 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "El contenido de algunos recursos depende del almacenamiento en la nube; esta instantánea local está incompleta",+ "syncAssetDownloadMode": "Descarga de recursos",+ "syncAssetDownloadModeTip": "Solo se aplica a este dispositivo. Los recursos bajo demanda se descargan al usarlos y no están disponibles sin conexión hasta entonces. Los recursos descargados se conservan y actualizan durante la sincronización. Al cambiar a Descargar todos, primero se descargan los recursos que faltan",+ "syncAssetDownloadAll": "Descargar todos",+ "syncAssetDownloadOnDemand": "Descargar bajo demanda",+ "syncAssetDownloadModeUpdating": "Actualizando el modo de descarga de recursos...",+ "syncAssetDownloadModeFailed": "No se puede actualizar el modo de descarga de recursos","globalDefaultFont": "Fuente predeterminada global","globalDefaultFontTip": "Se usa en la interfaz y en el contenido sin una fuente específica; deja la selección vacía para usar la fuente predeterminada del tema","mobileMultiSelectTip": "Toca los bloques para seleccionarlos o deseleccionarlos",@@ -2696,6 +2703,8 @@"372": "El cuaderno se ha restaurado y permanece cerrado","373": "Este archivo contiene datos de cuadernos. Impórtelo desde [Árbol de documentos - Más - Importar cuaderno]","374": "Base de datos [%s], campo de plantilla [%s], primer elemento afectado [%s] (ID del elemento: %s), cantidad de elementos afectados: %d, error: %s",- "375": "El cuaderno para guardar notas rápidas no está disponible. Seleccione un cuaderno abierto y sin cifrar en Configuración - Documento"+ "375": "El cuaderno para guardar notas rápidas no está disponible. Seleccione un cuaderno abierto y sin cifrar en Configuración - Documento",+ "376": "El recurso aún no se ha descargado y no se puede obtener en este momento",+ "377": "Cambie a Descargar todos antes de cambiar o restablecer el repositorio de datos"}}diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 946593ce5f..695730b057 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Le contenu de certaines ressources dépend du stockage cloud ; cet instantané local est incomplet",+ "syncAssetDownloadMode": "Téléchargement des ressources",+ "syncAssetDownloadModeTip": "S’applique uniquement à cet appareil. Les ressources à la demande sont téléchargées lors de leur utilisation et restent indisponibles hors ligne jusque-là. Les ressources téléchargées sont conservées et mises à jour lors de la synchronisation. Le passage à Tout télécharger commence par télécharger les ressources manquantes",+ "syncAssetDownloadAll": "Tout télécharger",+ "syncAssetDownloadOnDemand": "Télécharger à la demande",+ "syncAssetDownloadModeUpdating": "Mise à jour du mode de téléchargement des ressources...",+ "syncAssetDownloadModeFailed": "Impossible de mettre à jour le mode de téléchargement des ressources","globalDefaultFont": "Police globale par défaut","globalDefaultFontTip": "Utilisée pour l'interface et le contenu sans police spécifique ; ne sélectionnez aucune police pour utiliser celle du thème","mobileMultiSelectTip": "Touchez les blocs pour les sélectionner ou les désélectionner",@@ -2696,6 +2703,8 @@"372": "Le carnet a été restauré et reste fermé","373": "Cette archive contient des données de carnet. Veuillez l’importer depuis [Arborescence des documents - Plus - Importer un carnet]","374": "Base de données [%s], champ de modèle [%s], premier élément affecté [%s] (ID de l’élément : %s), nombre d’éléments affectés : %d, erreur : %s",- "375": "Le carnet d’enregistrement des notes rapides n’est pas disponible. Sélectionnez un carnet ouvert et non chiffré dans Paramètres - Document"+ "375": "Le carnet d’enregistrement des notes rapides n’est pas disponible. Sélectionnez un carnet ouvert et non chiffré dans Paramètres - Document",+ "376": "La ressource n’a pas encore été téléchargée et ne peut pas être récupérée actuellement",+ "377": "Veuillez passer à Tout télécharger avant de modifier ou de réinitialiser le dépôt de données"}}diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex e7b90c955c..ff0294ea09 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "התוכן של חלק מהמשאבים תלוי באחסון בענן; תמונת מצב מקומית זו אינה שלמה",+ "syncAssetDownloadMode": "הורדת קובצי משאבים",+ "syncAssetDownloadModeTip": "חל על מכשיר זה בלבד. משאבים לפי דרישה יורדים בעת השימוש ואינם זמינים ללא חיבור עד להורדתם. משאבים שהורדו נשמרים ומתעדכנים במהלך הסנכרון. במעבר להורדת הכול יורדים תחילה המשאבים החסרים",+ "syncAssetDownloadAll": "הורדת הכול",+ "syncAssetDownloadOnDemand": "הורדה לפי דרישה",+ "syncAssetDownloadModeUpdating": "מעדכן את מצב הורדת המשאבים...",+ "syncAssetDownloadModeFailed": "לא ניתן לעדכן את מצב הורדת המשאבים","globalDefaultFont": "גופן ברירת מחדל כללי","globalDefaultFontTip": "משמש לממשק ולתוכן ללא הגדרת גופן נפרדת; יש להשאיר את הבחירה ריקה כדי להשתמש בגופן ברירת המחדל של ערכת הנושא","mobileMultiSelectTip": "הקישו על בלוקים כדי לבחור אותם או לבטל את בחירתם",@@ -2696,6 +2703,8 @@"372": "המחברת שוחזרה ונשארה סגורה","373": "ארכיון זה מכיל נתוני מחברת. יש לייבא אותו מתוך [עץ המסמכים - עוד - ייבוא מחברת]","374": "מסד הנתונים [%s], שדה התבנית [%s], הפריט המושפע הראשון [%s] (מזהה פריט: %s), מספר הפריטים המושפעים: %d, שגיאה: %s",- "375": "מחברת השמירה של הרשומות המהירות אינה זמינה. יש לבחור מחברת פתוחה ולא מוצפנת בהגדרות - מסמך"+ "375": "מחברת השמירה של הרשומות המהירות אינה זמינה. יש לבחור מחברת פתוחה ולא מוצפנת בהגדרות - מסמך",+ "376": "המשאב טרם הורד ולא ניתן לאחזר אותו כעת",+ "377": "יש לעבור להורדת הכול לפני שינוי מאגר הנתונים או איפוסו"}}diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 3baf433adb..9076b0952a 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "कुछ संसाधनों की सामग्री क्लाउड स्टोरेज पर निर्भर है; यह स्थानीय स्नैपशॉट अधूरा है",+ "syncAssetDownloadMode": "संसाधन फ़ाइल डाउनलोड",+ "syncAssetDownloadModeTip": "केवल इस डिवाइस पर लागू होता है। आवश्यकतानुसार मोड में संसाधन उपयोग के समय डाउनलोड होते हैं और डाउनलोड होने तक ऑफ़लाइन उपलब्ध नहीं होते। डाउनलोड किए गए संसाधन सुरक्षित रखे जाते हैं और सिंक के दौरान अपडेट होते हैं। सभी डाउनलोड करें पर स्विच करने से पहले अनुपलब्ध संसाधन डाउनलोड किए जाते हैं",+ "syncAssetDownloadAll": "सभी डाउनलोड करें",+ "syncAssetDownloadOnDemand": "आवश्यकतानुसार डाउनलोड करें",+ "syncAssetDownloadModeUpdating": "संसाधन डाउनलोड मोड अपडेट हो रहा है...",+ "syncAssetDownloadModeFailed": "संसाधन डाउनलोड मोड अपडेट नहीं किया जा सका","globalDefaultFont": "वैश्विक डिफ़ॉल्ट फ़ॉन्ट","globalDefaultFontTip": "इंटरफ़ेस और अलग फ़ॉन्ट सेटिंग के बिना सामग्री के लिए उपयोग किया जाता है; थीम का डिफ़ॉल्ट फ़ॉन्ट उपयोग करने के लिए चयन खाली छोड़ें","mobileMultiSelectTip": "ब्लॉक चुनने या उनका चयन हटाने के लिए उन पर टैप करें",@@ -2696,6 +2703,8 @@"372": "नोटबुक पुनर्स्थापित हो गई है और बंद रहेगी","373": "इस संग्रह में नोटबुक डेटा है। कृपया इसे [दस्तावेज़ ट्री - अधिक - नोटबुक आयात करें] से आयात करें","374": "डेटाबेस [%s], टेम्पलेट फ़ील्ड [%s], पहला प्रभावित आइटम [%s] (आइटम ID: %s), प्रभावित आइटम की संख्या: %d, त्रुटि: %s",- "375": "त्वरित नोट सहेजने वाली नोटबुक उपलब्ध नहीं है। सेटिंग्स - दस्तावेज़ में कोई खुली और गैर-एन्क्रिप्टेड नोटबुक चुनें"+ "375": "त्वरित नोट सहेजने वाली नोटबुक उपलब्ध नहीं है। सेटिंग्स - दस्तावेज़ में कोई खुली और गैर-एन्क्रिप्टेड नोटबुक चुनें",+ "376": "संसाधन अभी डाउनलोड नहीं हुआ है और इस समय प्राप्त नहीं किया जा सकता",+ "377": "डेटा रिपॉज़िटरी बदलने या रीसेट करने से पहले सभी डाउनलोड करें पर स्विच करें"}}diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 312bb6aafe..3f59de0889 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Sebagian konten sumber daya bergantung pada penyimpanan awan; snapshot lokal ini belum lengkap",+ "syncAssetDownloadMode": "Unduhan berkas sumber daya",+ "syncAssetDownloadModeTip": "Hanya berlaku untuk perangkat ini. Sumber daya sesuai kebutuhan diunduh saat digunakan dan tidak tersedia luring sebelum diunduh. Sumber daya yang telah diunduh tetap disimpan dan diperbarui saat sinkronisasi. Beralih ke Unduh semua akan mengunduh sumber daya yang belum tersedia terlebih dahulu",+ "syncAssetDownloadAll": "Unduh semua",+ "syncAssetDownloadOnDemand": "Unduh sesuai kebutuhan",+ "syncAssetDownloadModeUpdating": "Memperbarui mode unduhan sumber daya...",+ "syncAssetDownloadModeFailed": "Tidak dapat memperbarui mode unduhan sumber daya","globalDefaultFont": "Font Default Global","globalDefaultFontTip": "Digunakan untuk antarmuka dan konten tanpa pengaturan font tersendiri; biarkan pilihan kosong untuk menggunakan font default tema","mobileMultiSelectTip": "Ketuk blok untuk memilih atau membatalkan pilihan",@@ -2696,6 +2703,8 @@"372": "Buku catatan telah dipulihkan dan tetap ditutup","373": "Arsip ini berisi data buku catatan. Impor dari [Pohon dokumen - Lainnya - Impor buku catatan]","374": "Basis data [%s], bidang templat [%s], item pertama yang terdampak [%s] (ID item: %s), jumlah item terdampak: %d, kesalahan: %s",- "375": "Buku catatan penyimpanan catatan cepat tidak tersedia. Pilih buku catatan terbuka dan tidak terenkripsi di Pengaturan - Dokumen"+ "375": "Buku catatan penyimpanan catatan cepat tidak tersedia. Pilih buku catatan terbuka dan tidak terenkripsi di Pengaturan - Dokumen",+ "376": "Sumber daya belum diunduh dan saat ini tidak dapat diambil",+ "377": "Beralihlah ke Unduh semua sebelum mengubah atau mengatur ulang repositori data"}}diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex fce87de2b7..5a204d3313 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Il contenuto di alcune risorse dipende dall’archiviazione cloud; questa istantanea locale è incompleta",+ "syncAssetDownloadMode": "Download delle risorse",+ "syncAssetDownloadModeTip": "Si applica solo a questo dispositivo. Le risorse su richiesta vengono scaricate quando utilizzate e non sono disponibili offline fino ad allora. Le risorse scaricate vengono conservate e aggiornate durante la sincronizzazione. Il passaggio a Scarica tutto scarica prima le risorse mancanti",+ "syncAssetDownloadAll": "Scarica tutto",+ "syncAssetDownloadOnDemand": "Scarica su richiesta",+ "syncAssetDownloadModeUpdating": "Aggiornamento della modalità di download delle risorse...",+ "syncAssetDownloadModeFailed": "Impossibile aggiornare la modalità di download delle risorse","globalDefaultFont": "Carattere predefinito globale","globalDefaultFontTip": "Usato per l'interfaccia e i contenuti senza un carattere specifico; lascia vuota la selezione per usare il carattere predefinito del tema","mobileMultiSelectTip": "Tocca i blocchi per selezionarli o deselezionarli",@@ -2696,6 +2703,8 @@"372": "Il taccuino è stato ripristinato e rimane chiuso","373": "Questo archivio contiene dati di un taccuino. Importalo da [Albero dei documenti - Altro - Importa taccuino]","374": "Database [%s], campo modello [%s], primo elemento interessato [%s] (ID elemento: %s), numero di elementi interessati: %d, errore: %s",- "375": "Il taccuino per il salvataggio delle note rapide non è disponibile. Seleziona un taccuino aperto e non crittografato in Impostazioni - Documento"+ "375": "Il taccuino per il salvataggio delle note rapide non è disponibile. Seleziona un taccuino aperto e non crittografato in Impostazioni - Documento",+ "376": "La risorsa non è ancora stata scaricata e al momento non può essere recuperata",+ "377": "Passa a Scarica tutto prima di cambiare o reimpostare il repository dei dati"}}diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 0ead3f0e1b..fcec8d321b 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "一部のリソースファイルはクラウドに依存しているため、このローカルスナップショットは不完全です",+ "syncAssetDownloadMode": "リソースファイルのダウンロード",+ "syncAssetDownloadModeTip": "現在の端末にのみ適用されます。必要時にダウンロードするモードでは、リソースファイルは使用時にダウンロードされ、それまではオフラインで利用できません。ダウンロード済みのファイルは保持され、同期時に更新されます。すべてダウンロードに切り替える前に、不足しているファイルをダウンロードします",+ "syncAssetDownloadAll": "すべてダウンロード",+ "syncAssetDownloadOnDemand": "必要時にダウンロード",+ "syncAssetDownloadModeUpdating": "リソースファイルのダウンロードモードを更新中...",+ "syncAssetDownloadModeFailed": "リソースファイルのダウンロードモードを更新できません","globalDefaultFont": "全体の既定フォント","globalDefaultFontTip": "インターフェースとフォントを個別に設定していないコンテンツに使用します。何も選択しない場合はテーマの既定フォントを使用します","mobileMultiSelectTip": "ブロックをタップして選択または選択解除",@@ -2696,6 +2703,8 @@"372": "ノートブックを復元し、閉じた状態を維持しました","373": "このアーカイブにはノートブックデータが含まれています。[ドキュメントツリー - その他 - ノートブックをインポート] からインポートしてください","374": "データベース [%s]、テンプレートフィールド [%s]、最初のエラー項目 [%s](項目 ID: %s)、エラー項目数: %d、エラー: %s",- "375": "フラッシュメモの保存先ノートブックを使用できません。設定 - ドキュメントで、開いている暗号化されていないノートブックを選択してください"+ "375": "フラッシュメモの保存先ノートブックを使用できません。設定 - ドキュメントで、開いている暗号化されていないノートブックを選択してください",+ "376": "リソースファイルはまだダウンロードされておらず、現在取得できません",+ "377": "データリポジトリを変更またはリセットする前に、すべてダウンロードに切り替えてください"}}diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex ebaa6220e0..72a5ea5b9f 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "일부 리소스 내용이 클라우드 저장소에 의존하므로 이 로컬 스냅샷은 완전하지 않습니다",+ "syncAssetDownloadMode": "리소스 파일 다운로드",+ "syncAssetDownloadModeTip": "현재 기기에만 적용됩니다. 필요할 때 다운로드하는 모드에서는 리소스를 사용할 때 다운로드하며, 다운로드 전에는 오프라인에서 사용할 수 없습니다. 다운로드한 리소스는 보관되고 동기화 시 업데이트됩니다. 모두 다운로드로 전환하기 전에 누락된 리소스를 먼저 다운로드합니다",+ "syncAssetDownloadAll": "모두 다운로드",+ "syncAssetDownloadOnDemand": "필요할 때 다운로드",+ "syncAssetDownloadModeUpdating": "리소스 다운로드 모드 업데이트 중...",+ "syncAssetDownloadModeFailed": "리소스 다운로드 모드를 업데이트할 수 없습니다","globalDefaultFont": "전역 기본 글꼴","globalDefaultFontTip": "인터페이스와 글꼴을 별도로 설정하지 않은 콘텐츠에 사용하며, 글꼴을 선택하지 않으면 테마의 기본 글꼴을 사용합니다","mobileMultiSelectTip": "블록을 탭하여 선택하거나 선택 해제하세요",@@ -2696,6 +2703,8 @@"372": "노트북이 복원되었으며 닫힌 상태로 유지됩니다","373": "이 압축 파일에는 노트북 데이터가 포함되어 있습니다. [문서 트리 - 더보기 - 노트북 가져오기]에서 가져오세요","374": "데이터베이스 [%s], 템플릿 필드 [%s], 첫 번째 오류 항목 [%s](항목 ID: %s), 오류 항목 수: %d, 오류: %s",- "375": "플래시 메모 저장 노트북을 사용할 수 없습니다. 설정 - 문서에서 열려 있는 암호화되지 않은 노트북을 선택하세요"+ "375": "플래시 메모 저장 노트북을 사용할 수 없습니다. 설정 - 문서에서 열려 있는 암호화되지 않은 노트북을 선택하세요",+ "376": "리소스가 아직 다운로드되지 않았으며 현재 가져올 수 없습니다",+ "377": "데이터 저장소를 변경하거나 초기화하기 전에 모두 다운로드로 전환하세요"}}diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex b13cd240c9..e351e99eb5 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "De inhoud van sommige bronbestanden is afhankelijk van cloudopslag; deze lokale momentopname is onvolledig",+ "syncAssetDownloadMode": "Bronbestanden downloaden",+ "syncAssetDownloadModeTip": "Geldt alleen voor dit apparaat. Bronbestanden worden op aanvraag gedownload wanneer ze worden gebruikt en zijn tot die tijd offline niet beschikbaar. Gedownloade bestanden blijven bewaard en worden tijdens synchronisatie bijgewerkt. Bij het omschakelen naar Alles downloaden worden eerst de ontbrekende bestanden gedownload",+ "syncAssetDownloadAll": "Alles downloaden",+ "syncAssetDownloadOnDemand": "Op aanvraag downloaden",+ "syncAssetDownloadModeUpdating": "Downloadmodus voor bronbestanden bijwerken...",+ "syncAssetDownloadModeFailed": "Kan de downloadmodus voor bronbestanden niet bijwerken","globalDefaultFont": "Globaal standaardlettertype","globalDefaultFontTip": "Voor de interface en inhoud zonder afzonderlijk ingesteld lettertype; laat de selectie leeg om het standaardlettertype van het thema te gebruiken","mobileMultiSelectTip": "Tik op blokken om ze te selecteren of te deselecteren",@@ -2696,6 +2703,8 @@"372": "Het notitieboek is hersteld en blijft gesloten","373": "Dit archief bevat notitieboekgegevens. Importeer het via [Documentboom - Meer - Notitieboek importeren]","374": "Database [%s], sjabloonveld [%s], eerste betrokken item [%s] (item-ID: %s), aantal betrokken items: %d, fout: %s",- "375": "Het notitieboek voor snelle notities is niet beschikbaar. Selecteer een geopend, niet-versleuteld notitieboek in Instellingen - Document"+ "375": "Het notitieboek voor snelle notities is niet beschikbaar. Selecteer een geopend, niet-versleuteld notitieboek in Instellingen - Document",+ "376": "Het bronbestand is nog niet gedownload en kan momenteel niet worden opgehaald",+ "377": "Schakel over naar Alles downloaden voordat u de gegevensopslag wijzigt of opnieuw instelt"}}diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 4347516a36..7ae6321bb5 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Zawartość niektórych zasobów zależy od pamięci w chmurze; ta lokalna migawka jest niekompletna",+ "syncAssetDownloadMode": "Pobieranie zasobów",+ "syncAssetDownloadModeTip": "Dotyczy tylko tego urządzenia. Zasoby na żądanie są pobierane podczas użycia i do tego czasu są niedostępne offline. Pobrane zasoby są zachowywane i aktualizowane podczas synchronizacji. Przełączenie na Pobierz wszystkie najpierw pobiera brakujące zasoby",+ "syncAssetDownloadAll": "Pobierz wszystkie",+ "syncAssetDownloadOnDemand": "Pobieraj na żądanie",+ "syncAssetDownloadModeUpdating": "Aktualizowanie trybu pobierania zasobów...",+ "syncAssetDownloadModeFailed": "Nie można zaktualizować trybu pobierania zasobów","globalDefaultFont": "Globalna czcionka domyślna","globalDefaultFontTip": "Używana w interfejsie i treści bez osobnego ustawienia czcionki; pozostaw pusty wybór, aby użyć domyślnej czcionki motywu","mobileMultiSelectTip": "Dotknij bloków, aby je zaznaczyć lub odznaczyć",@@ -2696,6 +2703,8 @@"372": "Notatnik został przywrócony i pozostaje zamknięty","373": "To archiwum zawiera dane notatnika. Zaimportuj je z [Drzewo dokumentów - Więcej - Importuj notatnik]","374": "Baza danych [%s], pole szablonu [%s], pierwszy element z błędem [%s] (ID elementu: %s), liczba elementów z błędem: %d, błąd: %s",- "375": "Notatnik zapisu szybkich notatek jest niedostępny. Wybierz otwarty, niezaszyfrowany notatnik w Ustawienia - Dokument"+ "375": "Notatnik zapisu szybkich notatek jest niedostępny. Wybierz otwarty, niezaszyfrowany notatnik w Ustawienia - Dokument",+ "376": "Zasób nie został jeszcze pobrany i obecnie nie można go uzyskać",+ "377": "Przełącz na Pobierz wszystkie przed zmianą lub zresetowaniem repozytorium danych"}}diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 73fdcd6d8a..230f2ddc65 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "O conteúdo de alguns recursos depende do armazenamento em nuvem; este instantâneo local está incompleto",+ "syncAssetDownloadMode": "Download de recursos",+ "syncAssetDownloadModeTip": "Aplica-se apenas a este dispositivo. Os recursos sob demanda são baixados quando utilizados e ficam indisponíveis offline até então. Os recursos baixados são mantidos e atualizados durante a sincronização. Ao mudar para Baixar todos, os recursos ausentes são baixados primeiro",+ "syncAssetDownloadAll": "Baixar todos",+ "syncAssetDownloadOnDemand": "Baixar sob demanda",+ "syncAssetDownloadModeUpdating": "Atualizando o modo de download de recursos...",+ "syncAssetDownloadModeFailed": "Não foi possível atualizar o modo de download de recursos","globalDefaultFont": "Fonte padrão global","globalDefaultFontTip": "Usada na interface e no conteúdo sem uma fonte específica; deixe a seleção vazia para usar a fonte padrão do tema","mobileMultiSelectTip": "Toque nos blocos para selecioná-los ou desmarcá-los",@@ -2696,6 +2703,8 @@"372": "O caderno foi restaurado e permanece fechado","373": "Este arquivo contém dados de caderno. Importe-o em [Árvore de documentos - Mais - Importar caderno]","374": "Banco de dados [%s], campo de modelo [%s], primeiro item afetado [%s] (ID do item: %s), quantidade de itens afetados: %d, erro: %s",- "375": "O caderno para salvar notas rápidas não está disponível. Selecione um caderno aberto e não criptografado em Configurações - Documento"+ "375": "O caderno para salvar notas rápidas não está disponível. Selecione um caderno aberto e não criptografado em Configurações - Documento",+ "376": "O recurso ainda não foi baixado e não pode ser obtido no momento",+ "377": "Mude para Baixar todos antes de alterar ou redefinir o repositório de dados"}}diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 87d0211aa1..7dbf1393e7 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Содержимое некоторых ресурсов зависит от облачного хранилища; этот локальный снимок неполон",+ "syncAssetDownloadMode": "Загрузка файлов ресурсов",+ "syncAssetDownloadModeTip": "Применяется только к этому устройству. Ресурсы по требованию загружаются при использовании и до загрузки недоступны без сети. Загруженные ресурсы сохраняются и обновляются при синхронизации. При переключении на Загрузить все сначала загружаются недостающие ресурсы",+ "syncAssetDownloadAll": "Загрузить все",+ "syncAssetDownloadOnDemand": "Загружать по требованию",+ "syncAssetDownloadModeUpdating": "Обновление режима загрузки ресурсов...",+ "syncAssetDownloadModeFailed": "Не удалось обновить режим загрузки ресурсов","globalDefaultFont": "Глобальный шрифт по умолчанию","globalDefaultFontTip": "Используется для интерфейса и содержимого без отдельной настройки шрифта; если ничего не выбрано, используется шрифт темы по умолчанию","mobileMultiSelectTip": "Нажимайте на блоки, чтобы выделить их или снять выделение",@@ -2696,6 +2703,8 @@"372": "Блокнот восстановлен и остаётся закрытым","373": "Этот архив содержит данные блокнота. Импортируйте его через [Дерево документов - Ещё - Импортировать блокнот]","374": "База данных [%s], поле шаблона [%s], первый затронутый элемент [%s] (ID элемента: %s), количество затронутых элементов: %d, ошибка: %s",- "375": "Блокнот для сохранения быстрых заметок недоступен. Выберите открытый незашифрованный блокнот в Настройки - Документ"+ "375": "Блокнот для сохранения быстрых заметок недоступен. Выберите открытый незашифрованный блокнот в Настройки - Документ",+ "376": "Ресурс ещё не загружен и сейчас не может быть получен",+ "377": "Переключитесь на Загрузить все перед изменением или сбросом репозитория данных"}}diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex d0da9d8398..cd780195a3 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Obsah niektorých zdrojových súborov závisí od cloudového úložiska; táto lokálna snímka je neúplná",+ "syncAssetDownloadMode": "Sťahovanie zdrojových súborov",+ "syncAssetDownloadModeTip": "Platí iba pre toto zariadenie. Súbory na požiadanie sa sťahujú pri použití a dovtedy nie sú dostupné offline. Stiahnuté súbory sa uchovávajú a aktualizujú počas synchronizácie. Pri prepnutí na Stiahnuť všetky sa najprv stiahnu chýbajúce súbory",+ "syncAssetDownloadAll": "Stiahnuť všetky",+ "syncAssetDownloadOnDemand": "Sťahovať na požiadanie",+ "syncAssetDownloadModeUpdating": "Aktualizuje sa režim sťahovania zdrojových súborov...",+ "syncAssetDownloadModeFailed": "Režim sťahovania zdrojových súborov sa nedá aktualizovať","globalDefaultFont": "Globálne predvolené písmo","globalDefaultFontTip": "Používa sa pre rozhranie a obsah bez samostatného nastavenia písma; bez výberu sa použije predvolené písmo témy","mobileMultiSelectTip": "Ťuknutím na bloky ich vyberiete alebo zrušíte ich výber",@@ -2696,6 +2703,8 @@"372": "Zápisník bol obnovený a zostáva zatvorený","373": "Tento archív obsahuje údaje zápisníka. Importujte ho cez [Strom dokumentov - Viac - Importovať zápisník]","374": "Databáza [%s], pole šablóny [%s], prvá ovplyvnená položka [%s] (ID položky: %s), počet ovplyvnených položiek: %d, chyba: %s",- "375": "Zápisník na ukladanie rýchlych poznámok nie je k dispozícii. Vyberte otvorený nezašifrovaný zápisník v Nastavenia - Dokument"+ "375": "Zápisník na ukladanie rýchlych poznámok nie je k dispozícii. Vyberte otvorený nezašifrovaný zápisník v Nastavenia - Dokument",+ "376": "Zdrojový súbor ešte nebol stiahnutý a momentálne ho nemožno získať",+ "377": "Pred zmenou alebo obnovením dátového úložiska prepnite na Stiahnuť všetky"}}diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex f31845b8bd..35075818ad 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "เนื้อหาทรัพยากรบางส่วนขึ้นอยู่กับที่เก็บข้อมูลบนคลาวด์ สแนปช็อตในเครื่องนี้จึงยังไม่สมบูรณ์",+ "syncAssetDownloadMode": "การดาวน์โหลดไฟล์ทรัพยากร",+ "syncAssetDownloadModeTip": "ใช้กับอุปกรณ์นี้เท่านั้น โหมดดาวน์โหลดตามต้องการจะดาวน์โหลดทรัพยากรเมื่อใช้งาน และจะใช้งานแบบออฟไลน์ไม่ได้จนกว่าจะดาวน์โหลด ทรัพยากรที่ดาวน์โหลดแล้วจะถูกเก็บไว้และอัปเดตระหว่างการซิงค์ การเปลี่ยนเป็นดาวน์โหลดทั้งหมดจะดาวน์โหลดทรัพยากรที่ขาดหายไปก่อน",+ "syncAssetDownloadAll": "ดาวน์โหลดทั้งหมด",+ "syncAssetDownloadOnDemand": "ดาวน์โหลดตามต้องการ",+ "syncAssetDownloadModeUpdating": "กำลังอัปเดตโหมดดาวน์โหลดทรัพยากร...",+ "syncAssetDownloadModeFailed": "ไม่สามารถอัปเดตโหมดดาวน์โหลดทรัพยากรได้","globalDefaultFont": "แบบอักษรเริ่มต้นส่วนกลาง","globalDefaultFontTip": "ใช้กับส่วนติดต่อและเนื้อหาที่ไม่ได้ตั้งค่าแบบอักษรแยกไว้ หากไม่เลือกแบบอักษรจะใช้แบบอักษรเริ่มต้นของธีม","mobileMultiSelectTip": "แตะบล็อกเพื่อเลือกหรือยกเลิกการเลือก",@@ -2696,6 +2703,8 @@"372": "กู้คืนสมุดแล้วและยังคงปิดอยู่","373": "ไฟล์บีบอัดนี้มีข้อมูลสมุดบันทึก โปรดนำเข้าจาก [แผนผังเอกสาร - เพิ่มเติม - นำเข้าสมุดบันทึก]","374": "ฐานข้อมูล [%s] ฟิลด์เทมเพลต [%s] รายการแรกที่ได้รับผลกระทบ [%s] (ID รายการ: %s) จำนวนรายการที่ได้รับผลกระทบ: %d ข้อผิดพลาด: %s",- "375": "สมุดบันทึกสำหรับบันทึกโน้ตด่วนไม่พร้อมใช้งาน โปรดเลือกสมุดบันทึกที่เปิดอยู่และไม่ได้เข้ารหัสใน การตั้งค่า - เอกสาร"+ "375": "สมุดบันทึกสำหรับบันทึกโน้ตด่วนไม่พร้อมใช้งาน โปรดเลือกสมุดบันทึกที่เปิดอยู่และไม่ได้เข้ารหัสใน การตั้งค่า - เอกสาร",+ "376": "ยังไม่ได้ดาวน์โหลดทรัพยากรและไม่สามารถดึงข้อมูลได้ในขณะนี้",+ "377": "โปรดเปลี่ยนเป็นดาวน์โหลดทั้งหมดก่อนเปลี่ยนหรือรีเซ็ตคลังข้อมูล"}}diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 228e06ba6c..b8e25ca11c 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Bazı kaynakların içeriği bulut depolamaya bağlıdır; bu yerel anlık görüntü eksiktir",+ "syncAssetDownloadMode": "Kaynak dosyası indirmeleri",+ "syncAssetDownloadModeTip": "Yalnızca bu cihaz için geçerlidir. İsteğe bağlı kaynaklar kullanıldıklarında indirilir ve indirilene kadar çevrimdışı kullanılamaz. İndirilen kaynaklar saklanır ve eşitleme sırasında güncellenir. Tümünü indir seçeneğine geçmeden önce eksik kaynaklar indirilir",+ "syncAssetDownloadAll": "Tümünü indir",+ "syncAssetDownloadOnDemand": "Gerektiğinde indir",+ "syncAssetDownloadModeUpdating": "Kaynak indirme modu güncelleniyor...",+ "syncAssetDownloadModeFailed": "Kaynak indirme modu güncellenemedi","globalDefaultFont": "Genel Varsayılan Yazı Tipi","globalDefaultFontTip": "Arayüz ve ayrı bir yazı tipi ayarı olmayan içerik için kullanılır; temanın varsayılan yazı tipini kullanmak için seçimi boş bırakın","mobileMultiSelectTip": "Blokları seçmek veya seçimlerini kaldırmak için dokunun",@@ -2696,6 +2703,8 @@"372": "Defter geri yüklendi ve kapalı kalacak","373": "Bu arşiv not defteri verileri içeriyor. [Belge ağacı - Diğer - Not defteri içe aktar] menüsünden içe aktarın","374": "Veritabanı [%s], şablon alanı [%s], etkilenen ilk öğe [%s] (öğe kimliği: %s), etkilenen öğe sayısı: %d, hata: %s",- "375": "Hızlı notların kaydedileceği not defteri kullanılamıyor. Ayarlar - Belge bölümünde açık ve şifrelenmemiş bir not defteri seçin"+ "375": "Hızlı notların kaydedileceği not defteri kullanılamıyor. Ayarlar - Belge bölümünde açık ve şifrelenmemiş bir not defteri seçin",+ "376": "Kaynak henüz indirilmedi ve şu anda alınamıyor",+ "377": "Veri deposunu değiştirmeden veya sıfırlamadan önce Tümünü indir seçeneğine geçin"}}diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex c52ac36081..683d42233d 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "Вміст деяких ресурсів залежить від хмарного сховища; цей локальний знімок неповний",+ "syncAssetDownloadMode": "Завантаження файлів ресурсів",+ "syncAssetDownloadModeTip": "Застосовується лише до цього пристрою. Ресурси на вимогу завантажуються під час використання й до завантаження недоступні без мережі. Завантажені ресурси зберігаються й оновлюються під час синхронізації. Під час переходу до Завантажити всі спочатку завантажуються відсутні ресурси",+ "syncAssetDownloadAll": "Завантажити всі",+ "syncAssetDownloadOnDemand": "Завантажувати на вимогу",+ "syncAssetDownloadModeUpdating": "Оновлення режиму завантаження ресурсів...",+ "syncAssetDownloadModeFailed": "Не вдалося оновити режим завантаження ресурсів","globalDefaultFont": "Глобальний типовий шрифт","globalDefaultFontTip": "Використовується для інтерфейсу та вмісту без окремого налаштування шрифту; якщо нічого не вибрано, використовується типовий шрифт теми","mobileMultiSelectTip": "Торкайтеся блоків, щоб вибрати їх або скасувати вибір",@@ -2696,6 +2703,8 @@"372": "Блокнот відновлено й залишено закритим","373": "Цей архів містить дані блокнота. Імпортуйте його через [Дерево документів - Більше - Імпортувати блокнот]","374": "База даних [%s], поле шаблону [%s], перший уражений елемент [%s] (ID елемента: %s), кількість уражених елементів: %d, помилка: %s",- "375": "Блокнот для збереження швидких нотаток недоступний. Виберіть відкритий незашифрований блокнот у Налаштування - Документ"+ "375": "Блокнот для збереження швидких нотаток недоступний. Виберіть відкритий незашифрований блокнот у Налаштування - Документ",+ "376": "Ресурс ще не завантажено, і зараз його неможливо отримати",+ "377": "Перейдіть до Завантажити всі перед зміною або скиданням сховища даних"}}diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex d0ec2f7f92..ba40c55ee4 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "部分资源文件内容依赖云端,本地快照尚不完整",+ "syncAssetDownloadMode": "资源文件下载",+ "syncAssetDownloadModeTip": "仅作用于当前设备;按需模式在使用资源文件时下载,未下载的资源文件离线不可用;已下载资源文件会保留并随同步更新;切换为全部下载前会先补齐缺失内容",+ "syncAssetDownloadAll": "全部下载",+ "syncAssetDownloadOnDemand": "按需下载",+ "syncAssetDownloadModeUpdating": "正在更新资源文件下载模式...",+ "syncAssetDownloadModeFailed": "无法更新资源文件下载模式","globalDefaultFont": "全局默认字体","globalDefaultFontTip": "用于界面和未单独设置字体的内容,不选择任何字体时使用主题默认字体","mobileMultiSelectTip": "轻点块以选中或取消选中",@@ -2696,6 +2703,8 @@"372": "笔记本已回滚并保持关闭状态","373": "该压缩包包含笔记本数据,请从 [文档树 - 更多 - 导入笔记本] 中导入","374": "数据库 [%s],模板字段 [%s],首个出错条目 [%s](项目 ID:%s),出错条目数:%d,错误:%s",- "375": "闪念速记存放笔记本不可用,请在设置 - 文档中选择一个已打开的非加密笔记本"+ "375": "闪念速记存放笔记本不可用,请在设置 - 文档中选择一个已打开的非加密笔记本",+ "376": "资源文件尚未下载,当前无法获取",+ "377": "请先切换为全部下载,再更换或重置数据仓库"}}diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex bd0dd14f1b..ec2e180af2 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,11 @@{+ "syncAssetSnapshotIncomplete": "部分資源檔案內容依賴雲端,本機快照尚不完整",+ "syncAssetDownloadMode": "資源檔案下載",+ "syncAssetDownloadModeTip": "僅套用於目前裝置;按需模式會在使用資源檔案時下載,尚未下載的資源檔案無法離線使用;已下載的資源檔案會保留並隨同步更新;切換為全部下載前會先補齊缺少的內容",+ "syncAssetDownloadAll": "全部下載",+ "syncAssetDownloadOnDemand": "按需下載",+ "syncAssetDownloadModeUpdating": "正在更新資源檔案下載模式...",+ "syncAssetDownloadModeFailed": "無法更新資源檔案下載模式","globalDefaultFont": "全域預設字型","globalDefaultFontTip": "用於介面和未個別設定字型的內容,未選擇任何字型時使用佈景主題的預設字型","mobileMultiSelectTip": "輕點區塊以選取或取消選取",@@ -2696,6 +2703,8 @@"372": "筆記本已回滾並保持關閉狀態","373": "該壓縮檔包含筆記本資料,請從 [文件樹 - 更多 - 導入筆記本] 中導入","374": "資料庫 [%s],範本欄位 [%s],第一個出錯項目 [%s](項目 ID:%s),出錯項目數:%d,錯誤:%s",- "375": "閃念速記存放筆記本不可用,請在設定 - 文件中選擇一個已開啟的非加密筆記本"+ "375": "閃念速記存放筆記本不可用,請在設定 - 文件中選擇一個已開啟的非加密筆記本",+ "376": "資源檔案尚未下載,目前無法取得",+ "377": "請先切換為全部下載,再更換或重設資料倉庫"}}diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.syindex 26b9eeb4fd..989fca1995 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy@@ -6,7 +6,7 @@"id": "20210721112206-mhr9wxi","title": "Data sync","type": "doc",- "updated": "20260803171606"+ "updated": "20260905191024"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20210721112403-8no39l4",- "updated": "20250218121000"+ "updated": "20260905184908"},"Children": [{@@ -29,7 +29,7 @@"Type": "NodeParagraph","Properties": {"id": "20210721112403-0ft3r91",- "updated": "20250218121000"+ "updated": "20260905184908"},"Children": [{@@ -43,7 +43,133 @@},{"Type": "NodeText",- "Data": " folder data consistent on multiple devices, includes assets, custom icons, plugins, code snippets, templates, widgets, and document data."+ "Data": " folder logically consistent across devices, including assets, custom icons, plugins, code snippets, templates, widgets, and document data. With on-demand downloads, some asset content may not yet be stored on this device."+ }+ ]+ },+ {+ "ID": "20260905184908-022q2es",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260905184908-022q2es",+ "updated": "20260905191024"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Asset downloads"+ }+ ]+ },+ {+ "ID": "20260905184908-jpha7l7",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-jpha7l7",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Choose Download all or Download on demand in "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Settings"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Account & Sync"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Asset downloads"+ },+ {+ "Type": "NodeText",+ "Data": ". This setting applies only to the current device."+ }+ ]+ },+ {+ "ID": "20260905184908-5jlxwbn",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-5jlxwbn",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Download all is the default. On-demand mode still fully syncs documents, database definitions, and the asset list. Required assets are downloaded when displaying images, audio, video, PDFs, or other content, or when opening asset links. Encrypted notebook assets still require the notebook to be unlocked."+ }+ ]+ },+ {+ "ID": "20260905184908-2t2p88b",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-2t2p88b",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Downloaded assets remain on this device and continue to receive updates during subsequent syncs. Enabling on-demand downloads does not remove existing files or immediately free their storage space."+ }+ ]+ },+ {+ "ID": "20260905184908-bb2w63n",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-bb2w63n",+ "updated": "20260905191024"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Assets that have not been downloaded are unavailable offline, and an error is reported if they cannot be retrieved. Switching to Download all first downloads the content needed by current assets and all retained local snapshots, which may include historical versions. If downloading fails, the previous mode is retained; reconnect and try again."+ }+ ]+ },+ {+ "ID": "20260905184908-yzvkosv",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-yzvkosv",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Local snapshots in on-demand mode may depend on cloud storage and must not be treated as complete offline backups. Downloading a complete snapshot, and exports or recovery operations that need asset content, first download the required assets and report an error if they cannot be retrieved."+ }+ ]+ },+ {+ "ID": "20260905184908-1wxzlh9",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-1wxzlh9",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Before changing the sync target, resetting the data repository, or opening this workspace with an older version, switch to Download all and finish downloading to preserve access to assets that are not yet stored locally."}]},@@ -1431,4 +1557,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.syindex d3b712587e..673270f509 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy@@ -6,7 +6,7 @@"id": "20230808120347-3cob0nb","title": "数据同步","type": "doc",- "updated": "20260803163440"+ "updated": "20260905191024"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20230808120347-wx5cr4v",- "updated": "20250218120940"+ "updated": "20260905184908"},"Children": [{@@ -29,7 +29,7 @@"Type": "NodeParagraph","Properties": {"id": "20230808120347-q4v034g",- "updated": "20250218120940"+ "updated": "20260905184908"},"Children": [{@@ -43,7 +43,133 @@},{"Type": "NodeText",- "Data": " 文件夹数据一致,包括资源文件、自定义图标、插件、代码片段、模板、挂件和文档数据。"+ "Data": " 文件夹中的数据在逻辑上保持一致,包括资源文件、自定义图标、插件、代码片段、模板、挂件和文档数据。按需下载模式允许资源文件的内容暂不保存到本机。"+ }+ ]+ },+ {+ "ID": "20260905184908-5o1vhpi",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260905184908-5o1vhpi",+ "updated": "20260905191024"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "资源文件下载"+ }+ ]+ },+ {+ "ID": "20260905184908-hlr159c",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-hlr159c",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "可在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "设置"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "账号与同步"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "资源文件下载"+ },+ {+ "Type": "NodeText",+ "Data": " 中选择全部下载或按需下载,设置仅作用于当前设备。"+ }+ ]+ },+ {+ "ID": "20260905184908-9m2nksl",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-9m2nksl",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "全部下载是默认模式。按需下载仍会完整同步文档、数据库定义和资源文件清单,在展示图片、音视频、PDF 等内容或打开资源链接时下载所需资源文件。加密笔记本资源仍需解锁后访问。"+ }+ ]+ },+ {+ "ID": "20260905184908-88bc5es",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-88bc5es",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "已下载的资源文件会保留在本机,并在后续同步时继续更新。启用按需下载不会清理已有文件,也不会立即释放已有占用。"+ }+ ]+ },+ {+ "ID": "20260905184908-k9wkzqk",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-k9wkzqk",+ "updated": "20260905191024"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "未下载的资源文件离线不可用,无法获取时会报错。切换为全部下载会先补齐当前资源文件及所有保留的本地快照所需内容,因此也可能下载历史版本;下载失败时保留原模式,可以恢复连接后重试。"+ }+ ]+ },+ {+ "ID": "20260905184908-cv88hsn",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-cv88hsn",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "按需模式的本地快照可能依赖云端,不能视为完整离线备份。完整快照下载,以及需要资源文件内容的导出和恢复操作,会先补齐对应资源文件,无法取得时明确报错。"+ }+ ]+ },+ {+ "ID": "20260905184908-84gaare",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-84gaare",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "更换同步目标、重置数据仓库或使用旧版本打开此工作空间前,请先切换为全部下载并完成下载,避免失去未下载资源文件的获取途径。"}]},@@ -1426,4 +1552,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.syindex 1e8e3913b6..64ab5b3b46 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy@@ -6,7 +6,7 @@"id": "20211226121438-xaafdo8","title": "資料同步","type": "doc",- "updated": "20260803163402"+ "updated": "20260905191024"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226121454-8vr6fgn",- "updated": "20250218121017"+ "updated": "20260905184908"},"Children": [{@@ -29,7 +29,7 @@"Type": "NodeParagraph","Properties": {"id": "20211226121454-2wnvrmj",- "updated": "20250218121017"+ "updated": "20260905184908"},"Children": [{@@ -43,7 +43,133 @@},{"Type": "NodeText",- "Data": " 文件夾資料一致,包括資源檔案、自訂圖示、外掛程式、程式碼片段、範本、掛件和文件資料。"+ "Data": " 資料夾中的資料在邏輯上保持一致,包括資源檔案、自訂圖示、外掛程式、程式碼片段、範本、掛件和文件資料。按需下載模式允許資源檔案的內容暫不儲存於本機。"+ }+ ]+ },+ {+ "ID": "20260905184908-43b5is5",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260905184908-43b5is5",+ "updated": "20260905191024"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "資源檔案下載"+ }+ ]+ },+ {+ "ID": "20260905184908-r2oumjv",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-r2oumjv",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "可在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "帳號與同步"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "資源檔案下載"+ },+ {+ "Type": "NodeText",+ "Data": " 中選擇全部下載或按需下載,設定僅套用於目前裝置。"+ }+ ]+ },+ {+ "ID": "20260905184908-ydno2ri",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-ydno2ri",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "全部下載是預設模式。按需下載仍會完整同步文件、資料庫定義和資源檔案清單,在顯示圖片、音訊、影片、PDF 等內容或開啟資源連結時下載所需資源檔案。加密筆記本資源仍需解鎖後存取。"+ }+ ]+ },+ {+ "ID": "20260905184908-u69286b",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-u69286b",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "已下載的資源檔案會保留於本機,並在後續同步時繼續更新。啟用按需下載不會清理現有檔案,也不會立即釋放已佔用的空間。"+ }+ ]+ },+ {+ "ID": "20260905184908-nspliig",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-nspliig",+ "updated": "20260905191024"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "尚未下載的資源檔案無法離線使用,無法取得時會回報錯誤。切換為全部下載會先補齊目前資源檔案及所有保留的本機快照所需內容,因此也可能下載歷史版本;下載失敗時保留原模式,可以恢復連線後重試。"+ }+ ]+ },+ {+ "ID": "20260905184908-ihj48vx",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-ihj48vx",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "按需模式的本機快照可能依賴雲端,不能視為完整離線備份。完整快照下載,以及需要資源檔案內容的匯出和復原操作,會先補齊對應資源檔案,無法取得時明確回報錯誤。"+ }+ ]+ },+ {+ "ID": "20260905184908-qskt7h0",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-qskt7h0",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "更換同步目標、重設資料倉庫或使用舊版本開啟此工作空間前,請先切換為全部下載並完成下載,避免失去取得尚未下載資源檔案的途徑。"}]},@@ -1435,4 +1561,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.syindex 98360d245a..bfe755085b 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy@@ -7,7 +7,7 @@"id": "20240530101000-wo49zvq","title": "データ同期","type": "doc",- "updated": "20260803170332"+ "updated": "20260905191024"},"Children": [{@@ -17,7 +17,7 @@"Properties": {"ID": "20240530101000-otrm2qw","id": "20240530101000-qw5ujp4",- "updated": "20250218121028"+ "updated": "20260905184908"},"Children": [{@@ -31,7 +31,7 @@"Type": "NodeParagraph","Properties": {"id": "20240530101000-6vtiz1y",- "updated": "20250218121028"+ "updated": "20260905184908"},"Children": [{@@ -45,7 +45,133 @@},{"Type": "NodeText",- "Data": " フォルダのデータを一致させることです。リソース ファイル、カスタム アイコン、プラグイン、コード スニペット、テンプレート、ウィジェット、ドキュメント データが含まれます。"+ "Data": " フォルダのデータを論理的に一致させることです。リソースファイル、カスタムアイコン、プラグイン、コードスニペット、テンプレート、ウィジェット、ドキュメントデータが含まれます。必要時にダウンロードするモードでは、一部のリソースファイルの内容が端末にまだ保存されていない場合があります。"+ }+ ]+ },+ {+ "ID": "20260905184908-ntlbfyd",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260905184908-ntlbfyd",+ "updated": "20260905191024"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "リソースファイルのダウンロード"+ }+ ]+ },+ {+ "ID": "20260905184908-civg0pm",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-civg0pm",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "ダウンロード方法は "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "アカウントと同期"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "リソースファイルのダウンロード"+ },+ {+ "Type": "NodeText",+ "Data": " で、すべてダウンロードと必要時にダウンロードから選択できます。この設定は現在の端末にのみ適用されます。"+ }+ ]+ },+ {+ "ID": "20260905184908-8ks0rt1",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-8ks0rt1",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "既定のモードはすべてダウンロードです。必要時にダウンロードするモードでも、ドキュメント、データベース定義、リソースファイルの一覧は完全に同期されます。画像、音声、動画、PDF などの表示時やリソースへのリンクを開く際に、必要なファイルがダウンロードされます。暗号化ノートブックのリソースにアクセスするには、引き続きロック解除が必要です。"+ }+ ]+ },+ {+ "ID": "20260905184908-hudbk6s",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-hudbk6s",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "ダウンロード済みのリソースファイルは端末に保持され、その後の同期時にも更新されます。必要時にダウンロードするモードを有効にしても、既存のファイルは削除されず、使用中の容量がすぐに解放されることはありません。"+ }+ ]+ },+ {+ "ID": "20260905184908-yksntn7",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-yksntn7",+ "updated": "20260905191024"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "未ダウンロードのリソースファイルはオフラインでは利用できず、取得できない場合はエラーが表示されます。すべてダウンロードに切り替える際は、現在のリソースファイルと保存されているすべてのローカルスナップショットに必要な内容が先にダウンロードされるため、履歴バージョンも対象になる場合があります。失敗した場合は元のモードが維持されるため、接続を回復してから再試行してください。"+ }+ ]+ },+ {+ "ID": "20260905184908-3g7irb7",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-3g7irb7",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "必要時にダウンロードするモードのローカルスナップショットはクラウドに依存する場合があり、完全なオフラインバックアップとして扱うことはできません。完全なスナップショットのダウンロード、およびリソースファイルの内容を必要とするエクスポートや復元では、必要なファイルを先にダウンロードし、取得できない場合はエラーを報告します。"+ }+ ]+ },+ {+ "ID": "20260905184908-qdp3vo4",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260905184908-qdp3vo4",+ "updated": "20260905184908"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "同期先の変更、データリポジトリのリセット、または古いバージョンでこのワークスペースを開く前に、すべてダウンロードに切り替えてダウンロードを完了し、端末に未保存のリソースファイルを取得できる状態を確保してください。"}]},@@ -1562,4 +1688,4 @@}}]-}\ No newline at end of file+}diff --git a/app/src/config/tabs/syncRuntime.ts b/app/src/config/tabs/syncRuntime.tsindex e96bd791ad..6a2586642c 100644--- a/app/src/config/tabs/syncRuntime.ts+++ b/app/src/config/tabs/syncRuntime.ts@@ -1,6 +1,7 @@import {fetchPost, fetchSyncPost} from "../../util/fetch";import {processSync} from "../../dialog/processSystem";import {updateAccountPanelVisibility} from "./accountUi";+import {showMessage} from "../../dialog/message";import {refreshLANSyncConfigItemVisibility,refreshSyncModeRelatedItems,@@ -10,6 +11,43 @@ import {/** 账号同步 Tab 根节点 */export let syncTabElement: HTMLElement | undefined;+let syncAssetDownloadModePending = false;++/** 切换资源下载模式时显示进度,并阻止重复提交。 */+export const mountSyncAssetDownloadMode = (root: ParentNode) => {+ root.querySelectorAll<HTMLSelectElement>('[id="sync.assetDownloadMode"]').forEach((element) => {+ element.disabled = syncAssetDownloadModePending || window.siyuan.config.readonly;+ element.setAttribute("aria-busy", String(syncAssetDownloadModePending));+ if (!syncAssetDownloadModePending) {+ element.value = String(window.siyuan.config.sync.assetDownloadMode ?? 0);+ }+ });+ root.querySelectorAll<HTMLElement>('[data-type="syncAssetDownloadStatus"]').forEach((element) => {+ element.textContent = syncAssetDownloadModePending ? window.siyuan.languages.syncAssetDownloadModeUpdating : "";+ });+};++const setSyncAssetDownloadMode = async (mode: Config.ISync["assetDownloadMode"]) => {+ if (syncAssetDownloadModePending || (mode !== 0 && mode !== 1)) {+ mountSyncAssetDownloadMode(document);+ return;+ }+ syncAssetDownloadModePending = true;+ mountSyncAssetDownloadMode(document);+ try {+ const response = await fetchSyncPost("/api/sync/setSyncAssetDownloadMode", {mode});+ if (response.code === 0) {+ window.siyuan.config.sync.assetDownloadMode = response.data.assetDownloadMode;+ }+ } catch (error) {+ console.warn("[config] failed to update asset download mode", error);+ showMessage(window.siyuan.languages.syncAssetDownloadModeFailed, 5000, "error");+ } finally {+ syncAssetDownloadModePending = false;+ mountSyncAssetDownloadMode(document);+ }+};+/** 释放 Tab 根节点引用;传入 root 时仅释放对应挂载,避免影响其他设置入口 */export const clearSyncTabElement = (root?: HTMLElement) => {if (!root || syncTabElement === root) {@@ -116,6 +154,9 @@ export const patchSyncConfig = (controlId: string, value: unknown) => {});break;}+ case "sync.assetDownloadMode": {+ return setSyncAssetDownloadMode(value as Config.ISync["assetDownloadMode"]);+ }case "sync.interval": {const interval = value as Config.ISync["interval"];fetchPost("/api/sync/setSyncInterval", {interval}, () => {diff --git a/app/src/config/tabs/syncTab.ts b/app/src/config/tabs/syncTab.tsindex 30c58e8f87..10dfe444a2 100644--- a/app/src/config/tabs/syncTab.ts+++ b/app/src/config/tabs/syncTab.ts@@ -10,7 +10,7 @@ import {bindSyncCloudListEvent, renderSyncCloudList, setKey} from "../../sync/syimport {Dialog} from "../../dialog";import {genConfigItemMainHtml, genConfigItemName} from "../render/fragments";import {getLANSyncSearchAvailability, getSyncProviderConfigKeywords} from "./syncUi";-import {mountLANSyncStatus, patchSyncConfig} from "./syncRuntime";+import {mountLANSyncStatus, mountSyncAssetDownloadMode, patchSyncConfig} from "./syncRuntime";import {openHistory} from "../../history/history";const registerSyncGroup = (tab: SettingTabBuilder) => {@@ -57,6 +57,16 @@ const registerSyncGroup = (tab: SettingTabBuilder) => {],save: (value) => patchSyncConfig("sync.mode", value),});+ group.select("sync.assetDownloadMode", {+ title: window.siyuan.languages.syncAssetDownloadMode,+ desc: `${window.siyuan.languages.syncAssetDownloadModeTip}<div data-type="syncAssetDownloadStatus" role="status"></div>`,+ options: [+ {value: 0, label: window.siyuan.languages.syncAssetDownloadAll},+ {value: 1, label: window.siyuan.languages.syncAssetDownloadOnDemand},+ ],+ save: (value) => patchSyncConfig("sync.assetDownloadMode", value),+ afterMount: mountSyncAssetDownloadMode,+ });group.number("sync.interval", {title: window.siyuan.languages.syncInterval,desc: window.siyuan.languages.syncIntervalTip,diff --git a/app/src/config/tabs/syncUi.ts b/app/src/config/tabs/syncUi.tsindex 5aad6b1db6..69bebd16e5 100644--- a/app/src/config/tabs/syncUi.ts+++ b/app/src/config/tabs/syncUi.ts@@ -45,6 +45,7 @@ const setSyncConfigItemVisible = (root: Element) => {"sync.enabled","sync.generateConflictDoc","sync.mode",+ "sync.assetDownloadMode","sync.interval","sync.perception","sync.lan.enabled",diff --git a/app/src/history/history.ts b/app/src/history/history.tsindex b9c8a3e958..7f5629ee20 100644--- a/app/src/history/history.ts+++ b/app/src/history/history.ts@@ -218,6 +218,7 @@ const renderRepoItem = (response: IWebSocketData, element: Element, type: stringsystemName: string,systemOS: string,tag: string,+ requiresDownload?: boolean,typesCount: { type: string, count: number }[]}) => {let statHTML = "";@@ -238,6 +239,8 @@ ${window.siyuan.languages.fileCount} ${item.count}<span class="fn__space"></span<span class="fn__space"></span><span class="b3-chip b3-chip--secondary b3-chip--small${item.tag ? "" : " fn__none"}">${item.tag}</span></div>+${item.requiresDownload && ["getRepoTagSnapshots", "getRepoSnapshots"].includes(type) ?+ `<div class="ft__smaller ft__error" style="white-space:normal">${escapeHtml(window.siyuan.languages.syncAssetSnapshotIncomplete)}</div>` : ""}<div class="b3-list-item__meta${isPhone ? " fn__none" : ""}">${escapeHtml(item.memo)}<span class="fn__space"></span>diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 6e54311f43..cf04b30280 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -1803,6 +1803,10 @@ declare namespace Config {* Whether to create a conflict document when a conflict occurs during synchronization*/generateConflictDoc: boolean;+ /**+ * 当前设备的资源下载模式,0:全部下载,1:按需下载。+ */+ assetDownloadMode: 0 | 1;/*** Synchronization mode* - `0`: Not setdiff --git a/docs/ASSET-DOWNLOAD.md b/docs/ASSET-DOWNLOAD.mdnew file mode 100644index 0000000000..13160d6f2b--- /dev/null+++ b/docs/ASSET-DOWNLOAD.md@@ -0,0 +1,45 @@+# 资源文件按需下载++对应需求:https://github.com/siyuan-note/siyuan/issues/19149++## 功能边界++`sync.assetDownloadMode` 是设备配置,`0` 为全部下载,`1` 为按需下载,默认值为 `0`。桌面端和移动端共用设置及内核实现,适用于官方云、S3、WebDAV 和本地文件系统同步。++按需模式始终同步完整文件元数据以及文档、数据库、配置、密钥等非资源内容。资源目录中的 `ocr-texts.json`、PDF 批注 `.sya` 文件和隐藏辅助文件也保持完整同步。没有自动清理已下载资源的策略;在已有完整数据的设备上启用按需模式,不会立即减少磁盘占用。++首次访问未下载资源时,先复用本地仓库已有的分块,再按需下载缺少的分块。下载成功后,该资源在后续同步中继续更新。已有本地内容不依赖联网、账号登录或同步开关。需要访问云端时沿用数据同步的账号及服务权限。++## 逻辑数据与本地内容++`dejavu` 在工作空间的 `conf/asset-downloads.json` 中保存经过仓库密钥认证加密的设备状态,包含显式版本、来源标识、未下载资源的完整文件版本,以及未完成应用操作的恢复日志。状态不参与数据同步。仓库中的 `asset-downloads-v1` 标记用于检测当前实现遗漏配置或丢失状态;状态丢失、未知版本或认证失败均返回错误并保留原始材料。++未下载资源仍属于当前数据和快照的逻辑文件清单。索引不能将其本地缺席解释为删除,同步不能上传尚未下载的旧版本分块。已经物化的文件由普通索引继续跟踪;资源删除、改名和移动入口先补齐相关内容,再执行原有文件操作。++修改同步忽略规则时,先补齐新被忽略的未下载资源,再停止跟踪,保留本地内容和历史分块;无法获取内容时保留原状态并报错。仅上传模式只补齐实际上传候选所需的分块,不将未访问的资源物化到工作区。++同步合并采用可恢复的应用日志,记录目标资源清单、变更前版本和云端基线。应用前检查本地文件是否仍符合预期,保留下载期间的本地额外修改。中断后可重试,只有文件及引用更新完成后才清除日志。来源切换与资源物化串行化,仓库内部操作共享原有互斥锁,并重新读取已认证的设备状态,避免旧实例覆盖新状态。++## 读取、导出与加密++内部逻辑路径解析、资源搜索、缺失检查和文件大小查询只读取逻辑元数据,不触发下载。实际显示图片、播放音视频、打开 PDF、访问资源链接、复制资源或导出时才补齐内容。用于为外部打开准备实际文件路径的 `/api/asset/resolveAssetPath` 也会先补齐资源。HTTP 和原始文件 API 先完成路径、符号链接、发布权限及加密笔记本权限检查,再执行下载。++导出在持有笔记本读锁和创建产物之前预取引用资源,范围包含子文档、关联文档、查询嵌入、题头图、数据库及关联数据库中的资源。目录资源根据逻辑清单补齐,不能只依靠磁盘遍历。下载或复制失败向上传播,不将缺少资源的产物报告为成功。++加密资源下载后仍保持原始密文,读取和导出继续由现有认证解密流程处理,兼容已发布的资源格式。不改变密钥信封、主盐、AAD 或密钥派生,不通过明文回退处理认证错误。读取和明文导出前检查笔记本准入,不在持有笔记本读锁期间等待网络。锁定笔记本的资源读取请求和仅枚举文件名不会触发下载;完整同步、密文备份及删除前保存历史可以补齐原始密文。++## 快照与来源变更++按需设备的本地快照可能只有部分资源内容,界面通过 `requiresDownload` 独立提示。读取历史资源按该快照的精确文件版本补齐分块,不覆盖工作区当前资源。完整云端快照下载检查所有目标文件的分块,即使其元数据已经存在也不跳过检查;失败时不创建成功标签。++恢复快照前,先补齐当前工作区和目标快照所需的资源。切回全部下载时,同时补齐当前资源和所有保留快照缺少的历史内容;失败则保留原设置。切换同步来源、云端清理、删除当前云目录及重置仓库或密钥前检查这些依赖,未完成时保留原来源。重建仓库前,只有旧状态认证成功且依赖完整,才能清除设备状态和标记。++官方云登出允许保留原来源标识,以便本地索引和已下载快照继续使用,随后重新认证原账号。存在未完成依赖时,跨区登录、换账号和注销账号受完整性检查保护。++未补齐的历史快照仍依赖对应云端内容的保留。其他设备清理云端或外部删除云对象可能使历史版本无法下载,因此部分本地快照不等价于完整离线备份。需要离线备份或更换来源时,应先完成全部下载。旧版本客户端不了解设备状态标记,降级前也必须完成全部下载;标记不能阻止旧版本把未下载文件当作本地删除。++## 开发与验证++实现同时涉及 `siyuan`、`dejavu` 和 `petal`。内核调用新增的 `dejavu` 资源下载及快照完整性接口,发布时应先发布依赖并更新模块版本。本地开发可使用临时 `replace` 指向 `dejavu` 检出,该替换不能提交。++回归覆盖完整与按需设备互相同步、单向同步、重复索引、远端版本更新、并发物化、本地修改保护、应用中断恢复、状态认证失败、来源变更、历史快照补齐、目录资源导出和已有加密资源格式。前端执行 `pnpm run lint`,语言执行 `python scripts/check-lang-keys.py`;不通过构建前端产物或编译运行内核进行验证。diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex 498144c5cb..6f7efdfb0f 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -23,6 +23,7 @@ import ("os""path/filepath""strings"+ "time""github.com/88250/go-humanize""github.com/88250/gulu"@@ -67,6 +68,26 @@ func statAsset(c *gin.Context) {info, err := os.Stat(p)if err != nil {+ if os.IsNotExist(err) {+ files, readErr := model.DeferredSyncAssets()+ if readErr != nil {+ ret.Code = 1+ ret.Msg = readErr.Error()+ return+ }+ for _, file := range files {+ if filepath.Clean(p) != filepath.Join(util.DataDir, filepath.FromSlash(strings.TrimPrefix(file.Path, "/"))) {+ continue+ }+ updated := time.UnixMilli(file.Updated).Format("2006-01-02 15:04:05")+ ret.Data = map[string]any{+ "size": file.Size, "hSize": humanize.IBytesCustomCeil(uint64(file.Size), 2),+ "created": file.Updated, "hCreated": updated, "updated": file.Updated, "hUpdated": updated,+ "downloaded": false,+ }+ return+ }+ }ret.Code = 1return}@@ -175,12 +196,23 @@ func ocr(c *gin.Context) {path := arg["path"].(string)// 加密笔记本的资源不参与全局 OCR- if absPath, absErr := model.GetAssetAbsPathInBox(path, ""); absErr == nil && model.IsEncryptedAssetPath(absPath) {+ absPath, err := model.GetAssetAbsPathInBox(path, "")+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ if model.IsEncryptedAssetPath(absPath) {ret.Code = -1ret.Msg = "OCR is not supported for assets in encrypted notebooks"ret.Data = map[string]any{"closeTimeout": 3000}return}+ if err = model.EnsureAssetLocal(absPath); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }ocrJSON, err := util.OcrAsset(path)if nil != err {@@ -523,6 +555,12 @@ func resolveAssetPath(c *gin.Context) {ret.Data = map[string]any{"closeTimeout": 3000}return}+ if err = model.EnsureAssetPrefixLocal(p); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ ret.Data = map[string]any{"closeTimeout": 7000}+ return+ }ret.Data = preturn}diff --git a/kernel/api/asset_download_authorization_test.go b/kernel/api/asset_download_authorization_test.gonew file mode 100644index 0000000000..c161af9310--- /dev/null+++ b/kernel/api/asset_download_authorization_test.go@@ -0,0 +1,242 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package api++import (+ "bytes"+ "crypto/sha256"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/dejavu/cloud"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDeferredAssetAPIAuthorizationAndMetadata(t *testing.T) {+ gin.SetMode(gin.TestMode)+ originalConf := model.Conf+ originalWorkspace, originalData, originalRepo := util.WorkspaceDir, util.DataDir, util.RepoDir+ originalHistory, originalTemp, originalConfDir := util.HistoryDir, util.TempDir, util.ConfDir+ originalStatusBar := util.StatusBarCfg+ t.Cleanup(func() {+ model.Conf = originalConf+ util.WorkspaceDir, util.DataDir, util.RepoDir = originalWorkspace, originalData, originalRepo+ util.HistoryDir, util.TempDir, util.ConfDir = originalHistory, originalTemp, originalConfDir+ util.StatusBarCfg = originalStatusBar+ })+ base := t.TempDir()+ remote := filepath.Join(base, "cloud")+ key := []byte("0123456789abcdef0123456789abcdef")+ model.Conf = model.NewAppConf()+ model.Conf.Sync, model.Conf.Repo, model.Conf.System = conf.NewSync(), conf.NewRepo(), conf.NewSystem()+ model.Conf.Search, model.Conf.FileTree = conf.NewSearch(), conf.NewFileTree()+ model.Conf.Sync.Provider, model.Conf.Sync.CloudName, model.Conf.Sync.Enabled = conf.ProviderLocal, "main", true+ model.Conf.Sync.Local = &conf.Local{Endpoint: remote}+ model.Conf.Sync.AssetDownloadMode, model.Conf.Repo.Key = 1, key+ model.Conf.SetUser(&conf.User{UserId: "asset-api-test", UserSiYuanOneTimePayStatus: 1})+ util.StatusBarCfg = &util.StatusBar{MsgDataSyncDisabled: true}+ util.WorkspaceDir = filepath.Join(base, "partial")+ util.DataDir, util.RepoDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "repo")+ util.HistoryDir, util.TempDir = filepath.Join(util.WorkspaceDir, "history"), filepath.Join(util.WorkspaceDir, "temp")+ util.ConfDir = filepath.Join(util.WorkspaceDir, "conf")+ // 测试仓库使用内核的本地存储来源格式,以便验证获准请求能够实际补齐资源。+ identity, err := json.Marshal([]string{fmt.Sprint(conf.ProviderLocal), "main", fmt.Sprintf("%x", sha256.Sum256(key)), filepath.Clean(remote)})+ if err != nil {+ t.Fatal(err)+ }+ scope := fmt.Sprintf("%x", sha256.Sum256(identity))+ makeRepo := func(name string, onDemand bool) *dejavu.Repo {+ t.Helper()+ dir := filepath.Join(base, name)+ repoPath := filepath.Join(dir, "repo")+ backend := cloud.NewLocal(&cloud.BaseCloud{Conf: &cloud.Conf{Dir: "main", RepoPath: repoPath,+ AvailableSize: 1024 * 1024 * 1024, Local: &cloud.ConfLocal{Endpoint: remote}}})+ repo, createErr := dejavu.NewRepo(filepath.Join(dir, "data"), repoPath, filepath.Join(dir, "history"),+ filepath.Join(dir, "temp"), name, name, "windows", key, nil, backend)+ if createErr != nil {+ t.Fatal(createErr)+ }+ if createErr = os.MkdirAll(filepath.Join(dir, "data"), 0755); createErr != nil {+ t.Fatal(createErr)+ }+ if createErr = os.WriteFile(filepath.Join(dir, "data", "seed.txt"), []byte("seed"), 0644); createErr != nil {+ t.Fatal(createErr)+ }+ if _, createErr = repo.Index("seed", true, nil); createErr != nil {+ t.Fatal(createErr)+ }+ if createErr = repo.ConfigureAssetDownloads(onDemand, filepath.Join(dir, "conf", "asset-downloads.json"), scope); createErr != nil {+ t.Fatal(createErr)+ }+ return repo+ }+ full := makeRepo("full", false)+ const boxID = "20260905123456-abcdefg"+ boxConf := conf.NewBoxConf()+ boxConf.Encrypted = true+ boxConfData, err := json.Marshal(boxConf)+ if err != nil {+ t.Fatal(err)+ }+ files := map[string][]byte{+ "assets/plain.bin": []byte("asset bytes downloaded only after authorization"),+ boxID + "/assets/private.bin": []byte("locked ciphertext fixture"),+ boxID + "/.siyuan/conf.json": boxConfData,+ }+ for name, data := range files {+ absPath := filepath.Join(base, "full", "data", filepath.FromSlash(name))+ if err = os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(absPath, data, 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err = full.Index("assets", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = full.Sync(nil); err != nil {+ t.Fatal(err)+ }+ partial := makeRepo("partial", true)+ if _, _, err = partial.Sync(nil); err != nil {+ t.Fatal(err)+ }+ deferred, err := model.DeferredSyncAssets()+ if err != nil || len(deferred) != 2 {+ t.Fatalf("expected two deferred assets: %+v, %v", deferred, err)+ }+ statePath := filepath.Join(util.ConfDir, "asset-downloads.json")+ stateBefore, err := os.ReadFile(statePath)+ if err != nil {+ t.Fatal(err)+ }+ assertNoDownloads := func() {+ t.Helper()+ stateAfter, readErr := os.ReadFile(statePath)+ if readErr != nil || !bytes.Equal(stateBefore, stateAfter) {+ t.Fatalf("read-only or denied request changed download state: %v", readErr)+ }+ for _, file := range deferred {+ absPath := filepath.Join(util.DataDir, filepath.FromSlash(file.Path))+ if _, statErr := os.Stat(absPath); !os.IsNotExist(statErr) {+ t.Fatalf("read-only or denied request materialized %q: %v", file.Path, statErr)+ }+ for _, chunkID := range file.Chunks {+ if _, statErr := os.Stat(filepath.Join(util.RepoDir, "objects", chunkID[:2], chunkID[2:])); !os.IsNotExist(statErr) {+ t.Fatalf("read-only or denied request downloaded chunk %q: %v", chunkID, statErr)+ }+ }+ }+ }+ assertNoDownloads()+ request := func(role model.Role, endpoint string, args any) *httptest.ResponseRecorder {+ t.Helper()+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, role)+ c.Next()+ })+ ServeAPI(engine)+ body, marshalErr := json.Marshal(args)+ if marshalErr != nil {+ t.Fatal(marshalErr)+ }+ recorder := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, endpoint, bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, req)+ return recorder+ }+ t.Run("metadata", func(t *testing.T) {+ recorder := request(model.RoleAdministrator, "/api/asset/statAsset", map[string]string{"path": "assets/plain.bin"})+ response := struct {+ Code int `json:"code"`+ Data struct {+ Size int64 `json:"size"`+ Downloaded *bool `json:"downloaded"`+ } `json:"data"`+ }{}+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if recorder.Code != http.StatusOK || response.Code != 0 || response.Data.Size != int64(len(files["assets/plain.bin"])) ||+ response.Data.Downloaded == nil || *response.Data.Downloaded {+ t.Fatalf("unexpected deferred metadata: %s", recorder.Body.String())+ }+ assertNoDownloads()+ })+ for _, endpoint := range []string{"/api/asset/statAsset", "/api/asset/resolveAssetPath", "/api/clipboard/writeFilePath", "/api/file/copyFile"} {+ t.Run("reader"+endpoint, func(t *testing.T) {+ recorder := request(model.RoleReader, endpoint, map[string]string{"path": "assets/plain.bin", "src": "data/assets/plain.bin", "dest": "temp/copied.bin"})+ if recorder.Code != http.StatusForbidden {+ t.Fatalf("reader unexpectedly authorized: %d %s", recorder.Code, recorder.Body.String())+ }+ assertNoDownloads()+ })+ }+ for _, test := range []struct {+ name string+ role model.Role+ path string+ code int+ }{+ {"unpublished", model.RoleReader, "data/assets/plain.bin", http.StatusForbidden},+ {"encrypted", model.RoleAdministrator, "data/" + boxID + "/assets/private.bin", -3},+ } {+ t.Run(test.name, func(t *testing.T) {+ recorder := request(test.role, "/api/file/getFile", map[string]string{"path": test.path})+ response := struct {+ Code int `json:"code"`+ }{}+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if recorder.Code != http.StatusAccepted || response.Code != test.code {+ t.Fatalf("unexpected access denial: %d %s", recorder.Code, recorder.Body.String())+ }+ assertNoDownloads()+ })+ }+ t.Run("encrypted-descendant", func(t *testing.T) {+ recorder := request(model.RoleAdministrator, "/api/file/workspaceCopyFiles", map[string]any{+ "srcs": []string{"data"}, "destDir": "temp/export/copied",+ })+ response := struct {+ Code int `json:"code"`+ }{}+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if response.Code == 0 {+ t.Fatalf("raw directory copy accepted an encrypted notebook descendant: %s", recorder.Body.String())+ }+ if _, statErr := os.Stat(filepath.Join(util.TempDir, "export", "copied")); !os.IsNotExist(statErr) {+ t.Fatalf("denied directory copy created output: %v", statErr)+ }+ assertNoDownloads()+ })+ t.Run("authorized", func(t *testing.T) {+ recorder := request(model.RoleAdministrator, "/api/file/getFile", map[string]string{"path": "data/assets/plain.bin"})+ if recorder.Code != http.StatusOK || !bytes.Equal(recorder.Body.Bytes(), files["assets/plain.bin"]) {+ t.Fatalf("authorized request failed to retrieve content: %d %s", recorder.Code, recorder.Body.String())+ }+ model.Conf.Sync.Enabled = false+ model.Conf.SetUser(nil)+ recorder = request(model.RoleAdministrator, "/api/file/getFile", map[string]string{"path": "data/assets/plain.bin"})+ if recorder.Code != http.StatusOK || !bytes.Equal(recorder.Body.Bytes(), files["assets/plain.bin"]) {+ t.Fatalf("cached asset unavailable offline: %d %s", recorder.Code, recorder.Body.String())+ }+ })+}diff --git a/kernel/api/clipboard.go b/kernel/api/clipboard.goindex f9c2b0652d..e15409a75e 100644--- a/kernel/api/clipboard.go+++ b/kernel/api/clipboard.go@@ -87,6 +87,12 @@ func writeFilePath(c *gin.Context) {return}+ if err = model.EnsureAssetPrefixLocal(absPath); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ ret.Data = map[string]any{"closeTimeout": 7000}+ return+ }if err = util.WriteFilePaths([]string{absPath}); err != nil {logging.LogErrorf("write file path to clipboard failed: %s", err)ret.Code = -1diff --git a/kernel/api/file.go b/kernel/api/file.goindex e481721dd2..56e8fc3e3e 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -59,6 +59,12 @@ func copyDecryptedAsset(src, dest string) error {if boxID == "" || !model.IsEncryptedBox(boxID) {return fmt.Errorf("source is not an encrypted asset")}+ if !model.IsBoxUnlocked(boxID) {+ return fmt.Errorf("%s", model.Conf.Language(314))+ }+ if err := model.EnsureAssetLocal(src); err != nil {+ return err+ }model.HoldBoxReadLock(boxID)defer model.ReleaseBoxReadLock(boxID)dek, dekErr := model.GetDEKIfUnlocked(boxID)@@ -101,6 +107,28 @@ func getUniqueFilename(c *gin.Context) {}}+// prepareFileAssets 在原始文件 API 完成权限校验后补齐目录或文件的资源内容。+func prepareFileAssets(absPath string) error {+ absPath = filepath.Clean(absPath)+ dataPath := filepath.Clean(util.DataDir)+ if gulu.File.IsSubPath(absPath, dataPath) {+ absPath = dataPath+ } else if absPath != dataPath && !gulu.File.IsSubPath(dataPath, absPath) {+ return nil+ }+ files, err := model.DeferredSyncAssets()+ if err != nil {+ return err+ }+ for _, file := range files {+ assetPath := filepath.Join(util.DataDir, filepath.FromSlash(strings.TrimPrefix(file.Path, "/")))+ if (absPath == assetPath || gulu.File.IsSubPath(absPath, assetPath)) && rejectEncryptedBoxPath(assetPath) {+ return fmt.Errorf("%s", model.Conf.Language(321))+ }+ }+ return model.EnsureAssetPrefixLocal(absPath)+}+func globalCopyFiles(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)@@ -144,13 +172,6 @@ func globalCopyFiles(c *gin.Context) {absSrc, _ := filepath.Abs(src)- if !filelock.IsExist(absSrc) {- logging.LogErrorf("file [%s] does not exist", src)- ret.Code = -1- ret.Msg = fmt.Sprintf("file [%s] does not exist", src)- return- }-if util.IsSensitivePath(absSrc) {logging.LogErrorf("refuse to copy sensitive file [%s]", src)ret.Code = -2@@ -164,6 +185,16 @@ func globalCopyFiles(c *gin.Context) {return}+ if err := prepareFileAssets(absSrc); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ if !filelock.IsExist(absSrc) {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("file [%s] does not exist", src)+ return+ }srcs[i] = absSrc}@@ -270,12 +301,6 @@ func workspaceCopyFiles(c *gin.Context) {ret.Msg = err.Error()return}- if !filelock.IsExist(absSrc) {- logging.LogErrorf("file [%s] does not exist", src)- ret.Code = -1- ret.Msg = fmt.Sprintf("file [%s] does not exist", src)- return- }if util.IsSensitivePath(absSrc) {logging.LogErrorf("refuse to copy sensitive file [%s]", src)ret.Code = -2@@ -287,6 +312,16 @@ func workspaceCopyFiles(c *gin.Context) {ret.Msg = model.Conf.Language(321)return}+ if err = prepareFileAssets(absSrc); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ if !filelock.IsExist(absSrc) {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("file [%s] does not exist", src)+ return+ }absSrcs = append(absSrcs, absSrc)}@@ -404,6 +439,12 @@ func copyFile(c *gin.Context) {return}+ if err = prepareFileAssets(src); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ ret.Data = map[string]any{"closeTimeout": 7000}+ return+ }info, err := os.Stat(src)if err != nil {logging.LogErrorf("stat [%s] failed: %s", src, err)@@ -470,16 +511,9 @@ func getFile(c *gin.Context) {c.JSON(http.StatusAccepted, ret)return}- if !filelock.IsExist(fileAbsPath) {- ret.Code = http.StatusNotFound- ret.Msg = "file does not exist"- c.JSON(http.StatusAccepted, ret)- return- }-// 解析符号链接(Windows 下含目录联接)后再做授权判断,防止 reader 通过 data/assets// 等目录下的链接读取工作空间外的文件(security advisory GHSA-g7gf-v79m-jwrm)- resolvedPath, err := model.ResolveRealPath(fileAbsPath)+ resolvedPath, err := model.ResolveAssetPathWithMissingLeaf(fileAbsPath)if err != nil {logging.LogErrorf("resolve symlinks for [%s] failed: %s", fileAbsPath, err)ret.Code = http.StatusInternalServerError@@ -496,28 +530,6 @@ func getFile(c *gin.Context) {}fileAbsPath = resolvedPath- info, err := os.Stat(fileAbsPath)- if os.IsNotExist(err) {- ret.Code = http.StatusNotFound- ret.Msg = err.Error()- c.JSON(http.StatusAccepted, ret)- return- }- if err != nil {- logging.LogErrorf("stat [%s] failed: %s", fileAbsPath, err)- ret.Code = http.StatusInternalServerError- ret.Msg = err.Error()- c.JSON(http.StatusAccepted, ret)- return- }- if info.IsDir() {- logging.LogErrorf("path [%s] is a directory path", fileAbsPath)- ret.Code = http.StatusConflict- ret.Msg = "path is a directory"- c.JSON(http.StatusAccepted, ret)- return- }-// REF: https://github.com/siyuan-note/siyuan/issues/11364if !model.IsAdminRoleContext(c) {// 符号链接解析后的真实路径必须仍位于工作空间内(admin 不受此限制,兼容 assets@@ -543,6 +555,33 @@ func getFile(c *gin.Context) {}}+ if gulu.File.IsSubPath(util.DataDir, fileAbsPath) {+ if err = model.EnsureAssetLocal(fileAbsPath); err != nil {+ ret.Code = http.StatusServiceUnavailable+ if os.IsNotExist(err) {+ ret.Code = http.StatusNotFound+ }+ ret.Msg = err.Error()+ c.JSON(http.StatusAccepted, ret)+ return+ }+ }+ info, err := os.Stat(fileAbsPath)+ if err != nil {+ ret.Code = http.StatusInternalServerError+ if os.IsNotExist(err) {+ ret.Code = http.StatusNotFound+ }+ ret.Msg = err.Error()+ c.JSON(http.StatusAccepted, ret)+ return+ }+ if info.IsDir() {+ ret.Code = http.StatusConflict+ ret.Msg = "path is a directory"+ c.JSON(http.StatusAccepted, ret)+ return+ }data, err := filelock.ReadFile(fileAbsPath)if err != nil {logging.LogErrorf("read file [%s] failed: %s", fileAbsPath, err)@@ -689,19 +728,6 @@ func renameFile(c *gin.Context) {ret.Msg = err.Error()return}- srcInfo, srcStatErr := os.Stat(srcAbsPath)- if os.IsNotExist(srcStatErr) {- ret.Code = http.StatusNotFound- ret.Msg = "Field [path]: path does not exist"- return- }- if srcStatErr != nil {- logging.LogErrorf("stat [%s] failed: %s", srcAbsPath, srcStatErr)- ret.Code = http.StatusInternalServerError- ret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return- }-destAbsPath, err := util.GetAbsPathInWorkspace(destPath)if err != nil {ret.Code = http.StatusForbidden@@ -714,6 +740,23 @@ func renameFile(c *gin.Context) {ret.Msg = model.Conf.Language(321)return}+ if err = prepareFileAssets(srcAbsPath); err == nil {+ err = prepareFileAssets(destAbsPath)+ }+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ srcInfo, srcStatErr := os.Stat(srcAbsPath)+ if srcStatErr != nil {+ ret.Code = http.StatusInternalServerError+ if os.IsNotExist(srcStatErr) {+ ret.Code = http.StatusNotFound+ }+ ret.Msg = srcStatErr.Error()+ return+ }if filelock.IsExist(destAbsPath) {ret.Code = http.StatusConflictret.Msg = "Field [newPath]: path already exists"@@ -792,6 +835,11 @@ func removeFile(c *gin.Context) {ret.Msg = model.Conf.Language(321)return}+ if err = prepareFileAssets(fileAbsPath); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }_, err = os.Stat(fileAbsPath)if os.IsNotExist(err) {ret.Code = http.StatusNotFounddiff --git a/kernel/api/router.go b/kernel/api/router.goindex dcd7333478..c2bedab1e4 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -353,6 +353,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/sync/setSyncProviderWebDAV", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setSyncProviderWebDAV)ginServer.Handle("POST", "/api/sync/setSyncProviderLocal", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setSyncProviderLocal)ginServer.Handle("POST", "/api/sync/setCloudSyncDir", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setCloudSyncDir)+ ginServer.Handle("POST", "/api/sync/setSyncAssetDownloadMode", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setSyncAssetDownloadMode)ginServer.Handle("POST", "/api/sync/createCloudSyncDir", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createCloudSyncDir)ginServer.Handle("POST", "/api/sync/removeCloudSyncDir", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeCloudSyncDir)ginServer.Handle("POST", "/api/sync/listCloudSyncDir", model.CheckAuth, model.CheckAdminRole, listCloudSyncDir)diff --git a/kernel/api/setting.go b/kernel/api/setting.goindex ba8ebb0bd0..245f7cc77a 100644--- a/kernel/api/setting.go+++ b/kernel/api/setting.go@@ -1113,6 +1113,11 @@ func getCloudUser(c *gin.Context) {ret.Data = nilreturn}+ if model.IsCloudAssetSourceChange(err) {+ ret.Code = 1+ ret.Msg = err.Error()+ return+ }ret.Code = 1ret.Msg = model.Conf.Language(18)}diff --git a/kernel/api/sync.go b/kernel/api/sync.goindex 34f7081165..397789a579 100644--- a/kernel/api/sync.go+++ b/kernel/api/sync.go@@ -653,6 +653,31 @@ func getSyncLANStatus(c *gin.Context) {ret.Data = model.GetSyncLANStatus()}+func setSyncAssetDownloadMode(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)+ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ var mode float64+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("mode", &mode, true, false)) {+ return+ }+ if mode != 0 && mode != 1 {+ ret.Code = -1+ ret.Msg = "invalid asset download mode"+ return+ }+ if err := model.SetSyncAssetDownloadMode(int(mode)); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ ret.Data = map[string]any{"closeTimeout": 7000}+ return+ }+ ret.Data = map[string]any{"assetDownloadMode": int(mode)}+}+func setSyncMode(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)@@ -839,5 +864,8 @@ func setCloudSyncDir(c *gin.Context) {if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("name", &name, true, true)) {return}- model.SetCloudSyncDir(name)+ if err := model.SetCloudSyncDir(name); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ }}diff --git a/kernel/conf/sync.go b/kernel/conf/sync.goindex b076c5e7ea..2fdeb79c65 100644--- a/kernel/conf/sync.go+++ b/kernel/conf/sync.go@@ -25,6 +25,7 @@ type Sync struct {Synced int64 `json:"synced"` // 最近同步时间Stat string `json:"stat"` // 最近同步统计信息GenerateConflictDoc bool `json:"generateConflictDoc"` // 云端同步冲突时是否生成冲突文档+ AssetDownloadMode int `json:"assetDownloadMode"` // 当前设备的资源下载模式,0:全部下载,1:按需下载Provider int `json:"provider"` // 云端存储服务提供者S3 *S3 `json:"s3"` // S3 对象存储服务配置WebDAV *WebDAV `json:"webdav"` // WebDAV 服务配置diff --git a/kernel/go.mod b/kernel/go.modindex 724883dc08..6c5df6f72c 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -72,7 +72,7 @@ require (github.com/sashabaranov/go-openai v1.42.0github.com/shirou/gopsutil/v4 v4.26.7github.com/siyuan-note/dataparser v0.0.0-20260115084335-b57cb8bc7c17- github.com/siyuan-note/dejavu v0.0.0-20260903044336-18ff3975dc11+ github.com/siyuan-note/dejavu v0.0.0-20260905115124-7887e495ff49github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044github.com/siyuan-note/eventbus v0.0.0-20260530125927-d77c74260dcegithub.com/siyuan-note/filelock v0.0.0-20260831011452-393425122aaadiff --git a/kernel/go.sum b/kernel/go.sumindex 5155422220..1d7ebc61b8 100644--- a/kernel/go.sum+++ b/kernel/go.sum@@ -452,6 +452,8 @@ github.com/siyuan-note/dejavu v0.0.0-20260819021305-56b6bf7abb5b h1:o0ar5s5+hzI4github.com/siyuan-note/dejavu v0.0.0-20260819021305-56b6bf7abb5b/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/dejavu v0.0.0-20260903044336-18ff3975dc11 h1:Ee596t6S1Uiy6zHJz7gpu+WQpyNsVsXP1SKSMxUYI2g=github.com/siyuan-note/dejavu v0.0.0-20260903044336-18ff3975dc11/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=+github.com/siyuan-note/dejavu v0.0.0-20260905115124-7887e495ff49 h1:rDRuOm/laqJ/KkvwHVsnGuKDCudZfmpM4YT7ViTsXOU=+github.com/siyuan-note/dejavu v0.0.0-20260905115124-7887e495ff49/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044 h1:b1/Q4DSREDvGh1/NbzR9873EKrjakdoUtsNlghWxUOI=github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044/go.mod h1:t6jXpJdrXzRsdQF+XGaw35f16JVZcDyIkk5/6//ywnY=github.com/siyuan-note/eventbus v0.0.0-20260530125927-d77c74260dce h1:356bfC3pucxXuYpZIwaQ3viVCbq5RbRuvBhb4xtoBR0=diff --git a/kernel/harmony/kernel.go b/kernel/harmony/kernel.goindex 8ac21f370c..3218a859c1 100644--- a/kernel/harmony/kernel.go+++ b/kernel/harmony/kernel.go@@ -188,6 +188,9 @@ func GetCurrentWorkspacePath() *C.char {//export GetAssetAbsPathfunc GetAssetAbsPath(relativePath *C.char) *C.char {absPath, err := model.GetAssetAbsPath(C.GoString(relativePath))+ if err == nil {+ err = model.EnsureAssetLocal(absPath)+ }if nil != err {logging.LogErrorf("get asset abs path failed: %s", err)return relativePath@@ -273,6 +276,9 @@ func GetExportFilePath(exportPath *C.char) *C.char {} else if strings.HasPrefix(pathStr, "assets/") {var err errorabsPath, err = model.GetAssetAbsPath(pathStr)+ if err == nil {+ err = model.EnsureAssetLocal(absPath)+ }if nil != err {logging.LogErrorf("get asset abs path [%s] failed: %s", pathStr, err)return nildiff --git a/kernel/mcp/tools/image.go b/kernel/mcp/tools/image.goindex 8918fb7293..23b08a65ad 100644--- a/kernel/mcp/tools/image.go+++ b/kernel/mcp/tools/image.go@@ -329,8 +329,8 @@ func imageOperationAssetExists(documentID, assetPath string) bool {if bt == nil {return false}- absPath, err := model.GetAssetAbsPathInBox(assetPath, bt.BoxID)- return err == nil && filelock.IsExist(absPath)+ _, err := model.GetAssetAbsPathInBox(assetPath, bt.BoxID)+ return err == nil}func imageJSON(value any) CallToolResult {diff --git a/kernel/mobile/kernel.go b/kernel/mobile/kernel.goindex ea1d56fd80..415ca10e64 100644--- a/kernel/mobile/kernel.go+++ b/kernel/mobile/kernel.go@@ -328,6 +328,9 @@ func GetCurrentWorkspacePath() string {func GetAssetAbsPath(asset string) (ret string) {ret, err := model.GetAssetAbsPath(asset)+ if err == nil {+ err = model.EnsureAssetLocal(ret)+ }if err != nil {logging.LogErrorf("get asset [%s] abs path failed: %s", asset, err)ret = asset@@ -409,6 +412,9 @@ func GetExportFilePath(exportPath string) (ret string) {} else if strings.HasPrefix(exportPath, "assets/") {var err errorabsPath, err = model.GetAssetAbsPath(exportPath)+ if err == nil {+ err = model.EnsureAssetLocal(absPath)+ }if nil != err {logging.LogErrorf("get asset abs path [%s] failed: %s", exportPath, err)returndiff --git a/kernel/model/asset_download.go b/kernel/model/asset_download.gonew file mode 100644index 0000000000..a88d40fc58--- /dev/null+++ b/kernel/model/asset_download.go@@ -0,0 +1,419 @@+// SiYuan - From thought to insight, with agents+// 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.++package model++import (+ "crypto/sha256"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "sync"++ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/dejavu/cloud"+ "github.com/siyuan-note/dejavu/entity"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// 资源下载不持有同步锁,避免调用方的笔记本读锁与同步后的笔记本更新互相等待。+var assetDownloadSourceMu sync.RWMutex++func assetDownloadStatePath() string {+ return filepath.Join(util.ConfDir, "asset-downloads.json")+}++func assetDownloadStateExists() (bool, error) {+ return dejavu.AssetDownloadStateExists(assetDownloadStatePath(), util.RepoDir)+}++// assetDownloadScope 只绑定资源来源,不将令牌、超时或并发等连接选项作为仓库身份。+func assetDownloadScope(provider int, c *cloud.Conf, key []byte) string {+ dir := c.Dir+ if provider == conf.ProviderS3 {+ dir = ""+ }+ identity := []string{fmt.Sprint(provider), dir, fmt.Sprintf("%x", sha256.Sum256(key))}+ switch provider {+ case conf.ProviderSiYuan:+ identity = append(identity, c.Server, c.UserID)+ case conf.ProviderS3:+ if c.S3 != nil {+ identity = append(identity, c.S3.Endpoint, c.S3.Bucket)+ }+ case conf.ProviderWebDAV:+ if c.WebDAV != nil {+ identity = append(identity, c.WebDAV.Endpoint, c.WebDAV.Username)+ }+ case conf.ProviderLocal:+ if c.Local != nil {+ identity = append(identity, filepath.Clean(c.Local.Endpoint))+ }+ }+ data, _ := json.Marshal(identity)+ return fmt.Sprintf("%x", sha256.Sum256(data))+}++// DeferredSyncAssets 仅读取逻辑清单,不发起下载。+func DeferredSyncAssets() ([]*entity.File, error) {+ return deferredSyncAssets()+}++func deferredSyncAssets() ([]*entity.File, error) {+ exists, err := assetDownloadStateExists()+ if err != nil || !exists {+ return nil, err+ }+ if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {+ return nil, errors.New(Conf.Language(377))+ }+ return dejavu.ReadDeferredAssets(assetDownloadStatePath(), Conf.Repo.Key)+}++// validateAssetDownloadSourceScope 在公布新的账号身份前保留未完成的资源与历史恢复来源。+func validateAssetDownloadSourceScope(scope string) error {+ exists, err := assetDownloadStateExists()+ if err != nil || !exists {+ return err+ }+ if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {+ return errors.New(Conf.Language(377))+ }+ stored, err := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Key)+ if err != nil || stored == scope {+ return err+ }+ return requireCompleteAssetDownloads()+}++func checkAssetDownloadAccess() error {+ if Conf.Sync == nil || !Conf.Sync.Enabled || Conf.GetUser() == nil {+ return errors.New(Conf.Language(376))+ }+ switch Conf.Sync.Provider {+ case conf.ProviderSiYuan:+ if !IsSubscriber() {+ return errors.New(Conf.Language(376))+ }+ case conf.ProviderS3, conf.ProviderWebDAV, conf.ProviderLocal:+ if !IsPaidUser() {+ return errors.New(Conf.Language(376))+ }+ }+ return nil+}++func dataRelativeAssetPath(absPath string) (string, error) {+ if !filepath.IsAbs(absPath) {+ return "", fmt.Errorf("asset path must be absolute")+ }+ rel, err := filepath.Rel(util.DataDir, filepath.Clean(absPath))+ if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {+ return "", fmt.Errorf("asset path is outside data directory")+ }+ if rel == "." {+ return "/", nil+ }+ return "/" + filepath.ToSlash(rel), nil+}++// EnsureAssetLocal 在调用方完成访问校验后补齐资源,下载内容仍由原有读取流程认证。+func EnsureAssetLocal(absPath string) error {+ if _, err := os.Stat(absPath); err == nil {+ return nil+ } else if !errors.Is(err, os.ErrNotExist) {+ return err+ }+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()+ rel, err := dataRelativeAssetPath(absPath)+ if err != nil {+ return err+ }+ files, err := deferredSyncAssets()+ if err != nil {+ return err+ }+ for _, file := range files {+ if file.Path == rel {+ if repoFileNeedsDownload(file) {+ if err = checkAssetDownloadAccess(); err != nil {+ return err+ }+ }+ repo, repoErr := newSyncRepositoryWithAssetSourceLocked()+ if repoErr != nil {+ return repoErr+ }+ var downloaded bool+ if downloaded, err = repo.EnsureAsset(rel, newSyncContext()); err != nil {+ return fmt.Errorf("%s: %w", Conf.Language(376), err)+ }+ if downloaded {+ HandleAssetsChangeEvent(absPath)+ }+ return nil+ }+ }+ return &os.PathError{Op: "open", Path: absPath, Err: os.ErrNotExist}+}++// EnsureAssetPrefixLocal 补齐逻辑清单中的目录内容,不能仅遍历本地磁盘。+func EnsureAssetPrefixLocal(absPrefix string) error {+ prefix, err := dataRelativeAssetPath(absPrefix)+ if err != nil {+ return err+ }+ files, err := deferredSyncAssets()+ if err != nil || len(files) == 0 {+ return err+ }+ hasDeferred := false+ for _, file := range files {+ if file.Path == prefix || strings.HasPrefix(file.Path, strings.TrimSuffix(prefix, "/")+"/") {+ hasDeferred = true+ break+ }+ }+ if !hasDeferred {+ return nil+ }+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()+ files, err = deferredSyncAssets()+ if err != nil {+ return err+ }+ var repo *dejavu.Repo+ for _, file := range files {+ if file.Path != prefix && !strings.HasPrefix(file.Path, strings.TrimSuffix(prefix, "/")+"/") {+ continue+ }+ if repoFileNeedsDownload(file) {+ if err = checkAssetDownloadAccess(); err != nil {+ return err+ }+ }+ if repo == nil {+ repo, err = newSyncRepositoryWithAssetSourceLocked()+ if err != nil {+ return err+ }+ }+ var downloaded bool+ if downloaded, err = repo.EnsureAsset(file.Path, newSyncContext()); err != nil {+ return fmt.Errorf("%s: %w", Conf.Language(376), err)+ }+ if downloaded {+ HandleAssetsChangeEvent(filepath.Join(util.DataDir, filepath.FromSlash(strings.TrimPrefix(file.Path, "/"))))+ }+ }+ return nil+}++// EnsureAllSyncAssets 用于完整导出和退出按需模式,不改变资源的逻辑版本。+func EnsureAllSyncAssets() error {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()+ return ensureAllSyncAssets()+}++func ensureAllSyncAssets() error {+ files, err := deferredSyncAssets()+ if err != nil || len(files) == 0 {+ return err+ }+ for _, file := range files {+ if repoFileNeedsDownload(file) {+ if err = checkAssetDownloadAccess(); err != nil {+ return err+ }+ break+ }+ }+ repo, err := newSyncRepositoryWithAssetSourceLocked()+ if err != nil {+ return err+ }+ if err = repo.EnsureAllAssets(newSyncContext()); err != nil {+ return fmt.Errorf("%s: %w", Conf.Language(376), err)+ }+ return nil+}++func requireCompleteAssetDownloads() error {+ files, err := deferredSyncAssets()+ if err != nil {+ return err+ }+ if len(files) != 0 {+ return errors.New(Conf.Language(377))+ }+ exists, err := assetDownloadStateExists()+ if err != nil || !exists {+ return err+ }+ repo, err := newRepositoryWithAssetSourceLocked()+ if err != nil {+ return err+ }+ incomplete, err := repo.HasIncompleteSnapshots()+ if err != nil {+ return err+ }+ if incomplete {+ return errors.New(Conf.Language(377))+ }+ return nil+}++// clearAssetDownloadState 在旧密钥仍可认证且全部恢复内容齐全时清除设备状态。+func clearAssetDownloadState() error {+ exists, err := assetDownloadStateExists()+ if err != nil || !exists {+ return err+ }+ repo, err := newRepositoryWithAssetSourceLocked()+ if err != nil {+ return err+ }+ return repo.ClearAssetDownloadState()+}++func SetSyncAssetDownloadMode(mode int) error {+ if mode != 0 && mode != 1 {+ return errors.New("invalid asset download mode")+ }+ lockSync()+ defer unlockSync()+ assetDownloadSourceMu.Lock()+ defer assetDownloadSourceMu.Unlock()+ if mode == 0 {+ if err := ensureAllSyncAssets(); err != nil {+ return err+ }+ exists, err := assetDownloadStateExists()+ if err != nil {+ return err+ }+ if exists {+ repo, repoErr := newRepositoryWithAssetSourceLocked()+ if repoErr != nil {+ return repoErr+ }+ incomplete, checkErr := repo.HasIncompleteSnapshots()+ if checkErr != nil {+ return checkErr+ }+ if incomplete {+ if err = checkAssetDownloadAccess(); err != nil {+ return err+ }+ if err = repo.EnsureAllSnapshotChunks(newSyncContext()); err != nil {+ return fmt.Errorf("%s: %w", Conf.Language(376), err)+ }+ }+ }+ }+ Conf.Sync.AssetDownloadMode = mode+ Conf.Save()+ return nil+}++// lockAssetSourceChange 与同步、首次下载串行化来源切换;释放函数可重复调用。+func lockAssetSourceChange() func() {+ lockSync()+ assetDownloadSourceMu.Lock()+ var once sync.Once+ return func() {+ once.Do(func() {+ assetDownloadSourceMu.Unlock()+ unlockSync()+ })+ }+}++func openRepoFileWithAssets(repo *dejavu.Repo, file *entity.File) ([]byte, error) {+ data, err := repo.OpenFile(file)+ if err == nil || !errors.Is(err, os.ErrNotExist) {+ return data, err+ }+ if err = checkAssetDownloadAccess(); err != nil {+ return nil, err+ }+ if err = repo.EnsureFileChunks(file, newSyncContext()); err != nil {+ return nil, fmt.Errorf("%s: %w", Conf.Language(376), err)+ }+ return repo.OpenFile(file)+}++// readRepoFileWithAssets 将仓库实例的创建和历史分块补齐纳入来源读锁。+func readRepoFileWithAssets(fileID string) ([]byte, *entity.File, error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()+ if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {+ return nil, nil, errors.New(Conf.Language(26))+ }+ repo, err := newRepositoryWithAssetSourceLocked()+ if err != nil {+ return nil, nil, err+ }+ file, err := repo.GetFile(fileID)+ if err != nil {+ return nil, nil, err+ }+ if boxID := encryptedBoxIDFromRepoPath(file.Path); boxID != "" && !IsBoxUnlocked(boxID) {+ return nil, nil, errors.New(Conf.Language(314))+ }+ data, err := openRepoFileWithAssets(repo, file)+ return data, file, err+}++func ensureRepoSnapshotComplete(repo *dejavu.Repo, indexID string) error {+ index, err := repo.GetIndex(indexID)+ if err != nil {+ return err+ }+ return repo.GetFilesIter(index, func(file *entity.File) error {+ if !repoFileNeedsDownload(file) {+ return nil+ }+ if err := checkAssetDownloadAccess(); err != nil {+ return err+ }+ return repo.EnsureFileChunks(file, newSyncContext())+ })+}++func repoFileNeedsDownload(file *entity.File) bool {+ return repoFileNeedsDownloadWithCache(file, nil)+}++func repoFileNeedsDownloadWithCache(file *entity.File, chunkAvailability map[string]bool) bool {+ for _, chunkID := range file.Chunks {+ if len(chunkID) != 40 {+ return true+ }+ available, checked := chunkAvailability[chunkID]+ if !checked {+ _, err := os.Stat(filepath.Join(util.RepoDir, "objects", chunkID[:2], chunkID[2:]))+ available = err == nil+ if chunkAvailability != nil {+ chunkAvailability[chunkID] = available+ }+ }+ if !available {+ return true+ }+ }+ return false+}diff --git a/kernel/model/asset_download_read.go b/kernel/model/asset_download_read.gonew file mode 100644index 0000000000..cbe2ba50e6--- /dev/null+++ b/kernel/model/asset_download_read.go@@ -0,0 +1,273 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import (+ "errors"+ "fmt"+ "os"+ "path"+ "path/filepath"+ "sort"+ "strings"++ "github.com/88250/gulu"+ "github.com/88250/lute/ast"+ "github.com/88250/lute/editor"+ "github.com/88250/lute/html"+ "github.com/88250/lute/parse"+ "github.com/emirpasic/gods/sets/hashset"+ "github.com/siyuan-note/dejavu/entity"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// ResolveAssetPathWithMissingLeaf 校验尚未下载的路径,已存在的父目录仍须通过符号链接校验。+func ResolveAssetPathWithMissingLeaf(absPath string) (string, error) {+ current := filepath.Clean(absPath)+ var missing []string+ for {+ resolved, err := ResolveRealPath(current)+ if err == nil {+ for i := len(missing) - 1; i >= 0; i-- {+ resolved = filepath.Join(resolved, missing[i])+ }+ return resolved, nil+ }+ if !os.IsNotExist(err) {+ return "", err+ }+ if info, statErr := os.Lstat(current); statErr == nil && info.Mode()&os.ModeSymlink != 0 {+ return "", fmt.Errorf("asset path contains an unresolved symbolic link [%s]", current)+ }+ parent := filepath.Dir(current)+ if parent == current {+ return "", err+ }+ missing = append(missing, filepath.Base(current))+ current = parent+ }+}++// deferredAssetPath 只解析同步清单,不访问网络,也不以未下载状态推断文件已删除。+func deferredAssetPath(relativePath, boxID string, includeEncrypted bool) (string, error) {+ files, err := DeferredSyncAssets()+ if err != nil {+ return "", err+ }+ return deferredAssetPathFromFiles(relativePath, boxID, includeEncrypted, files)+}++func deferredAssetPathFromFiles(relativePath, boxID string, includeEncrypted bool, files []*entity.File) (string, error) {+ relativePath = strings.TrimPrefix(path.Clean(filepath.ToSlash(relativePath)), "/")+ var candidates []string+ for _, file := range files {+ candidate := strings.TrimPrefix(file.Path, "/")+ lookupPath := candidate+ if boxID != "" {+ target := path.Join(boxID, relativePath)+ if candidate != target && !strings.HasPrefix(candidate, target+"/") {+ continue+ }+ lookupPath = target+ } else {+ switch {+ case candidate == relativePath, strings.HasSuffix(candidate, "/"+relativePath):+ case strings.HasPrefix(candidate, relativePath+"/"):+ lookupPath = relativePath+ case strings.Contains(candidate, "/"+relativePath+"/"):+ lookupPath = candidate[:strings.Index(candidate, "/"+relativePath+"/")+len(relativePath)+1]+ default:+ continue+ }+ }+ absPath := filepath.Join(util.DataDir, filepath.FromSlash(lookupPath))+ if !includeEncrypted && IsEncryptedAssetPath(absPath) {+ continue+ }+ if !gulu.File.IsSubPath(util.DataDir, absPath) {+ return "", errors.New("asset path escapes data directory")+ }+ if boxID == "" && !IsEncryptedAssetPath(absPath) {+ if _, _, resolveErr := ResolveDataAssetPath(lookupPath); resolveErr != nil {+ return "", resolveErr+ }+ } else {+ resolvedBoxID := boxID+ if resolvedBoxID == "" {+ resolvedBoxID = ExtractBoxIDFromAssetsPath(absPath)+ }+ root, rootErr := ResolveAssetPathWithMissingLeaf(filepath.Join(util.DataDir, resolvedBoxID, "assets"))+ resolved, resolveErr := ResolveAssetPathWithMissingLeaf(absPath)+ notebookRoot, notebookErr := ResolveRealPath(filepath.Join(util.DataDir, resolvedBoxID))+ dataRoot, dataErr := ResolveRealPath(util.DataDir)+ if rootErr != nil || resolveErr != nil || notebookErr != nil || dataErr != nil ||+ !gulu.File.IsSubPath(dataRoot, notebookRoot) ||+ !gulu.File.IsSubPath(notebookRoot, root) || !gulu.File.IsSubPath(root, resolved) {+ return "", errors.New("asset path resolves outside notebook assets directory")+ }+ }+ if lookupPath == relativePath {+ return absPath, nil+ }+ candidates = append(candidates, absPath)+ }+ sort.Strings(candidates)+ if len(candidates) > 0 {+ return candidates[0], nil+ }+ return "", nil+}++// ensureReadableAssetLocal 先检查加密笔记本准入,再下载原始密文;实际读取仍须认证解密。+func ensureReadableAssetLocal(absPath string) error {+ boxID := ExtractBoxIDFromAssetsPath(absPath)+ if boxID != "" && IsEncryptedBox(boxID) && !IsBoxUnlocked(boxID) {+ return errors.New(Conf.Language(314))+ }+ if gulu.File.IsSubPath(util.DataDir, absPath) {+ if err := EnsureAssetPrefixLocal(absPath); err != nil {+ return err+ }+ }+ return EnsureAssetLocal(absPath)+}++// prepareExportAssets 在导出持有笔记本读锁或生成产物之前补齐文档引用的资源。+func prepareExportAssets(boxID string, docPaths []string) error {+ if boxID != "" && IsEncryptedBox(boxID) && !IsBoxUnlocked(boxID) {+ return errors.New(Conf.Language(314))+ }+ deferred, err := DeferredSyncAssets()+ if err != nil || len(deferred) == 0 {+ return err+ }+ trees := map[string]*parse.Tree{}+ luteEngine := util.NewLute()+ for _, docPath := range docPaths {+ if !strings.HasSuffix(docPath, ".sy") {+ continue+ }+ targetBoxID := boxID+ if targetBoxID == "" {+ if bt := getExportBlockTree(util.GetTreeID(docPath)); bt != nil {+ targetBoxID = bt.BoxID+ }+ }+ if targetBoxID == "" {+ continue+ }+ if IsEncryptedBox(targetBoxID) && !IsBoxUnlocked(targetBoxID) {+ return errors.New(Conf.Language(314))+ }+ tree, loadErr := filesys.LoadTree(targetBoxID, docPath, luteEngine)+ if loadErr != nil {+ return loadErr+ }+ exportRefTrees(tree, &[]string{}, trees)+ }+ // 查询嵌入的资源属于导出依赖,按笔记本边界展开并去重,避免循环嵌入反复读取。+ var pending []*parse.Tree+ queued := map[string]bool{}+ appendPending := func() {+ for id, tree := range trees {+ if !queued[id] {+ queued[id] = true+ pending = append(pending, tree)+ }+ }+ }+ appendPending()+ for i := 0; i < len(pending); i++ {+ tree := pending[i]+ treenode.WalkWithTabTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering || node.Type != ast.NodeBlockQueryEmbedScript {+ return ast.WalkContinue+ }+ stmt := strings.ReplaceAll(html.UnescapeString(node.TokensStr()), editor.IALValEscNewLine, "\n")+ var blocks []*sql.Block+ if IsEncryptedBox(tree.Box) {+ blocks = sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Limit, tree.Box)+ } else {+ blocks = sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)+ }+ for _, block := range blocks {+ if embedded, loadErr := loadExportRelatedTree(block.ID, tree.Box); loadErr == nil {+ exportRefTrees(embedded, &[]string{}, trees)+ }+ }+ return ast.WalkContinue+ })+ appendPending()+ }+ assets := map[string]bool{}+ for _, tree := range trees {+ dests := getAssetsLinkDests(tree.Root, false)+ avBoxID := ""+ if IsEncryptedBox(tree.Box) {+ avBoxID = tree.Box+ }+ avIDs := hashset.New()+ treenode.WalkWithTabTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && node.Type == ast.NodeAttributeView && node.AttributeViewID != "" {+ walkRelationAvs(node.AttributeViewID, avBoxID, avIDs)+ }+ return ast.WalkContinue+ })+ for _, id := range avIDs.Values() {+ attrView, parseErr := av.ParseAttributeViewInBox(id.(string), avBoxID)+ if parseErr != nil {+ return parseErr+ }+ dests = append(dests, getAttributeViewAssetsLinkDests(attrView, false, nil)...)+ }+ if titleImage := treenode.GetDocTitleImgPath(tree.Root); titleImage != "" {+ dests = append(dests, titleImage)+ }+ for _, dest := range dests {+ dest = string(html.DecodeDestination([]byte(dest)))+ if fragment := strings.IndexByte(dest, '#'); fragment >= 0 {+ dest = dest[:fragment]+ }+ if !strings.HasPrefix(AssetPathWithoutQuery(dest), "assets/") {+ continue+ }+ absPath, resolveErr := GetAssetAbsPathInBox(dest, tree.Box)+ if resolveErr != nil {+ return resolveErr+ }+ assets[absPath] = true+ }+ }+ for absPath := range assets {+ if err = EnsureAssetPrefixLocal(absPath); err != nil {+ return fmt.Errorf("prepare export asset [%s]: %w", filepath.Base(absPath), err)+ }+ }+ return nil+}++func prepareExportBlockAssets(id string, includeSubDocs bool) error {+ bt := getExportBlockTree(id)+ if bt == nil {+ return nil+ }+ docPaths := []string{bt.Path}+ if includeSubDocs {+ if box := Conf.Box(bt.BoxID); box != nil {+ listPath := strings.TrimSuffix(bt.Path, ".sy")+ if IsBoxDoc(bt.BoxID, bt.RootID) {+ listPath = "/"+ }+ for _, file := range box.ListFiles(listPath) {+ docPaths = append(docPaths, file.path)+ }+ }+ }+ return prepareExportAssets(bt.BoxID, docPaths)+}diff --git a/kernel/model/asset_download_read_test.go b/kernel/model/asset_download_read_test.gonew file mode 100644index 0000000000..bb68f13de8--- /dev/null+++ b/kernel/model/asset_download_read_test.go@@ -0,0 +1,207 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import (+ "archive/zip"+ "bytes"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/dejavu/cloud"+ "github.com/siyuan-note/dejavu/entity"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDeferredAssetPathWithoutLocalDirectories(t *testing.T) {+ originalDataDir, originalWorkspaceDir, originalConf := util.DataDir, util.WorkspaceDir, Conf+ t.Cleanup(func() { util.DataDir, util.WorkspaceDir, Conf = originalDataDir, originalWorkspaceDir, originalConf })+ util.WorkspaceDir = t.TempDir()+ util.DataDir = filepath.Join(util.WorkspaceDir, "data")+ Conf = NewAppConf()+ if err := os.MkdirAll(util.DataDir, 0755); err != nil {+ t.Fatal(err)+ }+ const boxID = "20260905010101-abcdefg"+ boxConfPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")+ if err := os.MkdirAll(filepath.Dir(boxConfPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(boxConfPath, []byte(`{"name":"Notebook"}`), 0644); err != nil {+ t.Fatal(err)+ }+ files := []*entity.File{+ {Path: "/assets/site/index.html"},+ {Path: "/" + boxID + "/assets/notebook.pdf"},+ {Path: "/" + boxID + "/20260905010102-abcdefg/assets/document.pdf"},+ }+ for _, test := range []struct {+ assetPath string+ boxID string+ wantPath string+ }{+ {"assets/site/index.html", "", "assets/site/index.html"},+ {"assets/site", "", "assets/site"},+ {"assets/site/", "", "assets/site"},+ {"assets/notebook.pdf", boxID, boxID + "/assets/notebook.pdf"},+ {"assets/document.pdf", "", boxID + "/20260905010102-abcdefg/assets/document.pdf"},+ } {+ t.Run(test.assetPath, func(t *testing.T) {+ got, err := deferredAssetPathFromFiles(test.assetPath, test.boxID, false, files)+ want := filepath.Join(util.DataDir, filepath.FromSlash(test.wantPath))+ if err != nil || got != want {+ t.Fatalf("got %q, %v; want %q", got, err, want)+ }+ if _, statErr := os.Stat(got); !os.IsNotExist(statErr) {+ t.Fatalf("metadata resolution created local content: %v", statErr)+ }+ })+ }+ if got, err := deferredAssetPathFromFiles("assets/unknown.pdf", "", false, files); err != nil || got != "" {+ t.Fatalf("unknown asset resolved: %q, %v", got, err)+ }+}++func TestDeferredAssetReadAndDirectoryExport(t *testing.T) {+ originalConf := Conf+ originalWorkspace, originalData, originalRepo := util.WorkspaceDir, util.DataDir, util.RepoDir+ originalHistory, originalTemp, originalConfDir := util.HistoryDir, util.TempDir, util.ConfDir+ originalStatusBar := util.StatusBarCfg+ t.Cleanup(func() {+ Conf = originalConf+ util.WorkspaceDir, util.DataDir, util.RepoDir = originalWorkspace, originalData, originalRepo+ util.HistoryDir, util.TempDir, util.ConfDir = originalHistory, originalTemp, originalConfDir+ util.StatusBarCfg = originalStatusBar+ })+ base := t.TempDir()+ remote := filepath.Join(base, "cloud")+ key := []byte("0123456789abcdef0123456789abcdef")+ fullDir := filepath.Join(base, "full")+ backend := cloud.NewLocal(&cloud.BaseCloud{Conf: &cloud.Conf{Dir: "main", RepoPath: filepath.Join(fullDir, "repo"),+ AvailableSize: 1024 * 1024 * 1024, Local: &cloud.ConfLocal{Endpoint: remote}}})+ full, err := dejavu.NewRepo(filepath.Join(fullDir, "data"), filepath.Join(fullDir, "repo"),+ filepath.Join(fullDir, "history"), filepath.Join(fullDir, "temp"), "full", "full", "windows", key, nil, backend)+ if err != nil {+ t.Fatal(err)+ }+ files := map[string]string{+ "seed.txt": "seed", "assets/image.png": "image bytes",+ "assets/site/index.html": "<p>site</p>", "assets/site/style.css": "p { color: red; }",+ }+ for name, data := range files {+ absPath := filepath.Join(fullDir, "data", filepath.FromSlash(name))+ if err = os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(absPath, []byte(data), 0644); err != nil {+ t.Fatal(err)+ }+ }+ Conf = NewAppConf()+ util.StatusBarCfg = &util.StatusBar{MsgDataSyncDisabled: true}+ Conf.Sync, Conf.Repo, Conf.System, Conf.Search = conf.NewSync(), conf.NewRepo(), conf.NewSystem(), conf.NewSearch()+ Conf.FileTree = conf.NewFileTree()+ Conf.Sync.Local = &conf.Local{Endpoint: remote}+ Conf.User = &conf.User{UserId: "asset-test", UserSiYuanOneTimePayStatus: 1}+ Conf.Sync.Provider, Conf.Sync.CloudName, Conf.Sync.Enabled = conf.ProviderLocal, "main", true+ Conf.Sync.Local.Endpoint, Conf.Sync.AssetDownloadMode = remote, 1+ Conf.Repo.Key = key+ util.WorkspaceDir = filepath.Join(base, "partial")+ util.DataDir, util.RepoDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "repo")+ util.HistoryDir, util.TempDir = filepath.Join(util.WorkspaceDir, "history"), filepath.Join(util.WorkspaceDir, "temp")+ util.ConfDir = filepath.Join(util.WorkspaceDir, "conf")+ if err = os.MkdirAll(util.RepoDir, 0755); err != nil {+ t.Fatal(err)+ }+ if _, err = full.Index("full", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = full.Sync(nil); err != nil {+ t.Fatal(err)+ }+ partial, err := newRepository()+ if err != nil {+ t.Fatal(err)+ }+ if err = os.MkdirAll(util.DataDir, 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(util.DataDir, "seed.txt"), []byte("seed"), 0644); err != nil {+ t.Fatal(err)+ }+ if _, err = partial.Index("partial", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = partial.Sync(nil); err != nil {+ t.Fatal(err)+ }+ if _, err = os.Stat(filepath.Join(util.DataDir, "assets", "image.png")); !os.IsNotExist(err) {+ t.Fatalf("asset was eagerly downloaded: %v", err)+ }+ if assets := SearchAssetsByName("image", nil); len(assets) != 1 || assets[0].Path != "assets/image.png" {+ t.Fatalf("deferred asset missing from name search: %+v", assets)+ }+ data, err := ReadAssetBytesInBox("", "assets/image.png")+ if err != nil || !bytes.Equal(data, []byte("image bytes")) {+ t.Fatalf("on-demand read: %q, %v", data, err)+ }+ Conf.Sync.Enabled = false+ if _, err = ReadAssetBytesInBox("", "assets/image.png"); err != nil {+ t.Fatalf("cached asset unavailable with sync disabled: %v", err)+ }+ if uri, exportErr := ExportResources([]string{"data/assets/site"}, "site"); exportErr == nil || uri != "" {+ t.Fatalf("offline incomplete directory export succeeded: %q, %v", uri, exportErr)+ }+ Conf.Sync.Enabled = true+ uri, err := ExportResources([]string{"data/assets/site"}, "site")+ if err != nil {+ t.Fatal(err)+ }+ archive, err := zip.OpenReader(filepath.Join(util.WorkspaceDir, filepath.FromSlash(uri)))+ if err != nil {+ t.Fatal(err)+ }+ defer archive.Close()+ entries := map[string]bool{}+ for _, entry := range archive.File {+ entries[filepath.Base(entry.Name)] = true+ }+ if !entries["index.html"] || !entries["style.css"] {+ t.Fatalf("directory export omitted deferred files: %+v", entries)+ }+ deferred, err := DeferredSyncAssets()+ if err != nil || len(deferred) != 0 {+ t.Fatalf("downloaded files stayed deferred: %+v, %v", deferred, err)+ }+ if !strings.HasPrefix(uri, "temp/export/") {+ t.Fatalf("unexpected export path: %q", uri)+ }+}++func TestDeferredAssetPathRejectsMissingLeafThroughEscapingSymlink(t *testing.T) {+ originalDataDir := util.DataDir+ t.Cleanup(func() { util.DataDir = originalDataDir })+ util.DataDir = t.TempDir()+ if err := os.MkdirAll(filepath.Join(util.DataDir, "assets"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(t.TempDir(), filepath.Join(util.DataDir, "assets", "linked")); err != nil {+ t.Skipf("symlink unavailable: %s", err)+ }+ files := []*entity.File{{Path: "/assets/linked/missing/image.png"}}+ if got, err := deferredAssetPathFromFiles("assets/linked/missing/image.png", "", false, files); err == nil {+ t.Fatalf("escaped missing asset resolved: %q", got)+ }+ if err := os.Symlink(filepath.Join(t.TempDir(), "not-created"), filepath.Join(util.DataDir, "assets", "dangling")); err != nil {+ t.Fatal(err)+ }+ if _, _, err := ResolveDataAssetPath("assets/dangling/missing.png"); err == nil {+ t.Fatal("dangling symlink must not become a writable deferred path")+ }+}diff --git a/kernel/model/asset_download_source_test.go b/kernel/model/asset_download_source_test.gonew file mode 100644index 0000000000..8e6c7a4322--- /dev/null+++ b/kernel/model/asset_download_source_test.go@@ -0,0 +1,92 @@+package model++import (+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAssetRepositoryCreationWaitsForSourceChange(t *testing.T) {+ _, partial, _ := prepareAssetDownloadRepoTest(t)+ if err := partial.EnsureAllAssets(nil); err != nil {+ t.Fatal(err)+ }+ if err := partial.EnsureAllSnapshotChunks(nil); err != nil {+ t.Fatal(err)+ }+ assetDownloadSourceMu.Lock()+ locked := true+ defer func() {+ if locked {+ assetDownloadSourceMu.Unlock()+ }+ }()+ if err := clearAssetDownloadState(); err != nil {+ t.Fatal(err)+ }+ started := make(chan struct{})+ created := make(chan error, 1)+ go func() {+ close(started)+ _, err := newRepository()+ created <- err+ }()+ <-started+ select {+ case err := <-created:+ t.Fatalf("repository was created during source change: %v", err)+ case <-time.After(50 * time.Millisecond):+ }+ if _, err := os.Stat(assetDownloadStatePath()); !os.IsNotExist(err) {+ t.Fatalf("old source state was recreated: %v", err)+ }+ Conf.Repo.Key = []byte("abcdef0123456789abcdef0123456789")+ assetDownloadSourceMu.Unlock()+ locked = false+ select {+ case err := <-created:+ if err != nil {+ t.Fatal(err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("repository creation did not resume")+ }+ if _, err := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Key); err != nil {+ t.Fatalf("new source state does not authenticate: %v", err)+ }+}++func TestAssetDownloadIndexIgnoreRequiresAccess(t *testing.T) {+ _, partial, _ := prepareAssetDownloadRepoTest(t)+ deferred, err := partial.DeferredAssets()+ if err != nil || len(deferred) != 1 {+ t.Fatalf("unexpected deferred resources: %v %v", deferred, err)+ }+ ignorePath := filepath.Join(util.DataDir, ".siyuan", "syncignore")+ if err = os.MkdirAll(filepath.Dir(ignorePath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(ignorePath, []byte("/assets/file.bin"), 0644); err != nil {+ t.Fatal(err)+ }+ Conf.Sync.Enabled = false+ if _, err = IndexRepo("offline ignore change"); err == nil {+ t.Fatal("local snapshot downloaded an ignored resource without access")+ }+ if deferred, err = partial.DeferredAssets(); err != nil || len(deferred) != 1 {+ t.Fatalf("failed snapshot lost resource state: %v %v", deferred, err)+ }+ if err = partial.EnsureFileChunks(deferred[0], nil); err != nil {+ t.Fatal(err)+ }+ if _, err = IndexRepo("locally available ignore change"); err != nil {+ t.Fatalf("local chunks cannot preserve an ignored resource offline: %v", err)+ }+ if data, readErr := os.ReadFile(filepath.Join(util.DataDir, "assets", "file.bin")); readErr != nil || string(data) != "version one" {+ t.Fatalf("ignored resource was not preserved: %q %v", data, readErr)+ }+}diff --git a/kernel/model/asset_download_test.go b/kernel/model/asset_download_test.gonew file mode 100644index 0000000000..589d940ba1--- /dev/null+++ b/kernel/model/asset_download_test.go@@ -0,0 +1,231 @@+package model++import (+ "bytes"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/dejavu/cloud"+ "github.com/siyuan-note/dejavu/entity"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func prepareAssetDownloadRepoTest(t *testing.T) (*dejavu.Repo, *dejavu.Repo, string) {+ t.Helper()+ originalConf := Conf+ originalWorkspace, originalData, originalRepo := util.WorkspaceDir, util.DataDir, util.RepoDir+ originalHistory, originalTemp, originalConfDir := util.HistoryDir, util.TempDir, util.ConfDir+ originalStatusBar := util.StatusBarCfg+ t.Cleanup(func() {+ util.StatusBarCfg = originalStatusBar+ Conf = originalConf+ util.WorkspaceDir, util.DataDir, util.RepoDir = originalWorkspace, originalData, originalRepo+ util.HistoryDir, util.TempDir, util.ConfDir = originalHistory, originalTemp, originalConfDir+ })+ base := t.TempDir()+ remote, fullDir := filepath.Join(base, "cloud"), filepath.Join(base, "full")+ key := []byte("0123456789abcdef0123456789abcdef")+ fullData := filepath.Join(fullDir, "data")+ backend := cloud.NewLocal(&cloud.BaseCloud{Conf: &cloud.Conf{Dir: "main", RepoPath: filepath.Join(fullDir, "repo"),+ AvailableSize: 1 << 30, Local: &cloud.ConfLocal{Endpoint: remote}}})+ full, err := dejavu.NewRepo(fullData, filepath.Join(fullDir, "repo"), filepath.Join(fullDir, "history"),+ filepath.Join(fullDir, "temp"), "full", "full", "windows", key, nil, backend)+ if err != nil {+ t.Fatal(err)+ }+ for name, content := range map[string]string{"seed.txt": "seed", "assets/file.bin": "version one"} {+ p := filepath.Join(fullData, filepath.FromSlash(name))+ if err = os.MkdirAll(filepath.Dir(p), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(p, []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }+ Conf = NewAppConf()+ util.StatusBarCfg = &util.StatusBar{MsgDataSyncDisabled: true}+ Conf.Sync, Conf.Repo, Conf.System, Conf.Search = conf.NewSync(), conf.NewRepo(), conf.NewSystem(), conf.NewSearch()+ Conf.Sync.Local = &conf.Local{Endpoint: remote}+ Conf.SetUser(&conf.User{UserId: "asset-test", UserSiYuanOneTimePayStatus: 1})+ Conf.Sync.Provider, Conf.Sync.CloudName, Conf.Sync.Enabled = conf.ProviderLocal, "main", true+ Conf.Sync.Local.Endpoint, Conf.Sync.AssetDownloadMode = remote, 1+ Conf.Repo.Key = key+ util.WorkspaceDir = filepath.Join(base, "partial")+ util.DataDir, util.RepoDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "repo")+ util.HistoryDir, util.TempDir = filepath.Join(util.WorkspaceDir, "history"), filepath.Join(util.WorkspaceDir, "temp")+ util.ConfDir = filepath.Join(util.WorkspaceDir, "conf")+ if _, err = full.Index("first", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = full.Sync(nil); err != nil {+ t.Fatal(err)+ }+ partial, err := newRepository()+ if err != nil {+ t.Fatal(err)+ }+ if err = os.MkdirAll(util.DataDir, 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(util.DataDir, "seed.txt"), []byte("seed"), 0644); err != nil {+ t.Fatal(err)+ }+ if _, err = partial.Index("partial", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = partial.Sync(nil); err != nil {+ t.Fatal(err)+ }+ return full, partial, fullData+}++func TestAssetDownloadModePreservesHistoricalRecovery(t *testing.T) {+ full, partial, fullData := prepareAssetDownloadRepoTest(t)+ deferred, err := DeferredSyncAssets()+ if err != nil || len(deferred) != 1 {+ t.Fatalf("expected a deferred asset: %v, %v", deferred, err)+ }+ oldFile := deferred[0]+ if err = requireCompleteAssetDownloads(); err == nil {+ t.Fatal("source change allowed with missing current content")+ }+ assetPath := filepath.Join(fullData, "assets", "file.bin")+ if err = os.WriteFile(assetPath, []byte("version two is different"), 0644); err != nil {+ t.Fatal(err)+ }+ updated := time.UnixMilli(oldFile.Updated).Add(2 * time.Second)+ if err = os.Chtimes(assetPath, updated, updated); err != nil {+ t.Fatal(err)+ }+ if _, err = full.Index("second", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = full.Sync(nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = partial.Sync(nil); err != nil {+ t.Fatal(err)+ }+ localAsset := filepath.Join(util.DataDir, "assets", "file.bin")+ if err = EnsureAssetLocal(localAsset); err != nil {+ t.Fatal(err)+ }+ if !repoFileNeedsDownload(oldFile) {+ t.Fatal("current asset read unexpectedly downloaded its historical version")+ }+ if err = requireCompleteAssetDownloads(); err == nil {+ t.Fatal("source change allowed with missing historical content")+ }+ Conf.Sync.Enabled = false+ if err = SetSyncAssetDownloadMode(0); err == nil || Conf.Sync.AssetDownloadMode != 1 {+ t.Fatalf("offline mode switch discarded the previous mode: %v", err)+ }+ if err = EnsureAssetLocal(localAsset); err != nil {+ t.Fatalf("cached resource unavailable offline: %v", err)+ }+ Conf.Sync.Enabled = true+ if err = SetSyncAssetDownloadMode(0); err != nil {+ t.Fatal(err)+ }+ if Conf.Sync.AssetDownloadMode != 0 || repoFileNeedsDownload(oldFile) {+ t.Fatal("full mode did not complete historical assets")+ }+ if err = requireCompleteAssetDownloads(); err != nil {+ t.Fatalf("complete source cannot be changed: %v", err)+ }+ data, file, err := readRepoFileWithAssets(oldFile.ID)+ if err != nil || file.ID != oldFile.ID || !bytes.Equal(data, []byte("version one")) {+ t.Fatalf("historical read returned the wrong version: %q, %v", data, err)+ }+ if data, err = os.ReadFile(localAsset); err != nil || !bytes.Equal(data, []byte("version two is different")) {+ t.Fatalf("historical read overwrote current asset: %q, %v", data, err)+ }+ if err = clearAssetDownloadState(); err != nil {+ t.Fatal(err)+ }+ if exists, err := assetDownloadStateExists(); err != nil || exists {+ t.Fatalf("authenticated complete state was not cleared: %v", err)+ }+ Conf.Repo.Key = nil+ if err = requireCompleteAssetDownloads(); err != nil {+ t.Fatalf("reset state prevents initializing another key: %v", err)+ }+}++func TestAssetDownloadStateCorruptionPreservesSource(t *testing.T) {+ prepareAssetDownloadRepoTest(t)+ statePath := assetDownloadStatePath()+ data, err := os.ReadFile(statePath)+ if err != nil {+ t.Fatal(err)+ }+ data[len(data)-1] ^= 1+ if err = os.WriteFile(statePath, data, 0600); err != nil {+ t.Fatal(err)+ }+ key := append([]byte(nil), Conf.Repo.Key...)+ if err = requireCompleteAssetDownloads(); err == nil {+ t.Fatal("corrupt state accepted for a source change")+ }+ if err = SetSyncAssetDownloadMode(0); err == nil || Conf.Sync.AssetDownloadMode != 1 {+ t.Fatal("corrupt state was discarded during a mode change")+ }+ if err = clearAssetDownloadState(); err == nil {+ t.Fatal("corrupt state was discarded before changing the key")+ }+ remaining, err := os.ReadFile(statePath)+ if err != nil || !bytes.Equal(data, remaining) || !bytes.Equal(key, Conf.Repo.Key) {+ t.Fatal("failure changed source state or recovery key")+ }+}++func TestAssetDownloadUsesLocalSnapshotChunksWhileLoggedOut(t *testing.T) {+ _, partial, _ := prepareAssetDownloadRepoTest(t)+ files, err := DeferredSyncAssets()+ if err != nil || len(files) != 1 {+ t.Fatalf("expected deferred resource: %v", err)+ }+ if err = partial.EnsureFileChunks(files[0], nil); err != nil {+ t.Fatal(err)+ }+ assetPath := filepath.Join(util.DataDir, "assets", "file.bin")+ if _, err = os.Stat(assetPath); !os.IsNotExist(err) {+ t.Fatal("snapshot chunk download unexpectedly materialized workspace content")+ }+ Conf.Sync.Enabled = false+ Conf.SetUser(nil)+ if err = EnsureAssetLocal(assetPath); err != nil {+ t.Fatalf("offline local chunks were not reused: %v", err)+ }+ data, err := os.ReadFile(assetPath)+ if err != nil || !bytes.Equal(data, []byte("version one")) {+ t.Fatalf("offline materialization changed content: %q, %v", data, err)+ }+}++func TestAssetDownloadScopeIdentity(t *testing.T) {+ key := []byte("0123456789abcdef0123456789abcdef")+ c := &cloud.Conf{Dir: "main", S3: &cloud.ConfS3{Endpoint: "https://storage.invalid", Bucket: "first"}}+ scope := assetDownloadScope(conf.ProviderS3, c, key)+ c.Dir = "bucket-display-name"+ c.S3.Timeout = 120+ if got := assetDownloadScope(conf.ProviderS3, c, key); got != scope {+ t.Fatal("connection/display settings changed the S3 resource identity")+ }+ c.S3.Bucket = "second"+ if got := assetDownloadScope(conf.ProviderS3, c, key); got == scope {+ t.Fatal("different S3 buckets share an identity")+ }+ c.S3.Bucket = "first"+ key[0] ^= 1+ if got := assetDownloadScope(conf.ProviderS3, c, key); got == scope {+ t.Fatal("different repository keys share an identity")+ }+ if !repoFileNeedsDownload(&entity.File{Chunks: []string{"invalid"}}) {+ t.Fatal("malformed chunk metadata marked complete")+ }+}diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex c4c23f73eb..83fc64322e 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -60,7 +60,12 @@ func GetAssetImgSize(assetPath string) (width, height int) {}func GetAssetImgSizeInBox(assetPath, boxID string) (width, height int) {- data, err := ReadAssetBytesInBox(boxID, assetPath)+ absPath, resolveErr := GetAssetAbsPathInBox(assetPath, boxID)+ if resolveErr != nil || !filelock.IsExist(absPath) {+ // 计算布局尺寸不触发资源下载,展示图片或完整导出时再补齐内容。+ return+ }+ data, err := readAssetBytesInBox(boxID, assetPath, false)if err != nil {logging.LogErrorf("get asset [%s] abs path failed: %s", assetPath, err)return@@ -88,10 +93,19 @@ func GetAssetImgSizeInBox(assetPath, boxID string) (width, height int) {// ReadAssetBytesInBox 读取指定 box 内的资源文件字节。若 box 为加密笔记本则自动解密返回明文。// relativePath 形如 "assets/xxx.png",可带 ?box= 查询参数。func ReadAssetBytesInBox(boxID, relativePath string) ([]byte, error) {+ return readAssetBytesInBox(boxID, relativePath, true)+}++func readAssetBytesInBox(boxID, relativePath string, download bool) ([]byte, error) {absPath, err := GetAssetAbsPathInBox(relativePath, boxID)if err != nil {return nil, err}+ if download {+ if err = ensureReadableAssetLocal(absPath); err != nil {+ return nil, err+ }+ }var data []bytevar readErr errorif heif.IsPath(relativePath) {@@ -478,6 +492,9 @@ func PrepareAgentMessageImage(assetPath string) (PreparedDocumentImage, error) {if !strings.HasPrefix(relativePath, "assets/") {return PreparedDocumentImage{}, errors.New("only global assets/... images are supported")}+ if err = EnsureAssetLocal(absPath); err != nil {+ return PreparedDocumentImage{}, err+ }data, err := os.ReadFile(absPath)if err != nil {return PreparedDocumentImage{}, fmt.Errorf("read image failed: %w", err)@@ -894,7 +911,7 @@ func SearchAssetsByName(keyword string, exts []string) (ret []*cache.Asset) {}pathHitCount := map[string]int{}filterByExt := 0 < len(exts)- matchedAssets := cache.FilterAssets(func(path string, asset *cache.Asset) bool {+ filterAsset := func(path string, asset *cache.Asset) bool {// 扩展名过滤if filterByExt {@@ -942,7 +959,27 @@ func SearchAssetsByName(keyword string, exts []string) (ret []*cache.Asset) {// 记录命中次数用于排序pathHitCount[asset.Path] = hitNameCount + hitPathCountreturn true- })+ }+ matchedAssets := cache.FilterAssets(filterAsset)+ if deferred, err := DeferredSyncAssets(); err == nil {+ for _, file := range deferred {+ if !strings.HasPrefix(file.Path, "/assets/") {+ continue+ }+ absPath := filepath.Join(util.DataDir, filepath.FromSlash(strings.TrimPrefix(file.Path, "/")))+ if IsEncryptedAssetPath(absPath) {+ continue+ }+ assetPath, _, valid := AssetPathFromDataRelativePath(strings.TrimPrefix(file.Path, "/"))+ if !valid || matchedAssets[assetPath] != nil {+ continue+ }+ asset := &cache.Asset{HName: util.RemoveID(filepath.Base(assetPath)), Path: assetPath, Updated: file.SecUpdated()}+ if filterAsset(assetPath, asset) {+ matchedAssets[assetPath] = asset+ }+ }+ }// 添加高亮for _, asset := range matchedAssets {@@ -1037,7 +1074,7 @@ func ResolveDataAssetPath(assetPath string) (relativePath, absPath string, err ereturn}- resolvedRoot, evalErr := ResolveRealPath(assetRoot)+ resolvedRoot, evalErr := ResolveAssetPathWithMissingLeaf(assetRoot)if evalErr != nil {err = fmt.Errorf("resolve assets directory [%s] failed: %w", assetRoot, evalErr)return@@ -1053,7 +1090,7 @@ func ResolveDataAssetPath(assetPath string) (relativePath, absPath string, err ereturn}}- resolvedPath, evalErr := ResolveRealPath(absPath)+ resolvedPath, evalErr := ResolveAssetPathWithMissingLeaf(absPath)if evalErr != nil {err = fmt.Errorf("resolve asset [%s] failed: %w", absPath, evalErr)return@@ -1082,10 +1119,10 @@ func ResolveUnusedDataAssetPath(assetPath string) (relativePath, absPath string,}func unusedAssetsContainPath(relativePath, absPath string, items []*UnusedItem) bool {- resolvedPath, _ := ResolveRealPath(absPath)+ resolvedPath, _ := ResolveAssetPathWithMissingLeaf(absPath)for _, item := range items {if item.AbsPath != "" {- resolvedItemPath, evalErr := ResolveRealPath(item.AbsPath)+ resolvedItemPath, evalErr := ResolveAssetPathWithMissingLeaf(item.AbsPath)samePath, relErr := filepath.Rel(resolvedPath, resolvedItemPath)if resolvedPath != "" && evalErr == nil && relErr == nil && samePath == "." {return true@@ -1215,6 +1252,9 @@ func GetAssetAbsPathInBox(relativePath, boxID string) (string, error) {return p, nil}// 非加密 box 的资源可能回退到全局 data/assets(兼容旧笔记本结构)+ if deferredPath, deferredErr := deferredAssetPath(relativePath, boxID, true); deferredErr != nil || deferredPath != "" {+ return deferredPath, deferredErr+ }if !IsEncryptedBox(boxID) {return GetAssetAbsPathWithOpt(relativePath, false)}@@ -1300,7 +1340,7 @@ func getAssetAbsPath(relativePath string, includeEncrypted bool) (absPath stringreturn absPath, nil}}- return "", nil+ return deferredAssetPath(relativePath, "", includeEncrypted)}func UploadAssets2Cloud(id string, ignorePushMsg bool) (count int, err error) {@@ -1404,6 +1444,9 @@ func uploadAssets2Cloud(assetPaths []string, bizType string, ignorePushMsg bool)pushErrMsgCount := 0var completedUploadAssets []stringfor _, absAsset := range uploadAbsAssets {+ if err = ensureReadableAssetLocal(absAsset); err != nil {+ return count, err+ }fi, statErr := os.Stat(absAsset)if nil != statErr {logging.LogErrorf("stat file [%s] failed: %s", absAsset, statErr)@@ -1479,6 +1522,12 @@ func RemoveUnusedAssets() (ret []string) {}()unusedAssets := UnusedAssets(false)+ for _, unusedAsset := range unusedAssets {+ if err := EnsureAssetPrefixLocal(filepath.Join(util.DataDir, unusedAsset.Item)); err != nil {+ util.PushErrMsg(err.Error(), 7000)+ return+ }+ }historyDir, err := getHistoryDir(HistoryOpClean)if err != nil {@@ -1549,6 +1598,9 @@ func RemoveUnusedAsset(p string) (ret string, err error) {if err != nil {return}+ if err = EnsureAssetPrefixLocal(absPath); err != nil {+ return+ }historyDir, err := getHistoryDir(HistoryOpClean)if err != nil {logging.LogErrorf("get history dir failed: %s", err)@@ -1622,6 +1674,9 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {logging.LogErrorf("get asset [%s] abs path failed: %s", oldPath, getErr)return}+ if err = ensureReadableAssetLocal(oldAbsPath); err != nil {+ return+ }newAbsPath := filepath.Join(filepath.Dir(oldAbsPath), newName)filelock.Lock(oldAbsPath)if err = os.Rename(oldAbsPath, newAbsPath); err != nil {@@ -2645,6 +2700,27 @@ func allAssetAbsPaths() (assetsAbsPathMap map[string]string, err error) {}assetsAbsPathMap = map[string]string{}+ deferred, deferredErr := DeferredSyncAssets()+ if deferredErr != nil {+ return nil, deferredErr+ }+ for _, file := range deferred {+ absPath := filepath.Join(util.DataDir, filepath.FromSlash(strings.TrimPrefix(file.Path, "/")))+ if IsEncryptedAssetPath(absPath) {+ continue+ }+ relativePath, _, resolveErr := ResolveDataAssetPath(strings.TrimPrefix(file.Path, "/"))+ if resolveErr != nil {+ return nil, resolveErr+ }+ assetPath, _, valid := AssetPathFromDataRelativePath(relativePath)+ if valid {+ assetsAbsPathMap[assetPath] = absPath+ for dir, absDir := path.Dir(assetPath), filepath.Dir(absPath); dir != "assets" && dir != "."; dir, absDir = path.Dir(dir), filepath.Dir(absDir) {+ assetsAbsPathMap[dir+"/"] = absDir+ }+ }+ }// 笔记本 assets(跳过加密 box,加密资产不参与全局去重/清理)for _, notebook := range notebooks {if IsEncryptedBox(notebook.ID) {@@ -2760,22 +2836,25 @@ func assetPathMapKey(assetsDirPath, assetPath string, isDir bool) (ret string, e}// copyBoxAssetsToDataAssets 将笔记本路径下所有(包括子文档)的 assets 复制一份到 data/assets 中。-func copyBoxAssetsToDataAssets(boxID string) {+func copyBoxAssetsToDataAssets(boxID string) error {boxLocalPath := filepath.Join(util.DataDir, boxID)- copyAssetsToDataAssets(boxLocalPath)+ return copyAssetsToDataAssets(boxLocalPath)}// copyDocAssetsToDataAssets 将文档路径下所有(包括子文档)的 assets 复制一份到 data/assets 中。-func copyDocAssetsToDataAssets(boxID, parentDocPath string) {+func copyDocAssetsToDataAssets(boxID, parentDocPath string) error {boxLocalPath := filepath.Join(util.DataDir, boxID)parentDocDirAbsPath := filepath.Dir(filepath.Join(boxLocalPath, parentDocPath))- copyAssetsToDataAssets(parentDocDirAbsPath)+ return copyAssetsToDataAssets(parentDocDirAbsPath)}-func copyAssetsToDataAssets(rootPath string) {+func copyAssetsToDataAssets(rootPath string) error {var assetsDirPaths []string- filelock.Walk(rootPath, func(path string, d fs.DirEntry, err error) error {- if nil != err || rootPath == path || nil == d {+ if err := filelock.Walk(rootPath, func(path string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if rootPath == path || nil == d {return nil}@@ -2791,12 +2870,16 @@ func copyAssetsToDataAssets(rootPath string) {assetsDirPaths = append(assetsDirPaths, path)}return nil- })+ }); err != nil {+ return err+ }dataAssetsPath := filepath.Join(util.DataDir, "assets")for _, assetsDirPath := range assetsDirPaths {if err := filelock.Copy(assetsDirPath, dataAssetsPath); err != nil {logging.LogErrorf("copy tree assets from [%s] to [%s] failed: %s", assetsDirPaths, dataAssetsPath, err)+ return err}}+ return nil}diff --git a/kernel/model/clipboard.go b/kernel/model/clipboard.goindex 8cfe719d7f..a9faa714ea 100644--- a/kernel/model/clipboard.go+++ b/kernel/model/clipboard.go@@ -92,6 +92,9 @@ func PrepareRichClipboardAssets(assets []RichClipboardAsset) (ret *RichClipboardif resolveErr != nil {return nil, resolveErr}+ if ensureErr := ensureReadableAssetLocal(absPath); ensureErr != nil {+ return nil, ensureErr+ }destPath, ok := copied[absPath]if !ok {diff --git a/kernel/model/cloud_service.go b/kernel/model/cloud_service.goindex 5ffa052682..3ead4e73ca 100644--- a/kernel/model/cloud_service.go+++ b/kernel/model/cloud_service.go@@ -128,6 +128,13 @@ func StartFreeTrial() (err error) {}func DeactivateUser() (err error) {+ release := lockAssetSourceChange()+ defer release()+ if Conf.Sync.Provider == conf.ProviderSiYuan {+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }+ }requestResult := gulu.Ret.NewResult()request := httpclient.NewCloudRequest30s()resp, err := request.@@ -338,6 +345,8 @@ func refreshAnnouncement() {}func RefreshUser(token string) (ret *conf.User, err error) {+ release := lockAssetSourceChange()+ defer release()previousUserID := ""if previousUser := Conf.GetUser(); nil != previousUser {previousUserID = previousUser.UserId@@ -348,6 +357,9 @@ func RefreshUser(token string) (ret *conf.User, err error) {if nil == user && "" != Conf.UserData {user = loadUserFromConf()if nil != user {+ if err = validateCloudUserAssetSource(user); err != nil {+ return nil, err+ }Conf.SetUser(user)if previousUserID != user.UserId {refreshLANSyncManager()@@ -378,7 +390,7 @@ Net:user, invalidUserName, invalid := resolveCloudUserRefresh(Conf.GetUser(), user, err)if err != nil {if invalid {- LogoutUser()+ logoutUser()util.BroadcastByType("main", "setCloudUser", 0, "", map[string]any{"user": nil,"userName": invalidUserName,@@ -388,6 +400,9 @@ Net:return user, err}+ if err = validateCloudUserAssetSource(user); err != nil {+ return Conf.GetUser(), err+ }Conf.SetUser(user)data, _ := gulu.JSON.MarshalJSON(user)Conf.UserData = util.AESEncrypt(string(data))@@ -406,6 +421,39 @@ Net:return user, nil}+type cloudAssetSourceError struct {+ cause error+}++func (err *cloudAssetSourceError) Error() string {+ return err.cause.Error()+}++func (err *cloudAssetSourceError) Unwrap() error {+ return err.cause+}++func IsCloudAssetSourceChange(err error) bool {+ var sourceErr *cloudAssetSourceError+ return errors.As(err, &sourceErr)+}++// 使用服务端返回的账号标识验证来源,允许过期登出后重新认证原账号。+func validateCloudUserAssetSource(user *conf.User) error {+ if Conf.Sync.Provider != conf.ProviderSiYuan {+ return nil+ }+ cloudConf, err := buildCloudConf()+ if err != nil {+ return &cloudAssetSourceError{cause: err}+ }+ cloudConf.UserID = user.UserId+ if err = validateAssetDownloadSourceScope(assetDownloadScope(Conf.Sync.Provider, cloudConf, Conf.Repo.Key)); err != nil {+ return &cloudAssetSourceError{cause: err}+ }+ return nil+}+func IsInvalidUserRefresh(err error) bool {return errors.Is(err, errInvalidUser)}@@ -665,7 +713,17 @@ func CheckActivationcode(code string) (retCode int, msg string) {}func Login(userName, password, captcha string, cloudRegion int) (ret *gulu.Result) {+ release := lockAssetSourceChange()+ defer release()previousCloudRegion := util.CurrentCloudRegion+ if Conf.Sync.Provider == conf.ProviderSiYuan && previousCloudRegion != cloudRegion {+ if err := requireCompleteAssetDownloads(); err != nil {+ ret = gulu.Ret.NewResult()+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ }Conf.CloudRegion = cloudRegionConf.Save()util.CurrentCloudRegion = cloudRegion@@ -764,6 +822,13 @@ func parseLogin2faResult(result map[string]any) (ret *gulu.Result, ok bool) {}func LogoutUser() {+ release := lockAssetSourceChange()+ defer release()+ logoutUser()+}++// 登出只清除登录凭据,资源来源仍由已认证的下载状态保存。+func logoutUser() {hadUser := nil != Conf.GetUser()Conf.UserData = ""Conf.SetUser(nil)diff --git a/kernel/model/cloud_service_asset_source_test.go b/kernel/model/cloud_service_asset_source_test.gonew file mode 100644index 0000000000..815868a66a--- /dev/null+++ b/kernel/model/cloud_service_asset_source_test.go@@ -0,0 +1,124 @@+package model++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/dejavu/cloud"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestCloudAssetSourceAllowsOriginalAccountAfterLogout(t *testing.T) {+ originalConf := Conf+ originalData, originalRepo, originalConfDir := util.DataDir, util.RepoDir, util.ConfDir+ originalHistory, originalTemp, originalRegion := util.HistoryDir, util.TempDir, util.CurrentCloudRegion+ t.Cleanup(func() {+ Conf = originalConf+ util.DataDir, util.RepoDir, util.ConfDir = originalData, originalRepo, originalConfDir+ util.HistoryDir, util.TempDir, util.CurrentCloudRegion = originalHistory, originalTemp, originalRegion+ })+ base := t.TempDir()+ remote := filepath.Join(base, "cloud")+ key := []byte("0123456789abcdef0123456789abcdef")+ owner := &conf.User{UserId: "asset-owner", UserName: "owner"}+ Conf = NewAppConf()+ Conf.Sync, Conf.Repo, Conf.System = conf.NewSync(), conf.NewRepo(), conf.NewSystem()+ Conf.Sync.Provider, Conf.Sync.CloudName, Conf.Sync.Enabled = conf.ProviderSiYuan, "main", true+ Conf.Sync.AssetDownloadMode = 1+ Conf.Repo.Key = key+ Conf.SetUser(owner)+ Conf.CloudRegion, util.CurrentCloudRegion = 0, 0+ deviceDir := filepath.Join(base, "partial")+ util.DataDir, util.RepoDir, util.ConfDir = filepath.Join(deviceDir, "data"), filepath.Join(deviceDir, "repo"), filepath.Join(deviceDir, "conf")+ util.HistoryDir, util.TempDir = filepath.Join(deviceDir, "history"), filepath.Join(deviceDir, "temp")+ cloudConf, err := buildCloudConf()+ if err != nil {+ t.Fatal(err)+ }+ scope := assetDownloadScope(conf.ProviderSiYuan, cloudConf, key)+ makeRepo := func(name string, onDemand bool) *dejavu.Repo {+ t.Helper()+ dir := filepath.Join(base, name)+ repoPath := filepath.Join(dir, "repo")+ backend := cloud.NewLocal(&cloud.BaseCloud{Conf: &cloud.Conf{Dir: "main", RepoPath: repoPath,+ AvailableSize: 1024 * 1024 * 1024, Local: &cloud.ConfLocal{Endpoint: remote}}})+ repo, createErr := dejavu.NewRepo(filepath.Join(dir, "data"), repoPath, filepath.Join(dir, "history"),+ filepath.Join(dir, "temp"), name, name, "windows", key, nil, backend)+ if createErr != nil {+ t.Fatal(createErr)+ }+ if createErr = os.MkdirAll(filepath.Join(dir, "data"), 0755); createErr != nil {+ t.Fatal(createErr)+ }+ if createErr = os.WriteFile(filepath.Join(dir, "data", "seed.txt"), []byte("seed"), 0644); createErr != nil {+ t.Fatal(createErr)+ }+ if _, createErr = repo.Index("seed", true, nil); createErr != nil {+ t.Fatal(createErr)+ }+ if createErr = repo.ConfigureAssetDownloads(onDemand, filepath.Join(dir, "conf", "asset-downloads.json"), scope); createErr != nil {+ t.Fatal(createErr)+ }+ return repo+ }+ full := makeRepo("full", false)+ if err = os.MkdirAll(filepath.Join(base, "full", "data", "assets"), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(base, "full", "data", "assets", "remote.bin"), []byte("remote asset"), 0644); err != nil {+ t.Fatal(err)+ }+ if _, err = full.Index("asset", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = full.Sync(nil); err != nil {+ t.Fatal(err)+ }+ partial := makeRepo("partial", true)+ if _, _, err = partial.Sync(nil); err != nil {+ t.Fatal(err)+ }+ deferred, err := DeferredSyncAssets()+ if err != nil || len(deferred) != 1 {+ t.Fatalf("expected an undownloaded asset: %v, %v", deferred, err)+ }+ LogoutUser()+ if Conf.GetUser() != nil {+ t.Fatal("logout retained the cloud session")+ }+ if err = validateCloudUserAssetSource(owner); err != nil {+ t.Fatalf("original account cannot authenticate after logout: %v", err)+ }+ if err = validateCloudUserAssetSource(&conf.User{UserId: "different-owner"}); !IsCloudAssetSourceChange(err) {+ t.Fatalf("different account accepted despite undownloaded data: %v", err)+ }+ if snapshots, _, _, snapshotErr := GetRepoSnapshots(1); snapshotErr != nil || len(snapshots) == 0 {+ t.Fatalf("local snapshots unavailable after logout: %v, %v", snapshots, snapshotErr)+ }+ if err = checkAssetDownloadAccess(); err == nil {+ t.Fatal("cloud asset downloads accepted without a cloud session")+ }+ result := Login("different-owner", "unused-password", "", 1)+ if result.Code == 0 || Conf.CloudRegion != 0 || util.CurrentCloudRegion != 0 {+ t.Fatalf("cross-region login changed the source: result=%v, region=%d", result, util.CurrentCloudRegion)+ }+ if err = DeactivateUser(); err == nil {+ t.Fatal("account deactivation accepted despite undownloaded data")+ }+ if err = os.Rename(assetDownloadStatePath(), assetDownloadStatePath()+".saved"); err != nil {+ t.Fatal(err)+ }+ if err = validateCloudUserAssetSource(owner); !IsCloudAssetSourceChange(err) {+ t.Fatalf("missing asset state was accepted during authentication: %v", err)+ }+ result = Login("different-owner", "unused-password", "", 1)+ if result.Code == 0 || Conf.CloudRegion != 0 || util.CurrentCloudRegion != 0 {+ t.Fatalf("cross-region login discarded a source with missing state: %v", result)+ }+ if _, err = os.Stat(filepath.Join(util.RepoDir, "asset-downloads-v1")); err != nil {+ t.Fatalf("missing-state protection removed the repository marker: %v", err)+ }+}diff --git a/kernel/model/encrypted_export.go b/kernel/model/encrypted_export.goindex 43507f9595..ba31057580 100644--- a/kernel/model/encrypted_export.go+++ b/kernel/model/encrypted_export.go@@ -224,8 +224,21 @@ func AcquireExportArtifactLease(exportPath string) (lease *ExportArtifactLease,if resolveErr != nil {return nil, resolveErr}+ if ensureErr := EnsureAssetLocal(artifact); ensureErr != nil {+ return nil, ensureErr+ }return registerMobileExportLease("", artifact, filepath.Base(artifact), "")}+ if !IsBoxUnlocked(boxID) {+ return nil, errors.New(Conf.Language(314))+ }+ artifact, resolveErr := GetAssetAbsPathInBox(relativePath, boxID)+ if resolveErr != nil {+ return nil, resolveErr+ }+ if ensureErr := EnsureAssetLocal(artifact); ensureErr != nil {+ return nil, ensureErr+ }if err = AcquireEncryptedBoxOperation(boxID); err != nil {return nil, err@@ -242,10 +255,6 @@ func AcquireExportArtifactLease(exportPath string) (lease *ExportArtifactLease,if dekErr != nil {return nil, dekErr}- artifact, resolveErr := GetAssetAbsPathInBox(relativePath, boxID)- if resolveErr != nil {- return nil, resolveErr- }diskName := filepath.Base(relativePath)leaseID, idErr := newManagedEncryptedExportID()if idErr != nil {diff --git a/kernel/model/export.go b/kernel/model/export.goindex 1a4e60a8fb..78529e963e 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -159,6 +159,9 @@ func getAttrViewCSVRenderedValue(table *av.Table, value *av.Value) (ret string,}func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {+ if err = prepareExportBlockAssets(blockID, false); err != nil {+ return+ }// Database block supports export as CSV https://github.com/siyuan-note/siyuan/issues/10072err = withExportReadLockByBlockID(blockID, func() error {@@ -367,6 +370,8 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {targetAbsPath := filepath.Join(exportFolder, AssetPathWithoutQuery(asset))if copyErr := copyAssetDecryptIfEncrypted(srcAbsPath, targetAbsPath); copyErr != nil {logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, copyErr)+ f.Close()+ return copyErr}}@@ -402,6 +407,9 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {}func Export2Liandi(id string) (err error) {+ if err = prepareExportBlockAssets(id, false); err != nil {+ return+ }err = withExportReadLockByBlockID(id, func() error {tree, loadErr := LoadTreeByBlockID(id)if loadErr != nil {@@ -690,6 +698,9 @@ func ExportSYs(ids []string) (zipPath string) {}func ExportDataInFolder(exportFolder string) (name string, err error) {+ if err = EnsureAllSyncAssets(); err != nil {+ return+ }util.PushEndlessProgress(Conf.Language(65))defer util.ClearPushProgress(100)@@ -760,6 +771,9 @@ func ExportData() (zipPath string, err error) {func exportData(exportFolder string) (zipPath string, err error) {FlushTxQueue()+ if err = EnsureAllSyncAssets(); err != nil {+ return+ }logging.LogInfof("exporting data...")@@ -808,6 +822,17 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath stif detectErr != nil {return "", detectErr}+ if encryptedBoxID != "" && !IsBoxUnlocked(encryptedBoxID) {+ return "", errors.New(Conf.Language(314))+ }+ for _, resourcePath := range resourcePaths {+ source := filepath.Join(util.WorkspaceDir, resourcePath)+ if gulu.File.IsSubPath(util.DataDir, source) {+ if err = EnsureAssetPrefixLocal(source); err != nil {+ return+ }+ }+ }exportBasePath := filepath.Join(util.TempDir, "export")if encryptedBoxID != "" {@@ -1068,6 +1093,9 @@ func ExportPreview(id string, fillCSSVar bool, accessChecker ...EmbedBlockAccess}func ExportDocx(id, savePath string, removeAssets, merge bool, mergeHeadingOptions ...MergeHeadingOptions) (fullPath string, err error) {+ if err = prepareExportBlockAssets(id, merge); err != nil {+ return+ }err = withExportReadLockByBlockID(id, func() error {pandocRuntime := util.GetPandocRuntime()if !util.IsValidPandocBin(pandocRuntime.BinPath) {@@ -1090,7 +1118,10 @@ func ExportDocx(id, savePath string, removeAssets, merge bool, mergeHeadingOptioreturn mkdirErr}defer os.RemoveAll(tmpDir)- name, content := ExportMarkdownHTML(id, tmpDir, true, merge, mergeHeadingOptions...)+ name, content, exportErr := exportMarkdownHTML(id, tmpDir, true, merge, mergeHeadingOptions...)+ if exportErr != nil {+ return exportErr+ }content = strings.ReplaceAll(content, " \n", "<br>\n")tmpDocxPath := filepath.Join(tmpDir, name+".docx")@@ -1146,14 +1177,31 @@ func ExportDocx(id, savePath string, removeAssets, merge bool, mergeHeadingOptio}return nil})+ if err != nil {+ fullPath = ""+ }return}func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptions ...MergeHeadingOptions) (name, dom string) {- if exportErr := withExportReadLockByBlockID(id, func() error {+ if err := prepareExportBlockAssets(id, merge); err != nil {+ util.PushErrMsg(err.Error(), 7000)+ return+ }+ name, dom, err := exportMarkdownHTML(id, savePath, docx, merge, mergeHeadingOptions...)+ if err != nil {+ logging.LogErrorf("export markdown html [%s] failed: %s", id, err)+ util.PushErrMsg(err.Error(), 7000)+ return "", ""+ }+ return name, dom+}++func exportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptions ...MergeHeadingOptions) (name, dom string, err error) {+ err = withExportReadLockByBlockID(id, func() error {bt := getExportBlockTree(id)if nil == bt {- return nil+ return ErrBlockNotFound}tree := prepareExportTree(bt)@@ -1163,7 +1211,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptiotree, mergeErr = mergeSubDocs(tree, mergeHeadingOptionsOrDefault(mergeHeadingOptions), Conf.Export.AddTitle)if nil != mergeErr {logging.LogErrorf("merge sub docs failed: %s", mergeErr)- return nil+ return mergeErr}}@@ -1183,7 +1231,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptioif err := os.MkdirAll(savePath, 0755); err != nil {logging.LogErrorf("mkdir [%s] failed: %s", savePath, err)- return nil+ return err}if docx {@@ -1204,6 +1252,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptiotargetAbsPath := filepath.Join(savePath, AssetPathWithoutQuery(asset))if err = copyAssetDecryptIfEncrypted(srcAbsPath, targetAbsPath); err != nil {logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err)+ return err}}@@ -1229,7 +1278,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptioappearancePath, readErr = filepath.EvalSymlinks(util.AppearancePath)if nil != readErr {logging.LogErrorf("readlink [%s] failed: %s", util.AppearancePath, readErr)- return nil+ return readErr}}@@ -1238,7 +1287,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptioto := filepath.Join(savePath, "appearance", src)if err := filelock.Copy(from, to); err != nil {logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err)- return nil+ return err}}@@ -1250,7 +1299,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptiotoIconDir := filepath.Join(savePath, "appearance", "icons", "litheness")if err := os.MkdirAll(toIconDir, 0755); err != nil {logging.LogErrorf("mkdir [%s] failed: %s", toIconDir, err)- return nil+ return err}toIconFile := filepath.Join(toIconDir, "icon.js")if err := filelock.Copy(srcIconFile, toIconFile); err != nil {@@ -1263,7 +1312,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptiotoIconDir := filepath.Join(savePath, "appearance", "icons", iconName)if err := os.MkdirAll(toIconDir, 0755); err != nil {logging.LogErrorf("mkdir [%s] failed: %s", toIconDir, err)- return nil+ return err}toIconFile := filepath.Join(toIconDir, "icon.js")if err := filelock.Copy(srcIconFile, toIconFile); err != nil {@@ -1323,9 +1372,9 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptiodom = luteEngine.ProtylePreview(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)}return nil- }); exportErr != nil {- logging.LogErrorf("export markdown html [%s] failed: %s", id, exportErr)- return+ })+ if err != nil {+ return "", "", err}return}@@ -1336,12 +1385,16 @@ func ExportHTML(id, savePath string, pdf, keepFold, merge bool, mergeHeadingOptifunc ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle bool, customTitle string,mergeHeadingOptions ...MergeHeadingOptions) (name, dom string, node *ast.Node) {+ if err := prepareExportBlockAssets(id, merge); err != nil {+ util.PushErrMsg(err.Error(), 7000)+ return+ }if exportErr := withExportReadLockByBlockID(id, func() error {savePath = strings.TrimSpace(savePath)bt := getExportBlockTree(id)if nil == bt {- return nil+ return ErrBlockNotFound}tree := prepareExportTree(bt)@@ -1355,7 +1408,7 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle bootree, mergeErr = mergeSubDocs(tree, mergeHeadingOptionsOrDefault(mergeHeadingOptions), addTitle)if nil != mergeErr {logging.LogErrorf("merge sub docs failed: %s", mergeErr)- return nil+ return mergeErr}}@@ -1391,7 +1444,7 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle booif "" != savePath {if err := os.MkdirAll(savePath, 0755); err != nil {logging.LogErrorf("mkdir [%s] failed: %s", savePath, err)- return nil+ return err}assets := getAssetsLinkDests(tree.Root, false)@@ -1404,6 +1457,7 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle bootargetAbsPath := filepath.Join(savePath, AssetPathWithoutQuery(asset))if err = copyAssetDecryptIfEncrypted(srcAbsPath, targetAbsPath); err != nil {logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err)+ return err}}}@@ -1415,7 +1469,7 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle booto := filepath.Join(savePath, src)if err := filelock.Copy(from, to); err != nil {logging.LogErrorf("copy stage from [%s] to [%s] failed: %s", from, savePath, err)- return nil+ return err}}@@ -1432,7 +1486,7 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle booappearancePath, readErr = filepath.EvalSymlinks(util.AppearancePath)if nil != readErr {logging.LogErrorf("readlink [%s] failed: %s", util.AppearancePath, readErr)- return nil+ return readErr}}for _, src := range srcs {@@ -1451,7 +1505,7 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle bootoIconDir := filepath.Join(savePath, "appearance", "icons", "litheness")if err := os.MkdirAll(toIconDir, 0755); err != nil {logging.LogErrorf("mkdir [%s] failed: %s", toIconDir, err)- return nil+ return err}toIconFile := filepath.Join(toIconDir, "icon.js")if err := filelock.Copy(srcIconFile, toIconFile); err != nil {@@ -1464,7 +1518,7 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle bootoIconDir := filepath.Join(savePath, "appearance", "icons", iconName)if err := os.MkdirAll(toIconDir, 0755); err != nil {logging.LogErrorf("mkdir [%s] failed: %s", toIconDir, err)- return nil+ return err}toIconFile := filepath.Join(toIconDir, "icon.js")if err := filelock.Copy(srcIconFile, toIconFile); err != nil {@@ -1503,7 +1557,8 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle booreturn nil}); exportErr != nil {logging.LogErrorf("export html [%s] failed: %s", id, exportErr)- return+ util.PushErrMsg(exportErr.Error(), 7000)+ return "", "", nil}return}@@ -1605,6 +1660,9 @@ func processIFrameWithFilter(tree *parse.Tree, filter func(src string) bool) {}func ProcessPDF(id, p string, merge, removeAssets, watermark bool, mergeHeadingOptions ...MergeHeadingOptions) (err error) {+ if err = prepareExportBlockAssets(id, merge); err != nil {+ return+ }err = withExportReadLockByBlockID(id, func() error {tree, _ := LoadTreeByBlockID(id)if nil == tree {@@ -1937,7 +1995,7 @@ func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, boxIDembedPath := absPathif IsEncryptedAssetPath(absPath) {assetBoxID := ExtractBoxIDFromAssetsPath(absPath)- plain, readErr := ReadAssetBytesInBox(assetBoxID, sourceURI)+ plain, readErr := readAssetBytesInBox(assetBoxID, sourceURI, false)if nil != readErr {logging.LogWarnf("read encrypted asset [%s] failed: %s", sourceURI, readErr)continue@@ -2530,6 +2588,10 @@ func exportBoxSYZip(boxID string) (zipPath string) {func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, includeBoxConf bool) (zipPath string) {defer util.ClearPushProgress(100)+ if err := prepareExportAssets(boxID, docPaths); err != nil {+ util.PushErrMsg(err.Error(), 7000)+ return+ }dir, name := path.Split(baseFolderName)name = util.FilterFileName(name)@@ -2722,7 +2784,8 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, iassetErr := copyAssetDecryptIfEncrypted(srcPath, destPath)if nil != assetErr {logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, assetErr)- continue+ util.PushErrMsg(assetErr.Error(), 7000)+ return}copiedAssets.Add(copyKey)@@ -2788,7 +2851,10 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, icontinue}- exportAv(avID, avBoxes[avID], exportStorageAvDir, exportDir, assetPathMap)+ if exportErr := exportAv(avID, avBoxes[avID], exportStorageAvDir, exportDir, assetPathMap); exportErr != nil {+ util.PushErrMsg(exportErr.Error(), 7000)+ return+ }}if !IsEncryptedBox(box.ID) {@@ -2881,6 +2947,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, iif err = zip.Close(); err != nil {logging.LogErrorf("close export .sy.zip failed: %s", err)+ return ""}if err = os.Rename(zipPartialPath, zipPath); err != nil {logging.LogErrorf("publish export .sy.zip [%s] failed: %s", zipPath, err)@@ -2896,44 +2963,47 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, ireturn}-func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap map[string]string) {+func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap map[string]string) error {// 用 box-aware 路径解析 + 自动解密读取 AV 定义明文(加密笔记本的 AV 在 <boxID>/storage/av/,// GetAttributeViewDataPath 只查全局路径会漏;filelock.Copy 会拷密文)。avData, readErr := av.ReadAttributeViewDataInBox(avID, boxID)if readErr != nil {logging.LogErrorf("read attribute view [%s] failed: %s", avID, readErr)- return+ return readErr}if boxID != "" && avData != nil {avData, readErr = rewriteAttributeViewDataAssetReferences(avData, assetReferenceRewriteOptions{rewriteUnmapped: true})if readErr != nil {logging.LogErrorf("rewrite exported attribute view assets [%s] failed: %s", avID, readErr)- return+ return readErr}}if avData != nil {if mkdirErr := os.MkdirAll(exportStorageAvDir, 0755); mkdirErr != nil {logging.LogErrorf("create export av folder [%s] failed: %s", exportStorageAvDir, mkdirErr)- return+ return mkdirErr}if writeErr := os.WriteFile(filepath.Join(exportStorageAvDir, avID+".json"), avData, 0644); writeErr != nil {logging.LogErrorf("write av json failed: %s", writeErr)+ return writeErr}}attrView, parseErr := av.ParseAttributeViewInBox(avID, boxID)if parseErr != nil {logging.LogErrorf("parse attribute view [%s] failed: %s", avID, parseErr)- return+ return parseErr}- copyExportAttributeViewAssets(attrView, boxID, exportFolder, assetPathMap)+ if err := copyExportAttributeViewAssets(attrView, boxID, exportFolder, assetPathMap); err != nil {+ return err+ }// 级联导出关联列关联的数据库- exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder, assetPathMap)+ return exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder, assetPathMap)}-func copyExportAttributeViewAssets(attrView *av.AttributeView, boxID, exportFolder string, assetPathMap map[string]string) {+func copyExportAttributeViewAssets(attrView *av.AttributeView, boxID, exportFolder string, assetPathMap map[string]string) error {// 导出资源文件列、指向本地资源的 URL 列和富文本中的本地资源 https://github.com/siyuan-note/siyuan/issues/9919for _, assetPath := range getAttributeViewAssetsLinkDests(attrView, false, nil) {destPath := filepath.Join(exportFolder, AssetPathWithoutQuery(assetPath))@@ -2951,11 +3021,13 @@ func copyExportAttributeViewAssets(attrView *av.AttributeView, boxID, exportFoldif copyErr := copyAssetDecryptIfEncrypted(srcPath, destPath); nil != copyErr {logging.LogErrorf("copy asset failed: %s", copyErr)+ return copyErr}}+ return nil}-func exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap map[string]string) {+func exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap map[string]string) error {avIDs := hashset.New()walkRelationAvs(avID, boxID, avIDs)@@ -2989,8 +3061,11 @@ func exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder string, asslogging.LogErrorf("parse relation attribute view [%s] failed: %s", relAvID, parseErr)continue}- copyExportAttributeViewAssets(attrView, boxID, exportFolder, assetPathMap)+ if err := copyExportAttributeViewAssets(attrView, boxID, exportFolder, assetPathMap); err != nil {+ return err+ }}+ return nil}func walkRelationAvs(avID, boxID string, exportAvIDs *hashset.Set) {@@ -4270,6 +4345,10 @@ func exportPandocConvertZip(boxID, baseFolderName string, docPaths, defBlockIDsfunc exportPandocConvertZip0(boxID, baseFolderName string, docPaths, defBlockIDs []string, pandocFrom, pandocTo, ext string,boxPaths map[string]string) (zipPath string) {defer util.ClearPushProgress(100)+ if err := prepareExportAssets(boxID, docPaths); err != nil {+ util.PushErrMsg(err.Error(), 7000)+ return+ }dir, name := path.Split(baseFolderName)name = util.FilterFileName(name)@@ -4394,7 +4473,8 @@ func exportPandocConvertZip0(boxID, baseFolderName string, docPaths, defBlockIDsdestPath := filepath.Join(writeFolder, cleanNewAsset)if copyErr := copyAssetDecryptIfEncrypted(srcPath, destPath); copyErr != nil {logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, copyErr)- continue+ util.PushErrMsg(copyErr.Error(), 7000)+ return}}@@ -4453,6 +4533,7 @@ func exportPandocConvertZip0(boxID, baseFolderName string, docPaths, defBlockIDsif err = zip.Close(); err != nil {logging.LogErrorf("close export markdown zip failed: %s", err)+ return ""}if err = os.Rename(zipPartialPath, zipPath); err != nil {logging.LogErrorf("publish export markdown zip [%s] failed: %s", zipPath, err)diff --git a/kernel/model/export_asset_test.go b/kernel/model/export_asset_test.goindex 4447de828c..ff90ce5c50 100644--- a/kernel/model/export_asset_test.go+++ b/kernel/model/export_asset_test.go@@ -17,13 +17,63 @@package modelimport (+ "os"+ "path/filepath"+ "strings""testing""github.com/88250/lute/ast""github.com/88250/lute/parse""github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/util")+func TestExportAssetCopyFailureReturnsNoOutput(t *testing.T) {+ fixture := setupFileOperationTest(t)+ originalWorkspaceDir := util.WorkspaceDir+ util.WorkspaceDir = filepath.Dir(util.DataDir)+ t.Cleanup(func() { util.WorkspaceDir = originalWorkspaceDir })+ Conf.Editor = conf.NewEditor()+ Conf.Export = conf.NewExport()+ Conf.Appearance = conf.NewAppearance()+ Conf.Search = conf.NewSearch()+ Conf.System = conf.NewSystem()+ assetPath := "assets/export-20260905000000-abcdefg.html"+ absPath := filepath.Join(util.DataDir, assetPath)+ if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(absPath, []byte("asset content"), 0644); err != nil {+ t.Fatal(err)+ }+ tree := addFileOperationTestDoc(t, fixture, "20260905000001-abcdefg", "Export copy failure", false)+ tree.Root.AppendChild(&ast.Node{Type: ast.NodeIFrame, Tokens: []byte(`<iframe src="` + assetPath + `"></iframe>`)})+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }++ savePath := t.TempDir()+ if err := os.WriteFile(filepath.Join(savePath, "assets"), []byte("blocks asset directory"), 0644); err != nil {+ t.Fatal(err)+ }+ for _, docx := range []bool{false, true} {+ name, dom, err := exportMarkdownHTML(tree.ID, savePath, docx, false)+ if err == nil || !strings.Contains(err.Error(), "assets") {+ t.Fatalf("expected asset copy failure for docx=%v, got %v", docx, err)+ }+ if name != "" || dom != "" {+ t.Fatalf("failed markdown HTML export returned output: name=%q, dom=%q", name, dom)+ }+ }+ if name, dom := ExportMarkdownHTML(tree.ID, savePath, false, false); name != "" || dom != "" {+ t.Fatalf("failed public markdown HTML export returned output: name=%q, dom=%q", name, dom)+ }+ if name, dom, node := ExportHTMLWithTitle(tree.ID, savePath, false, false, false, false, ""); name != "" || dom != "" || node != nil {+ t.Fatalf("failed HTML export returned output: name=%q, dom=%q, node=%v", name, dom, node)+ }+}+func TestResolveExportAssetPaths(t *testing.T) {const (imageAsset = "assets/image%20file-20260724150608-42z1qwz.png"diff --git a/kernel/model/file.go b/kernel/model/file.goindex 23c64bf3ca..24be6de880 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1923,6 +1923,9 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEnginmoveToRoot := "/" == toPathtoBlockID := tree.IDfromFolder := path.Join(path.Dir(fromPath), tree.ID)+ if err = EnsureAssetPrefixLocal(filepath.Join(util.DataDir, fromBox.ID, fromFolder)); err != nil {+ return+ }toFolder := "/"if moveToRoot {refresh.addNotebook(toBox.ID)@@ -2118,6 +2121,12 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) (ret *parse.Tree, errif err != nil || nil == ret {return nil, ErrBlockNotFound}+ if !IsEncryptedBox(box.ID) {+ assetParent := filepath.Dir(filepath.Join(util.DataDir, box.ID, p))+ if err = EnsureAssetPrefixLocal(assetParent); err != nil {+ return nil, err+ }+ }historyDir, err := getHistoryDir(HistoryOpDelete)if err != nil {@@ -2135,7 +2144,9 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) (ret *parse.Tree, errgenerateAvHistoryInTree(ret, historyDir)// 加密笔记本的 assets 不提升到全局if !IsEncryptedBox(box.ID) {- copyDocAssetsToDataAssets(box.ID, p)+ if err = copyDocAssetsToDataAssets(box.ID, p); err != nil {+ return nil, err+ }}removeIDs := treenode.RootChildIDs(ret.ID)diff --git a/kernel/model/lan_sync.go b/kernel/model/lan_sync.goindex 052bbc0782..0efe7e174a 100644--- a/kernel/model/lan_sync.go+++ b/kernel/model/lan_sync.go@@ -242,7 +242,14 @@ func RefreshLANSyncNetwork() {}func newSyncRepository() (ret *dejavu.Repo, err error) {- ret, err = newRepository()+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()+ return newSyncRepositoryWithAssetSourceLocked()+}++// newSyncRepositoryWithAssetSourceLocked 在来源锁保护下创建带局域网分块来源的仓库。+func newSyncRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {+ ret, err = newRepositoryWithAssetSourceLocked()if nil != err {return}diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex fea0e05049..17cd30eab1 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -239,6 +239,11 @@ func RemoveBox(boxID string) (err error) {// 删目录前固定加密状态,确保后续历史、资源和索引清理始终使用同一个安全边界。isEncrypted := IsEncryptedBox(boxID)+ if !isUserGuide {+ if err = EnsureAssetPrefixLocal(localPath); err != nil {+ return+ }+ }if isEncrypted {// 加密索引先持有生命周期租约再获取索引锁,因此删除也必须先结束生命周期,保持锁顺序一致。unmount0(boxID)@@ -273,7 +278,9 @@ func RemoveBox(boxID string) (err error) {// 加密笔记本的 assets 不提升到全局 data/assets,避免密文污染全局或被全局索引if !isEncrypted {- copyBoxAssetsToDataAssets(boxID)+ if err = copyBoxAssetsToDataAssets(boxID); err != nil {+ return+ }}}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex d313db885f..355ef39dd9 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -80,6 +80,8 @@ var ()func autoPurgeRepo(cron bool) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()if cron && !autoPurgeRepoAfterFirstSync {return}@@ -96,7 +98,7 @@ func autoPurgeRepo(cron bool) {return}- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -203,17 +205,7 @@ func GetRepoFile(fileID string) (ret []byte, p string, err error) {return}- repo, err := newRepository()- if err != nil {- return- }-- file, err := repo.GetFile(fileID)- if err != nil {- return- }-- ret, err = repo.OpenFile(file)+ ret, file, err := readRepoFileWithAssets(fileID)if err != nil {return}@@ -253,17 +245,7 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {return}- repo, err := newRepository()- if err != nil {- return- }-- file, err := repo.GetFile(fileID)- if err != nil {- return- }-- data, err := repo.OpenFile(file)+ data, file, err := readRepoFileWithAssets(fileID)if err != nil {return}@@ -278,7 +260,7 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {// 回滚快照时默认为当前数据创建一个快照// When rolling back a snapshot, a snapshot is created for the current data by default https://github.com/siyuan-note/siyuan/issues/12470FlushTxQueue()- _, err = repo.Index("Backup before checkout", false, map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})+ _, err = IndexRepo("Backup before checkout")if err != nil {logging.LogErrorf("index repository failed: %s", err)util.PushClearProgress()@@ -400,17 +382,7 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText breturn}- repo, err := newRepository()- if err != nil {- return- }-- file, err := repo.GetFile(fileID)- if err != nil {- return- }-- data, err := repo.OpenFile(file)+ data, file, err := readRepoFileWithAssets(fileID)if err != nil {return}@@ -889,17 +861,7 @@ func ExportRepoFile(id string) (exportPath string, err error) {return}- repo, err := newRepository()- if err != nil {- return- }-- file, err := repo.GetFile(id)- if err != nil {- return- }-- data, err := repo.OpenFile(file)+ data, file, err := readRepoFileWithAssets(id)if err != nil {return}@@ -1016,7 +978,8 @@ func ExportRepoFile(id string) (exportPath string, err error) {type Snapshot struct {*dejavu.Log- TypesCount []*TypeCount `json:"typesCount"`+ TypesCount []*TypeCount `json:"typesCount"`+ RequiresDownload bool `json:"requiresDownload"`}type TypeCount struct {@@ -1056,12 +1019,21 @@ func GetRepoSnapshots(page int) (ret []*Snapshot, pageCount, totalCount int, err}func buildSnapshots(logs []*dejavu.Log) (ret []*Snapshot) {+ chunkAvailability := map[string]bool{}for _, l := range logs {typesCount := statTypesByPath(l.Files)+ requiresDownload := false+ for _, file := range l.Files {+ if repoFileNeedsDownloadWithCache(file, chunkAvailability) {+ requiresDownload = true+ break+ }+ }l.Files = nil // 置空,否则返回前端数据量太大ret = append(ret, &Snapshot{- Log: l,- TypesCount: typesCount,+ Log: l,+ TypesCount: typesCount,+ RequiresDownload: requiresDownload,})}return@@ -1104,6 +1076,11 @@ func statTypesByPath(files []*entity.File) (ret []*TypeCount) {}func ImportRepoKey(base64Key string) (retKey string, err error) {+ release := lockAssetSourceChange()+ defer release()+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }util.PushMsg(Conf.Language(136), 3000)retKey = gulu.Str.RemoveInvisible(base64Key)@@ -1121,6 +1098,9 @@ func ImportRepoKey(base64Key string) (retKey string, err error) {if 32 != len(key) {return "", errors.New(Conf.Language(157))}+ if err = clearAssetDownloadState(); err != nil {+ return+ }suspendLANSyncManager()Conf.Repo.Key = key@@ -1134,21 +1114,30 @@ func ImportRepoKey(base64Key string) (retKey string, err error) {return}+ release()initDataRepo()refreshLANSyncManager()return}func ResetRepo() (err error) {+ release := lockAssetSourceChange()+ defer release()+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }logging.LogInfof("resetting data repo...")msgId := util.PushMsg(Conf.Language(144), 1000*60)suspendLANSyncManager()- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}+ if err = repo.ClearAssetDownloadState(); err != nil {+ return+ }if err = repo.Reset(); err != nil {logging.LogErrorf("reset data repo failed: %s", err)return@@ -1166,11 +1155,16 @@ func ResetRepo() (err error) {}func PurgeCloud() (err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }msg := Conf.Language(223)util.PushEndlessProgress(msg)defer util.PushClearProgress()- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -1189,11 +1183,13 @@ func PurgeCloud() (err error) {}func PurgeRepo() (err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()msg := Conf.Language(202)util.PushEndlessProgress(msg)defer util.PushClearProgress()- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -1212,11 +1208,19 @@ func PurgeRepo() (err error) {}func InitRepoKeyFromPassphrase(passphrase string) (err error) {+ release := lockAssetSourceChange()+ defer release()+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }passphrase = gulu.Str.RemoveInvisible(passphrase)passphrase = strings.TrimSpace(passphrase)if "" == passphrase {return errors.New(Conf.Language(142))}+ if err = clearAssetDownloadState(); err != nil {+ return+ }util.PushMsg(Conf.Language(136), 3000)suspendLANSyncManager()@@ -1246,12 +1250,21 @@ func InitRepoKeyFromPassphrase(passphrase string) (err error) {Conf.Save()logging.LogInfof("inited repo key [%x]", sha1.Sum(Conf.Repo.Key))+ release()initDataRepo()refreshLANSyncManager()return}func InitRepoKey() (err error) {+ release := lockAssetSourceChange()+ defer release()+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }+ if err = clearAssetDownloadState(); err != nil {+ return+ }util.PushMsg(Conf.Language(136), 3000)suspendLANSyncManager()@@ -1285,6 +1298,7 @@ func InitRepoKey() (err error) {Conf.Save()logging.LogInfof("inited repo key [%x]", sha1.Sum(Conf.Repo.Key))+ release()initDataRepo()refreshLANSyncManager()return@@ -1313,16 +1327,25 @@ func checkoutRepo(id string) {util.PushErrMsg(Conf.Language(26), 7000)return}+ FlushTxQueue()+ release := lockAssetSourceChange()+ defer release()- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {logging.LogErrorf("new repository failed: %s", err)util.PushErrMsg(Conf.Language(141), 7000)return}+ if err = ensureAllSyncAssets(); err == nil {+ err = ensureRepoSnapshotComplete(repo, id)+ }+ if err != nil {+ util.PushErrMsg(err.Error(), 7000)+ return+ }util.PushEndlessProgress(Conf.Language(63))- FlushTxQueue()CloseWatchAssets()defer WatchAssets()@@ -1344,7 +1367,6 @@ func checkoutRepo(id string) {// 回滚快照时默认为当前数据创建一个快照// When rolling back a snapshot, a snapshot is created for the current data by default https://github.com/siyuan-note/siyuan/issues/12470- FlushTxQueue()_, err = repo.Index("Backup before checkout", false, map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})if err != nil {logging.LogErrorf("index repository failed: %s", err)@@ -1361,6 +1383,7 @@ func checkoutRepo(id string) {return}+ release()FullReindexDirect()appendAgentRollbackEntries()time.Sleep(time.Second)@@ -1426,12 +1449,14 @@ func appendAgentRollbackEntries() {}func DownloadCloudSnapshot(tag, id string) (err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()if 1 > len(Conf.Repo.Key) {err = errors.New(Conf.Language(26))return}- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -1468,12 +1493,14 @@ func DownloadCloudSnapshot(tag, id string) (err error) {}func UploadCloudSnapshot(tag, id string) (err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()if 1 > len(Conf.Repo.Key) {err = errors.New(Conf.Language(26))return}- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -1509,12 +1536,14 @@ func UploadCloudSnapshot(tag, id string) (err error) {}func RemoveCloudRepoTag(tag string) (err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()if 1 > len(Conf.Repo.Key) {err = errors.New(Conf.Language(26))return}- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -1639,12 +1668,14 @@ func GetTagSnapshots() (ret []*Snapshot, err error) {}func RemoveTagSnapshot(tag string) (err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()if 1 > len(Conf.Repo.Key) {err = errors.New(Conf.Language(26))return}- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -1654,6 +1685,8 @@ func RemoveTagSnapshot(tag string) (err error) {}func TagSnapshot(id, name string) (err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()if 1 > len(Conf.Repo.Key) {err = errors.New(Conf.Language(26))return@@ -1671,7 +1704,7 @@ func TagSnapshot(id, name string) (err error) {return}- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -1701,19 +1734,31 @@ func IndexRepo(memo string) (id string, err error) {err = errors.New(Conf.Language(142))return}+ FlushTxQueue()+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()+ if err != nil {+ return+ }+ needsDownload, err := repo.NeedsAssetDownloadsForIndex()if err != nil {return}+ if needsDownload {+ if err = checkAssetDownloadAccess(); err != nil {+ return+ }+ }util.PushEndlessProgress(Conf.Language(143))start := time.Now()latest, _ := repo.Latest()- FlushTxQueue()index, err := repo.Index(memo, true, map[string]any{- eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress,+ eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress,+ dejavu.CtxAssetDownloadsAllowed: checkAssetDownloadAccess() == nil,})if err != nil {util.PushStatusBar("Index data repo failed: " + html.EscapeString(err.Error()))@@ -1959,6 +2004,11 @@ func bootSyncRepo() (err error) {util.PushErrMsg(msg, 0)return}+ preparedSourceConf, err := buildCloudConf()+ if err != nil {+ return+ }+ preparedSourceScope := assetDownloadScope(Conf.Sync.Provider, preparedSourceConf, Conf.Repo.Key)isBootSyncing.Store(true)@@ -2047,6 +2097,16 @@ func bootSyncRepo() (err error) {lockSync()defer unlockSync()+ currentSourceConf, sourceErr := buildCloudConf()+ if sourceErr != nil || preparedSourceScope != assetDownloadScope(Conf.Sync.Provider, currentSourceConf, Conf.Repo.Key) {+ logging.LogInfof("skip prepared boot sync after repository source changed")+ return+ }+ repo, repoErr := newSyncRepository()+ if repoErr != nil {+ logging.LogErrorf("reopen prepared boot repository failed: %s", repoErr)+ return+ }logging.LogInfof("syncing prepared boot data repo [device=%s, kernel=%s, provider=%d]", Conf.System.ID, KernelID, Conf.Sync.Provider)syncStart := time.Now()@@ -2801,6 +2861,13 @@ func indexRepoBeforeCloudSync(repo *dejavu.Repo) (beforeIndex, afterIndex *entit}func newRepository() (ret *dejavu.Repo, err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()+ return newRepositoryWithAssetSourceLocked()+}++// newRepositoryWithAssetSourceLocked 由已持有来源锁的调用方创建仓库,避免读写锁递归等待。+func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {cloudConf, err := buildCloudConf()if err != nil {return@@ -2838,6 +2905,17 @@ func newRepository() (ret *dejavu.Repo, err error) {logging.LogErrorf("init data repo failed: %s", err)return}+ scope := assetDownloadScope(Conf.Sync.Provider, cloudConf, Conf.Repo.Key)+ if Conf.Sync.Provider == conf.ProviderSiYuan && Conf.GetUser() == nil {+ stored, readErr := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Key)+ if readErr != nil {+ return nil, readErr+ }+ if stored != "" {+ scope = stored+ }+ }+ err = ret.ConfigureAssetDownloads(Conf.Sync.AssetDownloadMode == 1, assetDownloadStatePath(), scope)return}diff --git a/kernel/model/sync.go b/kernel/model/sync.goindex 49a7f3c2c7..b87001dd9a 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -98,8 +98,10 @@ func syncDataDownloadLocked() (err error) {}func getSyncCloudLatestID() (ret string) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()// 同步感知消息不包含云端提交 ID,需要先读取最新索引,以便和局域网提交提示使用同一个去重键。- repo, err := newSyncRepository()+ repo, err := newSyncRepositoryWithAssetSourceLocked()if nil != err {logging.LogWarnf("create repo before perceived sync failed: %s", err)return@@ -501,19 +503,24 @@ func upsertIndexes(upsertFilePaths []string) (upsertRootIDs []string) {return}-func SetCloudSyncDir(name string) {+func SetCloudSyncDir(name string) error {+ release := lockAssetSourceChange()+ defer release()if !cloud.IsValidCloudDirName(name) {- util.PushErrMsg(Conf.Language(37), 5000)- return+ return errors.New(Conf.Language(37))}if Conf.Sync.CloudName == name {- return+ return nil+ }+ if err := requireCompleteAssetDownloads(); err != nil {+ return err}Conf.Sync.CloudName = nameConf.Save()refreshLANSyncManager()+ return nil}func SetSyncGenerateConflictDoc(b bool) {@@ -562,6 +569,13 @@ func SetSyncMode(mode int) {}func SetSyncProvider(provider int) (err error) {+ release := lockAssetSourceChange()+ defer release()+ if provider != Conf.Sync.Provider {+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }+ }Conf.Sync.Provider = providerConf.Save()refreshLANSyncManager()@@ -569,6 +583,8 @@ func SetSyncProvider(provider int) (err error) {}func SetSyncProviderS3(s3 *conf.S3) (err error) {+ release := lockAssetSourceChange()+ defer release()s3.Endpoint = strings.TrimSpace(s3.Endpoint)s3.Endpoint = util.NormalizeEndpoint(s3.Endpoint)s3.AccessKey = strings.TrimSpace(s3.AccessKey)@@ -577,6 +593,12 @@ func SetSyncProviderS3(s3 *conf.S3) (err error) {s3.Region = strings.TrimSpace(s3.Region)s3.Timeout = util.NormalizeTimeout(s3.Timeout)s3.ConcurrentReqs = util.NormalizeConcurrentReqs(s3.ConcurrentReqs, conf.ProviderS3)+ if Conf.Sync.Provider == conf.ProviderS3 && (Conf.Sync.S3 == nil ||+ Conf.Sync.S3.Endpoint != s3.Endpoint || Conf.Sync.S3.Bucket != s3.Bucket) {+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }+ }Conf.Sync.S3 = s3Conf.Save()@@ -585,6 +607,8 @@ func SetSyncProviderS3(s3 *conf.S3) (err error) {}func SetSyncProviderWebDAV(webdav *conf.WebDAV) (err error) {+ release := lockAssetSourceChange()+ defer release()webdav.Endpoint = strings.TrimSpace(webdav.Endpoint)webdav.Endpoint = util.NormalizeEndpoint(webdav.Endpoint)@@ -598,6 +622,12 @@ func SetSyncProviderWebDAV(webdav *conf.WebDAV) (err error) {webdav.Password = strings.TrimSpace(webdav.Password)webdav.Timeout = util.NormalizeTimeout(webdav.Timeout)webdav.ConcurrentReqs = util.NormalizeConcurrentReqs(webdav.ConcurrentReqs, conf.ProviderWebDAV)+ if Conf.Sync.Provider == conf.ProviderWebDAV && (Conf.Sync.WebDAV == nil ||+ Conf.Sync.WebDAV.Endpoint != webdav.Endpoint || Conf.Sync.WebDAV.Username != webdav.Username) {+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }+ }Conf.Sync.WebDAV = webdavConf.Save()@@ -606,6 +636,8 @@ func SetSyncProviderWebDAV(webdav *conf.WebDAV) (err error) {}func SetSyncProviderLocal(local *conf.Local) (err error) {+ release := lockAssetSourceChange()+ defer release()local.Endpoint = strings.TrimSpace(local.Endpoint)local.Endpoint = util.NormalizeLocalPath(local.Endpoint)@@ -638,6 +670,12 @@ func SetSyncProviderLocal(local *conf.Local) (err error) {local.Timeout = util.NormalizeTimeout(local.Timeout)local.ConcurrentReqs = util.NormalizeConcurrentReqs(local.ConcurrentReqs, conf.ProviderLocal)+ if Conf.Sync.Provider == conf.ProviderLocal && (Conf.Sync.Local == nil ||+ filepath.Clean(Conf.Sync.Local.Endpoint) != filepath.Clean(local.Endpoint)) {+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }+ }Conf.Sync.Local = localConf.Save()@@ -656,6 +694,8 @@ var ()func CreateCloudSyncDir(name string) (err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()switch Conf.Sync.Provider {case conf.ProviderSiYuan, conf.ProviderLocal:break@@ -669,7 +709,7 @@ func CreateCloudSyncDir(name string) (err error) {return errors.New(Conf.Language(37))}- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -683,6 +723,13 @@ func CreateCloudSyncDir(name string) (err error) {}func RemoveCloudSyncDir(name string) (err error) {+ release := lockAssetSourceChange()+ defer release()+ if name == Conf.Sync.CloudName {+ if err = requireCompleteAssetDownloads(); err != nil {+ return+ }+ }switch Conf.Sync.Provider {case conf.ProviderSiYuan, conf.ProviderLocal:break@@ -693,7 +740,7 @@ func RemoveCloudSyncDir(name string) (err error) {msgId := util.PushMsg(Conf.Language(116), 15000)- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}@@ -715,11 +762,13 @@ func RemoveCloudSyncDir(name string) (err error) {}func ListCloudSyncDir() (syncDirs []*Sync, hSize string, err error) {+ assetDownloadSourceMu.RLock()+ defer assetDownloadSourceMu.RUnlock()syncDirs = []*Sync{}var dirs []*cloud.Repovar size int64- repo, err := newRepository()+ repo, err := newRepositoryWithAssetSourceLocked()if err != nil {return}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex fcb3b4af44..a43bdf1102 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -1786,6 +1786,10 @@ func (tx *Transaction) processGlobalAssets(tree *parse.Tree) {}// 只有全局 assets 才移动到相对 assets+ if !filelock.IsExist(assetPath) {+ // 未下载的资源保留全局引用,文档事务不触发网络请求。+ return ast.WalkContinue+ }targetP := filepath.Join(tx.assetsDir, filepath.Base(assetPath))if e = filelock.Rename(assetPath, targetP); e != nil {logging.LogErrorf("copy path of asset from [%s] to [%s] failed: %s", assetPath, targetP, e)diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 431cd15a7f..cb1ac4b53d 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -1056,6 +1056,18 @@ func serveAssets(ginServer *gin.Engine) {context.Status(http.StatusForbidden)return}+ if model.IsEncryptedAssetPath(p) && !model.IsBoxUnlocked(model.ExtractBoxIDFromAssetsPath(p)) {+ context.Status(http.StatusForbidden)+ return+ }+ if err = model.EnsureAssetLocal(p); err != nil {+ if os.IsNotExist(err) {+ context.Status(http.StatusNotFound)+ } else {+ context.String(http.StatusServiceUnavailable, "%s", err)+ }+ return+ }if heif.IsPath(p) {addHEIFVaryAccept(context)