mirror of
https://github.com/siyuan-note/siyuan.git
synced 2026-07-03 14:09:06 +02:00
Merge remote-tracking branch 'origin/dev' into dev
This commit is contained in:
@@ -1785,6 +1785,11 @@
|
||||
"285": "كلمة المرور غير صحيحة",
|
||||
"286": "[%s] تم التراجع عنه بالفعل",
|
||||
"287": "لا يمكن أن يحتوي رمز تفويض الوصول على مسافات فقط. إذا كنت تريد تعطيله، فيرجى مسح حقل الإدخال مباشرةً",
|
||||
"288": " (الافتراضي)"
|
||||
"288": " (الافتراضي)",
|
||||
"289": "تم التصدير إلى التنزيلات",
|
||||
"290": "فشل التصدير",
|
||||
"291": "الملف غير موجود أو فارغ",
|
||||
"292": "لا يمكن إنشاء الملف",
|
||||
"293": "لا يمكن كتابة الملف"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Passwort ist falsch",
|
||||
"286": "[%s] wurde bereits zurückgesetzt",
|
||||
"287": "Der Zugriffsautorisierungscode darf nicht nur aus Leerzeichen bestehen. Um ihn zu deaktivieren, leeren Sie das Eingabefeld direkt",
|
||||
"288": " (Standard)"
|
||||
"288": " (Standard)",
|
||||
"289": "In Downloads exportiert",
|
||||
"290": "Export fehlgeschlagen",
|
||||
"291": "Datei nicht gefunden oder leer",
|
||||
"292": "Datei kann nicht erstellt werden",
|
||||
"293": "Datei kann nicht geschrieben werden"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Password is incorrect",
|
||||
"286": "[%s] has already been rolled back",
|
||||
"287": "The access auth code cannot contain only spaces. To disable it, just clear the input box",
|
||||
"288": " (Default)"
|
||||
"288": " (Default)",
|
||||
"289": "Exported to Downloads",
|
||||
"290": "Export failed",
|
||||
"291": "File not found or empty",
|
||||
"292": "Cannot create file",
|
||||
"293": "Cannot write file"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "La contraseña es incorrecta",
|
||||
"286": "[%s] ya ha sido revertido",
|
||||
"287": "El código de autorización de acceso no puede contener solo espacios. Si desea desactivarlo, simplemente borre el cuadro de entrada",
|
||||
"288": " (Por defecto)"
|
||||
"288": " (Por defecto)",
|
||||
"289": "Exportado a Descargas",
|
||||
"290": "Error al exportar",
|
||||
"291": "Archivo no encontrado o vacío",
|
||||
"292": "No se puede crear el archivo",
|
||||
"293": "No se puede escribir el archivo"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Le mot de passe est incorrect",
|
||||
"286": "[%s] a déjà été restauré",
|
||||
"287": "Le code d'autorisation d'accès ne peut pas contenir uniquement des espaces. Pour le désactiver, effacez directement le champ de saisie",
|
||||
"288": " (Default)"
|
||||
"288": " (Default)",
|
||||
"289": "Exporté vers Téléchargements",
|
||||
"290": "Échec de l'exportation",
|
||||
"291": "Fichier introuvable ou vide",
|
||||
"292": "Impossible de créer le fichier",
|
||||
"293": "Impossible d'écrire le fichier"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "הסיסמה שגויה",
|
||||
"286": "[%s] כבר הוחזר",
|
||||
"287": "קוד אישור הגישה לא יכול להכיל רווחים בלבד. כדי להשבית אותו, יש לרוקן ישירות את שדה הקלט",
|
||||
"288": " (ברירת מחדל)"
|
||||
"288": " (ברירת מחדל)",
|
||||
"289": "יוצא להורדות",
|
||||
"290": "הייצוא נכשל",
|
||||
"291": "הקובץ לא נמצא או ריק",
|
||||
"292": "לא ניתן ליצור קובץ",
|
||||
"293": "לא ניתן לכתוב קובץ"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "पासवर्ड गलत है",
|
||||
"286": "[%s] पहले ही वापस रोल किया जा चुका है",
|
||||
"287": "एक्सेस प्राधिकरण कोड में केवल रिक्त स्थान नहीं हो सकते। इसे अक्षम करने के लिए, बस इनपुट बॉक्स साफ़ करें",
|
||||
"288": " (डिफ़ॉल्ट)"
|
||||
"288": " (डिफ़ॉल्ट)",
|
||||
"289": "डाउनलोड में निर्यात किया गया",
|
||||
"290": "निर्यात विफल",
|
||||
"291": "फ़ाइल नहीं मिली या खाली है",
|
||||
"292": "फ़ाइल नहीं बना सकते",
|
||||
"293": "फ़ाइल लिख नहीं सकते"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Kata sandi salah",
|
||||
"286": "[%s] telah diputar balik",
|
||||
"287": "Kode otorisasi akses tidak boleh hanya berisi spasi. Untuk menonaktifkannya, cukup kosongkan kotak input",
|
||||
"288": " (Default)"
|
||||
"288": " (Default)",
|
||||
"289": "Diekspor ke Unduhan",
|
||||
"290": "Ekspor gagal",
|
||||
"291": "File tidak ditemukan atau kosong",
|
||||
"292": "Tidak dapat membuat file",
|
||||
"293": "Tidak dapat menulis file"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "La password è errata",
|
||||
"286": "[%s] è già stato ripristinato",
|
||||
"287": "Il codice di autorizzazione di accesso non può contenere solo spazi. Per disabilitarlo, svuota direttamente il campo di input",
|
||||
"288": " (Predefinito)"
|
||||
"288": " (Predefinito)",
|
||||
"289": "Esportato in Download",
|
||||
"290": "Esportazione fallita",
|
||||
"291": "File non trovato o vuoto",
|
||||
"292": "Impossibile creare il file",
|
||||
"293": "Impossibile scrivere il file"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "パスワードが正しくありません",
|
||||
"286": "[%s] は既にロールバックされました",
|
||||
"287": "アクセス認証コードを空白だけにすることはできません。無効にする場合は、入力欄を直接空にしてください",
|
||||
"288": " (デフォルト)"
|
||||
"288": " (デフォルト)",
|
||||
"289": "ダウンロードにエクスポートしました",
|
||||
"290": "エクスポート失敗",
|
||||
"291": "ファイルが存在しないか空です",
|
||||
"292": "ファイルを作成できません",
|
||||
"293": "ファイルに書き込めません"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "비밀번호가 올바르지 않습니다",
|
||||
"286": "[%s] 이미 롤백되었습니다",
|
||||
"287": "액세스 인증 코드는 공백만 포함할 수 없습니다. 비활성화하려면 입력 칸을 직접 비우세요",
|
||||
"288": " (기본)"
|
||||
"288": " (기본)",
|
||||
"289": "다운로드로 내보내기 완료",
|
||||
"290": "내보내기 실패",
|
||||
"291": "파일이 없거나 비어 있습니다",
|
||||
"292": "파일을 만들 수 없습니다",
|
||||
"293": "파일에 쓸 수 없습니다"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Wachtwoord onjuist",
|
||||
"286": "[%s] is al teruggedraaid",
|
||||
"287": "Toegangscode mag niet alleen spaties bevatten",
|
||||
"288": " (Standaard)"
|
||||
"288": " (Standaard)",
|
||||
"289": "Geëxporteerd naar Downloads",
|
||||
"290": "Export mislukt",
|
||||
"291": "Bestand niet gevonden of leeg",
|
||||
"292": "Kan bestand niet aanmaken",
|
||||
"293": "Kan niet naar bestand schrijven"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Hasło jest nieprawidłowe",
|
||||
"286": "[%s] został cofnięty",
|
||||
"287": "Kod autoryzacji dostępu nie może składać się wyłącznie ze spacji. Aby go wyłączyć, po prostu wyczyść pole wprowadzania",
|
||||
"288": " (Domyślny)"
|
||||
"288": " (Domyślny)",
|
||||
"289": "Wyeksportowano do Pobrane",
|
||||
"290": "Eksport nie powiódł się",
|
||||
"291": "Plik nie znaleziony lub pusty",
|
||||
"292": "Nie można utworzyć pliku",
|
||||
"293": "Nie można zapisać pliku"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "A senha está incorreta",
|
||||
"286": "[%s] já foi revertido",
|
||||
"287": "O código de autorização de acesso não pode conter apenas espaços. Para desativá-lo, basta limpar o campo de entrada",
|
||||
"288": " (Padrão)"
|
||||
"288": " (Padrão)",
|
||||
"289": "Exportado para Downloads",
|
||||
"290": "Falha na exportação",
|
||||
"291": "Arquivo não encontrado ou vazio",
|
||||
"292": "Não foi possível criar o arquivo",
|
||||
"293": "Não foi possível gravar o arquivo"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Пароль неверный",
|
||||
"286": "[%s] уже откатён",
|
||||
"287": "Код авторизации доступа не может состоять только из пробелов. Чтобы отключить его, просто очистите поле ввода",
|
||||
"288": " (По умолчанию)"
|
||||
"288": " (По умолчанию)",
|
||||
"289": "Экспортировано в Загрузки",
|
||||
"290": "Ошибка экспорта",
|
||||
"291": "Файл не найден или пуст",
|
||||
"292": "Не удалось создать файл",
|
||||
"293": "Не удалось записать файл"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Nesprávne heslo",
|
||||
"286": "[%s] bol vrátený",
|
||||
"287": "Prístupový autorizačný kód nemôže obsahovať iba medzery. Ak ho chcete zakázať, jednoducho vymažte vstupné pole",
|
||||
"288": " (Predvolené)"
|
||||
"288": " (Predvolené)",
|
||||
"289": "Exportované do Prevzatia",
|
||||
"290": "Export zlyhal",
|
||||
"291": "Súbor nebol nájdený alebo je prázdny",
|
||||
"292": "Súbor sa nedá vytvoriť",
|
||||
"293": "Do súboru sa nedá zapísať"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "รหัสไม่ถูกต้อง",
|
||||
"286": "[%s] ย้อนกลับแล้ว",
|
||||
"287": "รหัสต้องไม่มีเฉพาะช่องว่าง",
|
||||
"288": " (ค่าเริ่มต้น)"
|
||||
"288": " (ค่าเริ่มต้น)",
|
||||
"289": "ส่งออกไปยังดาวน์โหลดแล้ว",
|
||||
"290": "การส่งออกล้มเหลว",
|
||||
"291": "ไม่พบไฟล์หรือไฟล์ว่างเปล่า",
|
||||
"292": "ไม่สามารถสร้างไฟล์ได้",
|
||||
"293": "ไม่สามารถเขียนไฟล์ได้"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Şifre yanlış",
|
||||
"286": "[%s] geri alındı",
|
||||
"287": "Erişim yetkilendirme kodu yalnızca boşluklardan oluşamaz. Devre dışı bırakmak için giriş kutusunu doğrudan temizleyin",
|
||||
"288": " (Varsayılan)"
|
||||
"288": " (Varsayılan)",
|
||||
"289": "İndirilenlere aktarıldı",
|
||||
"290": "Dışa aktarma başarısız",
|
||||
"291": "Dosya bulunamadı veya boş",
|
||||
"292": "Dosya oluşturulamadı",
|
||||
"293": "Dosyaya yazılamadı"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "Пароль неправильний",
|
||||
"286": "[%s] уже було відкотено",
|
||||
"287": "Код авторизації доступу не може складатися лише з пробілів. Щоб вимкнути його, просто очистьте поле введення",
|
||||
"288": " (Типово)"
|
||||
"288": " (Типово)",
|
||||
"289": "Експортовано в Завантаження",
|
||||
"290": "Помилка експорту",
|
||||
"291": "Файл не знайдено або порожній",
|
||||
"292": "Не вдалося створити файл",
|
||||
"293": "Не вдалося записати файл"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "密碼不正確",
|
||||
"286": "[%s] 已經回滾完畢",
|
||||
"287": "授權碼不能只包含空格。如需停用,請直接清空輸入框",
|
||||
"288": "(預設圖標)"
|
||||
"288": "(預設圖標)",
|
||||
"289": "已匯出到下載目錄",
|
||||
"290": "匯出失敗",
|
||||
"291": "檔案不存在或為空",
|
||||
"292": "無法建立檔案",
|
||||
"293": "無法寫入檔案"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1785,6 +1785,11 @@
|
||||
"285": "密码不正确",
|
||||
"286": "[%s] 已经回滚完毕",
|
||||
"287": "授权码不能只包含空格。如需禁用,请直接清空输入框",
|
||||
"288": "(默认图标)"
|
||||
"288": "(默认图标)",
|
||||
"289": "已导出到下载目录",
|
||||
"290": "导出失败",
|
||||
"291": "文件不存在或为空",
|
||||
"292": "无法创建文件",
|
||||
"293": "无法写入文件"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,17 +142,14 @@ export const saveExportFile = async (uri: string) => {
|
||||
try {
|
||||
if (isInAndroid()) {
|
||||
window.JSAndroid.saveExportFile(uri);
|
||||
showMessage(window.siyuan.languages.exported);
|
||||
return;
|
||||
}
|
||||
if (isInIOS()) {
|
||||
window.webkit.messageHandlers.saveExportFile.postMessage(uri);
|
||||
showMessage(window.siyuan.languages.exported);
|
||||
return;
|
||||
}
|
||||
if (isInHarmony()) {
|
||||
window.JSHarmony.saveExportFile(uri);
|
||||
showMessage(window.siyuan.languages.exported);
|
||||
return;
|
||||
}
|
||||
const openUrl = new URL(uri, `${location.origin}/`);
|
||||
|
||||
@@ -245,7 +245,7 @@ var blockPrependCmd = &cobra.Command{
|
||||
dom := markdownToBlockDOM(data)
|
||||
transactions := []*model.Transaction{{
|
||||
DoOperations: []*model.Operation{{
|
||||
Action: "prepend",
|
||||
Action: "prependInsert",
|
||||
Data: dom,
|
||||
ParentID: parentID,
|
||||
}},
|
||||
|
||||
@@ -18,7 +18,9 @@ package main
|
||||
|
||||
import (
|
||||
"C"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -158,6 +160,51 @@ func Unzip(zipFilePath, destination *C.char) {
|
||||
}
|
||||
}
|
||||
|
||||
//export ReadExportFile
|
||||
func ReadExportFile(exportPath *C.char) *C.char {
|
||||
pathStr := C.GoString(exportPath)
|
||||
var absPath string
|
||||
if strings.HasPrefix(pathStr, "/export/") {
|
||||
fileName := strings.TrimPrefix(pathStr, "/export/")
|
||||
if decoded, err := url.PathUnescape(fileName); err == nil {
|
||||
fileName = decoded
|
||||
}
|
||||
fileName = filepath.Clean(fileName)
|
||||
if strings.HasPrefix(fileName, "..") {
|
||||
logging.LogWarnf("read export file [%s] blocked: path traversal attempt [%s]", pathStr, fileName)
|
||||
return nil
|
||||
}
|
||||
absPath = filepath.Join(util.TempDir, "export", fileName)
|
||||
exportBaseDir := filepath.Join(util.TempDir, "export")
|
||||
if !gulu.File.IsSubPath(exportBaseDir, absPath) {
|
||||
logging.LogWarnf("read export file [%s] blocked: path [%s] is outside export base dir [%s]", pathStr, absPath, exportBaseDir)
|
||||
return nil
|
||||
}
|
||||
} else if strings.HasPrefix(pathStr, "assets/") {
|
||||
var err error
|
||||
absPath, err = model.GetAssetAbsPath(pathStr)
|
||||
if nil != err {
|
||||
logging.LogErrorf("get asset abs path [%s] failed: %s", pathStr, err)
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
logging.LogWarnf("read export file [%s] failed: unsupported path prefix", pathStr)
|
||||
return nil
|
||||
}
|
||||
|
||||
if "" == absPath {
|
||||
logging.LogWarnf("read export file [%s] failed: resolved to empty abs path", pathStr)
|
||||
return nil
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(absPath)
|
||||
if nil != err {
|
||||
logging.LogErrorf("read export file [%s] failed: %s", absPath, err)
|
||||
return nil
|
||||
}
|
||||
return C.CString(base64.StdEncoding.EncodeToString(data))
|
||||
}
|
||||
|
||||
//export Exit
|
||||
func Exit() {
|
||||
os.Exit(logging.ExitCodeOk)
|
||||
|
||||
@@ -39,7 +39,6 @@ func StartCron() {
|
||||
go every(util.SQLFlushInterval, sql.FlushTxJob)
|
||||
go every(util.SQLFlushInterval, sql.FlushHistoryTxJob)
|
||||
go every(util.SQLFlushInterval, sql.FlushAssetContentTxJob)
|
||||
go every(util.SQLFlushInterval, sql.PollIndexQueue)
|
||||
go every(50*time.Microsecond, model.PollPushQueue)
|
||||
go every(10*time.Minute, model.IndexEmbedBlockJob)
|
||||
go every(10*time.Minute, model.CacheVirtualBlockRefJob)
|
||||
|
||||
@@ -19,6 +19,7 @@ package mobile
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@@ -304,6 +305,52 @@ func Unzip(zipFilePath, destination string) {
|
||||
}
|
||||
}
|
||||
|
||||
// ReadExportFile 读取导出文件内容,绕过 HTTP 层以避免访问授权码拦截。
|
||||
// exportPath 格式为 "/export/xxx.zip" 或 "assets/xxx"。
|
||||
// 返回文件字节,失败返回 nil。
|
||||
func ReadExportFile(exportPath string) (ret []byte) {
|
||||
var absPath string
|
||||
if strings.HasPrefix(exportPath, "/export/") {
|
||||
fileName := strings.TrimPrefix(exportPath, "/export/")
|
||||
if decoded, err := url.PathUnescape(fileName); err == nil {
|
||||
fileName = decoded
|
||||
}
|
||||
fileName = filepath.Clean(fileName)
|
||||
if strings.HasPrefix(fileName, "..") {
|
||||
logging.LogWarnf("read export file [%s] blocked: path traversal attempt [%s]", exportPath, fileName)
|
||||
return
|
||||
}
|
||||
absPath = filepath.Join(util.TempDir, "export", fileName)
|
||||
exportBaseDir := filepath.Join(util.TempDir, "export")
|
||||
if !gulu.File.IsSubPath(exportBaseDir, absPath) {
|
||||
logging.LogWarnf("read export file [%s] blocked: path [%s] is outside export base dir [%s]", exportPath, absPath, exportBaseDir)
|
||||
return
|
||||
}
|
||||
} else if strings.HasPrefix(exportPath, "assets/") {
|
||||
var err error
|
||||
absPath, err = model.GetAssetAbsPath(exportPath)
|
||||
if nil != err {
|
||||
logging.LogErrorf("get asset abs path [%s] failed: %s", exportPath, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
logging.LogWarnf("read export file [%s] failed: unsupported path prefix", exportPath)
|
||||
return
|
||||
}
|
||||
|
||||
if "" == absPath {
|
||||
logging.LogWarnf("read export file [%s] failed: resolved to empty abs path", exportPath)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(absPath)
|
||||
if nil != err {
|
||||
logging.LogErrorf("read export file [%s] failed: %s", absPath, err)
|
||||
return
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func Exit() {
|
||||
os.Exit(logging.ExitCodeOk)
|
||||
}
|
||||
|
||||
+77
-109
@@ -23,22 +23,21 @@ import (
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/88250/gulu"
|
||||
"github.com/88250/lute"
|
||||
"github.com/88250/lute/parse"
|
||||
"github.com/gofrs/flock"
|
||||
"github.com/siyuan-note/dataparser"
|
||||
"github.com/siyuan-note/filelock"
|
||||
"github.com/siyuan-note/eventbus"
|
||||
"github.com/siyuan-note/logging"
|
||||
"github.com/siyuan-note/siyuan/kernel/filesys"
|
||||
"github.com/siyuan-note/siyuan/kernel/util"
|
||||
)
|
||||
|
||||
var (
|
||||
indexMu sync.Mutex
|
||||
indexQueueSize atomic.Int64
|
||||
skipIndexAppend atomic.Bool
|
||||
indexFlock *flock.Flock
|
||||
indexMu sync.Mutex
|
||||
indexQueueSize atomic.Int64
|
||||
indexFlock *flock.Flock
|
||||
)
|
||||
|
||||
type indexEntry struct {
|
||||
@@ -69,10 +68,6 @@ func closeIndexQueue() {
|
||||
}
|
||||
|
||||
func appendToIndexQueue(op *dbQueueOperation) {
|
||||
if skipIndexAppend.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
entry := dbOpToIndexEntry(op)
|
||||
if nil == entry {
|
||||
return
|
||||
@@ -209,27 +204,6 @@ func clearIndexQueueEntries() {
|
||||
indexQueueSize.Store(0)
|
||||
}
|
||||
|
||||
func PollIndexQueue() {
|
||||
if skipIndexAppend.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
_ = indexFlock.Lock()
|
||||
defer func() { _ = indexFlock.Unlock() }()
|
||||
|
||||
entries := loadIndexQueue()
|
||||
if 1 > len(entries) {
|
||||
return
|
||||
}
|
||||
|
||||
skipIndexAppend.Store(true)
|
||||
defer skipIndexAppend.Store(false)
|
||||
|
||||
logging.LogInfof("polling [%d] external index queue operations", len(entries))
|
||||
processIndexEntries(entries, "poll index queue")
|
||||
clearIndexQueueEntries()
|
||||
}
|
||||
|
||||
func loadIndexQueue() (entries []indexEntry) {
|
||||
indexQueuePath := filepath.Join(util.QueueDir, "index.queue")
|
||||
f, err := os.Open(indexQueuePath)
|
||||
@@ -267,86 +241,80 @@ func recoverIndexQueue() {
|
||||
}
|
||||
|
||||
logging.LogInfof("recovering [%d] index queue operations", len(entries))
|
||||
processIndexEntries(entries, "recover index queue")
|
||||
|
||||
luteEngine := lute.New()
|
||||
dbQueueLock.Lock()
|
||||
for _, e := range entries {
|
||||
op := indexEntryToOp(e, luteEngine, "recover index queue")
|
||||
if nil == op {
|
||||
continue
|
||||
}
|
||||
operationQueue = append(operationQueue, op)
|
||||
}
|
||||
dbQueueLock.Unlock()
|
||||
|
||||
eventbus.Publish(eventbus.EvtSQLIndexChanged)
|
||||
logging.LogInfof("recovered [%d] index queue operations, will be flushed soon", len(entries))
|
||||
}
|
||||
|
||||
func processIndexEntries(entries []indexEntry, prefix string) {
|
||||
luteEngine := lute.New()
|
||||
for _, e := range entries {
|
||||
switch e.Action {
|
||||
case "upsert":
|
||||
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s upsert: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
continue
|
||||
}
|
||||
UpsertTreeQueue(tree)
|
||||
case "index":
|
||||
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s index: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
continue
|
||||
}
|
||||
IndexTreeQueue(tree)
|
||||
case "rename":
|
||||
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s rename: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
continue
|
||||
}
|
||||
RenameTreeQueue(tree)
|
||||
case "move":
|
||||
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s move: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
continue
|
||||
}
|
||||
MoveTreeQueue(tree)
|
||||
case "update_refs":
|
||||
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s update_refs: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
continue
|
||||
}
|
||||
UpdateRefsTreeQueue(tree)
|
||||
case "delete_refs":
|
||||
tree, err := loadTreeFromDisk(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s delete_refs: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
continue
|
||||
}
|
||||
DeleteRefsTreeQueue(tree)
|
||||
case "delete":
|
||||
RemoveTreePathQueue(e.Box, e.Path)
|
||||
case "delete_id":
|
||||
RemoveTreeQueue(e.ID)
|
||||
case "delete_ids":
|
||||
BatchRemoveTreeQueue(e.IDs)
|
||||
case "delete_box":
|
||||
DeleteBoxQueue(e.Box)
|
||||
case "delete_box_refs":
|
||||
DeleteBoxRefsQueue(e.Box)
|
||||
case "delete_assets":
|
||||
BatchRemoveAssetsQueue(e.Hashes)
|
||||
case "index_node":
|
||||
IndexNodeQueue(e.ID)
|
||||
func indexEntryToOp(e indexEntry, luteEngine *lute.Lute, prefix string) *dbQueueOperation {
|
||||
switch e.Action {
|
||||
case "upsert":
|
||||
tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s upsert: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
return nil
|
||||
}
|
||||
return &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "upsert"}
|
||||
case "index":
|
||||
tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s index: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
return nil
|
||||
}
|
||||
return &dbQueueOperation{indexTree: tree, inQueueTime: time.Now(), action: "index"}
|
||||
case "rename":
|
||||
tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s rename: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
return nil
|
||||
}
|
||||
return &dbQueueOperation{indexTree: tree, inQueueTime: time.Now(), action: "rename"}
|
||||
case "move":
|
||||
tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s move: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
return nil
|
||||
}
|
||||
return &dbQueueOperation{indexTree: tree, inQueueTime: time.Now(), action: "move"}
|
||||
case "update_refs":
|
||||
tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s update_refs: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
return nil
|
||||
}
|
||||
return &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "update_refs"}
|
||||
case "delete_refs":
|
||||
tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)
|
||||
if err != nil {
|
||||
logging.LogWarnf("%s delete_refs: load tree [%s/%s] failed: %s", prefix, e.Box, e.Path, err)
|
||||
return nil
|
||||
}
|
||||
return &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "delete_refs"}
|
||||
case "delete":
|
||||
return &dbQueueOperation{removeTreeBox: e.Box, removeTreePath: e.Path, inQueueTime: time.Now(), action: "delete"}
|
||||
case "delete_id":
|
||||
return &dbQueueOperation{removeTreeID: e.ID, inQueueTime: time.Now(), action: "delete_id"}
|
||||
case "delete_ids":
|
||||
return &dbQueueOperation{removeTreeIDs: e.IDs, inQueueTime: time.Now(), action: "delete_ids"}
|
||||
case "delete_box":
|
||||
return &dbQueueOperation{box: e.Box, inQueueTime: time.Now(), action: "delete_box"}
|
||||
case "delete_box_refs":
|
||||
return &dbQueueOperation{box: e.Box, inQueueTime: time.Now(), action: "delete_box_refs"}
|
||||
case "delete_assets":
|
||||
return &dbQueueOperation{removeAssetHashes: e.Hashes, inQueueTime: time.Now(), action: "delete_assets"}
|
||||
case "index_node":
|
||||
return &dbQueueOperation{id: e.ID, inQueueTime: time.Now(), action: "index_node"}
|
||||
}
|
||||
}
|
||||
|
||||
func loadTreeFromDisk(box, p string, luteEngine *lute.Lute) (tree *parse.Tree, err error) {
|
||||
filePath := filepath.Join(util.DataDir, box, p)
|
||||
data, err := filelock.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
tree, _, err = dataparser.ParseJSON(data, luteEngine.ParseOptions)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tree.Box = box
|
||||
tree.Path = p
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
+37
-3
@@ -27,6 +27,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/88250/lute"
|
||||
"github.com/88250/lute/parse"
|
||||
"github.com/siyuan-note/eventbus"
|
||||
"github.com/siyuan-note/logging"
|
||||
@@ -39,7 +40,6 @@ var (
|
||||
operationQueue []*dbQueueOperation
|
||||
dbQueueLock = sync.Mutex{}
|
||||
dbQueueCond = sync.NewCond(&dbQueueLock)
|
||||
txLock = sync.Mutex{}
|
||||
)
|
||||
|
||||
type dbQueueOperation struct {
|
||||
@@ -108,14 +108,13 @@ func FlushQueue() {
|
||||
ops, indexSnapshot := getOperations()
|
||||
total := len(ops)
|
||||
if 1 > total && !flushingTx.Load() {
|
||||
processDiskQueue()
|
||||
return
|
||||
}
|
||||
|
||||
txLock.Lock()
|
||||
flushingTx.Store(true)
|
||||
defer func() {
|
||||
flushingTx.Store(false)
|
||||
txLock.Unlock()
|
||||
// 通知等待的协程队列已刷新完成
|
||||
dbQueueCond.Broadcast()
|
||||
}()
|
||||
@@ -205,6 +204,7 @@ func FlushQueue() {
|
||||
eventbus.Publish(eventbus.EvtSQLIndexFlushed)
|
||||
|
||||
clearIndexQueue(indexSnapshot)
|
||||
processDiskQueue()
|
||||
}
|
||||
|
||||
func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err error) {
|
||||
@@ -465,3 +465,37 @@ func appendOperation(op *dbQueueOperation) {
|
||||
appendToIndexQueue(op)
|
||||
eventbus.Publish(eventbus.EvtSQLIndexChanged)
|
||||
}
|
||||
|
||||
func processDiskQueue() {
|
||||
entries := loadIndexQueue()
|
||||
if 1 > len(entries) {
|
||||
return
|
||||
}
|
||||
|
||||
logging.LogInfof("flushing [%d] disk index queue operations", len(entries))
|
||||
|
||||
luteEngine := lute.New()
|
||||
context := map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}
|
||||
for _, e := range entries {
|
||||
op := indexEntryToOp(e, luteEngine, "flush disk queue")
|
||||
if nil == op {
|
||||
continue
|
||||
}
|
||||
tx, err := beginTx()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = execOp(op, tx, context); err != nil {
|
||||
tx.Rollback()
|
||||
closeTxPreparedStmts(tx)
|
||||
logging.LogErrorf("queue operation [%s] failed: %s", op.action, err)
|
||||
continue
|
||||
}
|
||||
if err = commitTx(tx); err != nil {
|
||||
logging.LogErrorf("commit tx failed: %s", err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
clearIndexQueueEntries()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user