Skip to content

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

:sparkles: Support importing .sy.zip as notebook

Daniel800361b4fba1
diff --git a/app/src/util/mount.ts b/app/src/util/mount.ts
index 376e528df2..a921102b7a 100644
--- a/app/src/util/mount.ts
+++ b/app/src/util/mount.ts
@@ -112,6 +112,7 @@ export const newNotebook = () => {
importObsidianHTML = `<div class="fn__hr"></div>
<div class="b3-label__text fn__pointer fn__flex" style="align-items: center;gap: 4px" data-type="toggle-import" role="button" tabindex="0" aria-expanded="false"><svg class="b3-list-item__arrow" style="display: block;flex: none;height: 14px;width: 14px" data-type="import-arrow"><use xlink:href="#iconRight"></use></svg><span style="line-height: 20px">${window.siyuan.languages.importFromMoreApps}</span></div>
<div class="b3-list--background fn__none" data-type="import-options" style="padding-top: 8px">
+ <label class="b3-list-item fn__pointer" data-type="import-sy"><svg class="b3-list-item__graphic"><use xlink:href="#iconSiYuan"></use></svg><span class="b3-list-item__text">SiYuan .sy.zip</span><input class="b3-form__upload" type="file" accept="application/zip"></label>
<div class="b3-list-item fn__pointer" data-type="import-obsidian" role="button" tabindex="0"><svg class="b3-list-item__graphic"><use xlink:href="#iconObsidian"></use></svg><span class="b3-list-item__text">Obsidian Vault</span></div>
</div>`;
/// #endif
@@ -163,6 +164,17 @@ export const newNotebook = () => {
toggleImportOptions();
}
});
+ dialog.element.querySelector('[data-type="import-sy"] .b3-form__upload').addEventListener("change", (event: InputEvent & {
+ target: HTMLInputElement
+ }) => {
+ if (!event.target.files?.[0]) {
+ return;
+ }
+ const formData = new FormData();
+ formData.append("file", event.target.files[0]);
+ dialog.destroy();
+ fetchPost("/api/import/importSYNotebook", formData);
+ });
const importObsidianElement = dialog.element.querySelector('[data-type="import-obsidian"]') as HTMLElement;
let selectingObsidianVault = false;
const selectObsidianVault = async () => {
diff --git a/kernel/api/import.go b/kernel/api/import.go
index 5fd4ca2ce6..0d6fe3d919 100644
--- a/kernel/api/import.go
+++ b/kernel/api/import.go
@@ -17,8 +17,10 @@
package api
import (
+ "errors"
"fmt"
"io"
+ "mime/multipart"
"net/http"
"os"
"path/filepath"
@@ -38,96 +40,95 @@ func importSY(c *gin.Context) {
util.PushEndlessProgress(model.Conf.Language(73))
defer util.ClearPushProgress(100)
- form, err := c.MultipartForm()
+ form, writePath, cleanup, err := saveImportUpload(c)
if err != nil {
- logging.LogErrorf("parse import .sy.zip failed: %s", err)
+ logging.LogErrorf("save import .sy.zip failed: %s", err)
ret.Code = -1
ret.Msg = err.Error()
return
}
+ defer cleanup()
- files := form.File["file"]
- if 1 > len(files) {
- logging.LogErrorf("parse import .sy.zip failed, no file found")
- ret.Code = -1
- ret.Msg = "no file found"
- return
- }
- file := files[0]
- importDir := filepath.Join(util.TempDir, "import")
- if err = os.MkdirAll(importDir, 0755); err != nil {
- logging.LogErrorf("make import dir [%s] failed: %s", importDir, err)
- ret.Code = -1
- ret.Msg = err.Error()
- return
- }
+ notebook := form.Value["notebook"][0]
+ toPath := form.Value["toPath"][0]
- writePath := filepath.Join(importDir, file.Filename)
- if !gulu.File.IsSubPath(importDir, writePath) {
- logging.LogErrorf("import path [%s] is not sub path of import dir [%s]", writePath, importDir)
+ err = model.ImportSY(writePath, notebook, toPath)
+ if err != nil {
ret.Code = -1
- ret.Msg = "import path is not sub path of import dir"
+ ret.Msg = err.Error()
return
}
+}
- defer os.RemoveAll(writePath)
+func importSYNotebook(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
- var reader io.ReadCloser
- var writer *os.File
- defer func() {
- if writer != nil {
- _ = writer.Close()
- }
- if reader != nil {
- _ = reader.Close()
- }
- }()
+ util.PushEndlessProgress(model.Conf.Language(73))
+ defer util.ClearPushProgress(100)
- reader, err = file.Open()
+ _, writePath, cleanup, err := saveImportUpload(c)
if err != nil {
- logging.LogErrorf("read import .sy.zip failed: %s", err)
+ logging.LogErrorf("save notebook import .sy.zip failed: %s", err)
ret.Code = -1
ret.Msg = err.Error()
return
}
+ defer cleanup()
- writer, err = os.OpenFile(writePath, os.O_RDWR|os.O_CREATE, 0644)
+ id, err := model.ImportSYNotebook(writePath)
if err != nil {
- logging.LogErrorf("open import .sy.zip [%s] failed: %s", writePath, err)
- ret.Code = -1
- ret.Msg = err.Error()
- return
- }
- if _, err = io.Copy(writer, reader); err != nil {
- logging.LogErrorf("write import .sy.zip failed: %s", err)
ret.Code = -1
ret.Msg = err.Error()
return
}
- if err = writer.Close(); err != nil {
- logging.LogErrorf("close import .sy.zip [%s] failed: %s", writePath, err)
+
+ existed, err := model.Mount(id)
+ if err != nil {
ret.Code = -1
ret.Msg = err.Error()
return
}
- writer = nil
- if err = reader.Close(); err != nil {
- logging.LogErrorf("close import upload reader failed: %s", err)
+ box := model.Conf.Box(id)
+ if box == nil {
ret.Code = -1
- ret.Msg = err.Error()
+ ret.Msg = "opened notebook [" + id + "] not found"
return
}
- reader = nil
- notebook := form.Value["notebook"][0]
- toPath := form.Value["toPath"][0]
+ ret.Data = map[string]any{"notebook": box}
+ event := util.NewCmdResult("createnotebook", 0, util.PushModeBroadcast)
+ event.Data = map[string]any{"box": box, "existed": existed}
+ util.PushEvent(event)
+}
- err = model.ImportSY(writePath, notebook, toPath)
+func saveImportUpload(c *gin.Context) (form *multipart.Form, writePath string, cleanup func(), err error) {
+ form, err = c.MultipartForm()
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
return
}
+ files := form.File["file"]
+ if len(files) < 1 {
+ err = errors.New("no file found")
+ return
+ }
+
+ importDir := filepath.Join(util.TempDir, "import", gulu.Rand.String(7))
+ if err = os.MkdirAll(importDir, 0755); err != nil {
+ return
+ }
+ cleanup = func() { _ = os.RemoveAll(importDir) }
+ writePath = filepath.Join(importDir, filepath.Base(files[0].Filename))
+ if !gulu.File.IsSubPath(importDir, writePath) {
+ err = errors.New("import path is not sub path of import dir")
+ cleanup()
+ return
+ }
+
+ if err = c.SaveUploadedFile(files[0], writePath); err != nil {
+ cleanup()
+ }
+ return
}
func importData(c *gin.Context) {
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 540c0aed89..a42f35d898 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -391,6 +391,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/import/importZipMd", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importZipMd)
ginServer.Handle("POST", "/api/import/importData", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importData)
ginServer.Handle("POST", "/api/import/importSY", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importSY)
+ ginServer.Handle("POST", "/api/import/importSYNotebook", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importSYNotebook)
ginServer.Handle("POST", "/api/import/startObsidianVaultAnalysis", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, startObsidianVaultAnalysis)
ginServer.Handle("POST", "/api/import/getObsidianVaultTask", model.CheckAuth, model.CheckAdminRole, getObsidianVaultTask)
ginServer.Handle("POST", "/api/import/startObsidianVaultImport", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, startObsidianVaultImport)
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 90c2c6e710..af6ee1150c 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -596,7 +596,7 @@ func ExportSYs(ids []string) (zipPath string) {
}
}
}
- zipPath = exportSYZip(block.BoxID, path.Dir(block.Path), baseFolderName, docPaths)
+ zipPath = exportSYZip(block.BoxID, path.Dir(block.Path), baseFolderName, docPaths, false)
return
}
@@ -2300,11 +2300,11 @@ func exportBoxSYZip(boxID string) (zipPath string) {
for _, docFile := range docFiles {
docPaths = append(docPaths, docFile.path)
}
- zipPath = exportSYZip(boxID, "/", baseFolderName, docPaths)
+ zipPath = exportSYZip(boxID, "/", baseFolderName, docPaths, true)
return
}
-func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (zipPath string) {
+func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, includeBoxConf bool) (zipPath string) {
defer util.ClearPushProgress(100)
dir, name := path.Split(baseFolderName)
@@ -2343,6 +2343,29 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (
logging.LogErrorf("create export temp folder failed: %s", err)
return
}
+ if includeBoxConf {
+ boxConf := box.GetConf()
+ boxConf.Sort = 0
+ boxConf.Closed = true
+ boxConf.RefCreateSaveBox = ""
+ boxConf.DocCreateSaveBox = ""
+ boxConf.Encrypted = false
+ boxConf.BoxCrypt = nil
+ confData, marshalErr := gulu.JSON.MarshalIndentJSON(boxConf, "", " ")
+ if marshalErr != nil {
+ logging.LogErrorf("marshal export notebook conf failed: %s", marshalErr)
+ return
+ }
+ confDir := filepath.Join(exportDir, ".siyuan")
+ if mkdirErr := os.MkdirAll(confDir, 0755); mkdirErr != nil {
+ logging.LogErrorf("create export notebook conf dir failed: %s", mkdirErr)
+ return
+ }
+ if writeErr := os.WriteFile(filepath.Join(confDir, "conf.json"), confData, 0644); writeErr != nil {
+ logging.LogErrorf("write export notebook conf failed: %s", writeErr)
+ return
+ }
+ }
trees := map[string]*parse.Tree{}
refTrees := map[string]*parse.Tree{}
diff --git a/kernel/model/import.go b/kernel/model/import.go
index b0c47b965e..eb0b5cb091 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -50,6 +50,7 @@ import (
"github.com/siyuan-note/logging"
"github.com/siyuan-note/riff"
"github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
@@ -113,7 +114,15 @@ func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parse
}
func ImportSY(zipPath, boxID, toPath string) (err error) {
- toPath = normalizeBoxDocTarget(boxID, toPath)
+ _, err = importSY(zipPath, boxID, toPath, false)
+ return
+}
+
+func ImportSYNotebook(zipPath string) (boxID string, err error) {
+ return importSY(zipPath, "", "/", true)
+}
+
+func importSY(zipPath, boxID, toPath string, createNotebook bool) (createdBoxID string, err error) {
util.PushEndlessProgress(Conf.Language(73))
defer util.ClearPushProgress(100)
@@ -149,16 +158,75 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
logging.LogErrorf("read unzip dir [%s] failed: %s", unzipPath, err)
return
}
- if 1 != len(entries) {
+ if 1 != len(entries) || !entries[0].IsDir() || len(syPaths) < 1 {
logging.LogErrorf("invalid .sy.zip [%v]", entries)
- return errors.New(Conf.Language(199))
+ err = errors.New(Conf.Language(199))
+ return
}
unzipRootPath := filepath.Join(unzipPath, entries[0].Name())
name := filepath.Base(unzipRootPath)
if strings.HasPrefix(name, "data-20") && len("data-20230321175442") == len(name) {
logging.LogErrorf("invalid .sy.zip [unzipRootPath=%s, baseName=%s]", unzipRootPath, name)
- return errors.New(Conf.Language(199))
+ err = errors.New(Conf.Language(199))
+ return
}
+ var importedBoxConf *conf.BoxConf
+ importedConfPath := filepath.Join(unzipRootPath, ".siyuan", "conf.json")
+ if filelock.IsExist(importedConfPath) {
+ confData, readErr := filelock.ReadFile(importedConfPath)
+ if readErr == nil {
+ importedBoxConf = conf.NewBoxConf()
+ if unmarshalErr := gulu.JSON.UnmarshalJSON(confData, importedBoxConf); unmarshalErr != nil {
+ logging.LogWarnf("parse imported notebook conf failed: %s", unmarshalErr)
+ importedBoxConf = nil
+ }
+ } else {
+ logging.LogWarnf("read imported notebook conf failed: %s", readErr)
+ }
+ if removeErr := filelock.Remove(importedConfPath); removeErr != nil {
+ err = removeErr
+ return
+ }
+ }
+ if createNotebook {
+ if importedBoxConf != nil && importedBoxConf.Name != "" {
+ name = importedBoxConf.Name
+ }
+ boxID, err = CreateBox(util.RemoveInvalid(name))
+ if err != nil {
+ return "", err
+ }
+ createdBoxID = boxID
+ defer func() {
+ if err == nil {
+ return
+ }
+ treenode.RemoveBlockTreesByBoxID(boxID)
+ sql.DeleteBoxQueue(boxID)
+ if removeErr := filelock.Remove(filepath.Join(util.DataDir, boxID)); removeErr != nil {
+ logging.LogErrorf("remove notebook [%s] after import failed: %s", boxID, removeErr)
+ }
+ }()
+ if importedBoxConf != nil {
+ box := &Box{ID: boxID}
+ boxConf := box.GetConf()
+ boxConf.Icon = importedBoxConf.Icon
+ if strings.Contains(boxConf.Icon, ".") {
+ boxConf.Icon = util.FilterUploadEmojiFileName(boxConf.Icon)
+ }
+ boxConf.RefCreateSavePath = importedBoxConf.RefCreateSavePath
+ boxConf.DocCreateSavePath = importedBoxConf.DocCreateSavePath
+ boxConf.DailyNoteSavePath = importedBoxConf.DailyNoteSavePath
+ boxConf.DailyNoteTemplatePath = importedBoxConf.DailyNoteTemplatePath
+ boxConf.SortMode = importedBoxConf.SortMode
+ if err = box.SaveConf(boxConf); err != nil {
+ return createdBoxID, err
+ }
+ }
+ } else {
+ createdBoxID = boxID
+ }
+ toPath = normalizeBoxDocTarget(boxID, toPath)
luteEngine := util.NewLute()
blockIDs := map[string]string{}
@@ -284,7 +352,8 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
data, readErr := os.ReadFile(oldPath)
if nil != readErr {
logging.LogErrorf("read av file [%s] failed: %s", oldPath, readErr)
- return nil
+ err = readErr
+ return
}
// 将数据库文件中的 ID 替换为新的 ID
@@ -296,7 +365,8 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
if !bytes.Equal(data, newData) {
if writeErr := os.WriteFile(oldPath, newData, 0644); nil != writeErr {
logging.LogErrorf("write av file [%s] failed: %s", oldPath, writeErr)
- return nil
+ err = writeErr
+ return
}
}
@@ -552,7 +622,8 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
newPath := renamePaths[oldPath]
if err = filelock.Rename(oldPath, newPath); err != nil {
logging.LogErrorf("rename path from [%s] to [%s] failed: %s", oldPath, renamePaths[oldPath], err)
- return errors.New("rename path failed")
+ err = errors.New("rename path failed")
+ return
}
delete(renamePaths, oldPath)
@@ -698,7 +769,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
block := treenode.GetBlockTreeRootByPath(boxID, toPath)
if nil == block {
logging.LogErrorf("not found block by path [%s]", toPath)
- return nil
+ return createdBoxID, nil
}
baseTargetPath = strings.TrimSuffix(block.Path, ".sy")
}