-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathimport.go
More file actions
2284 lines (2085 loc) · 69 KB
/
Copy pathimport.go
File metadata and controls
2284 lines (2085 loc) · 69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SiYuan - Refactor your thinking
// Copyright (c) 2020-present, b3log.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package model
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"io/fs"
"maps"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"runtime/debug"
"sort"
"strings"
"github.com/88250/gulu"
"github.com/88250/lute"
"github.com/88250/lute/ast"
"github.com/88250/lute/html"
"github.com/88250/lute/html/atom"
"github.com/88250/lute/parse"
"github.com/88250/lute/render"
util2 "github.com/88250/lute/util"
"github.com/siyuan-note/dataparser"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/riff"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/cache"
"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"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parse.Tree, withMath bool) {
htmlStr = gulu.Str.RemovePUA(htmlStr)
assetDirPath := filepath.Join(util.DataDir, "assets")
if boxID != "" {
assetDirPath = filepath.Join(util.DataDir, boxID, "assets")
_ = os.MkdirAll(assetDirPath, 0755)
}
tree = luteEngine.HTML2Tree(htmlStr)
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
switch n.Type {
case ast.NodeHTMLBlock:
if bytes.HasPrefix(n.Tokens, []byte("<pre ")) && bytes.HasSuffix(n.Tokens, []byte("</pre>")) {
if bytes.Contains(n.Tokens, []byte("data:image/svg+xml;base64")) {
matches := regexp.MustCompile(`(?sU)<pre [^>]*>(.*)</pre>`).FindSubmatch(n.Tokens)
if len(matches) >= 2 {
n.Tokens = matches[1]
}
subTree := parse.Inline("", n.Tokens, luteEngine.ParseOptions)
if nil != subTree && nil != subTree.Root && nil != subTree.Root.FirstChild {
n.Type = ast.NodeParagraph
var children []*ast.Node
for c := subTree.Root.FirstChild.FirstChild; nil != c; c = c.Next {
children = append(children, c)
}
for _, c := range children {
n.AppendChild(c)
}
}
} else if bytes.Contains(n.Tokens, []byte("<svg")) {
processHTMLBlockSvgImg(n, assetDirPath, boxID)
}
}
case ast.NodeText:
if n.ParentIs(ast.NodeTableCell) {
n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("\\|"), []byte("|"))
n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("|"), []byte("\\|"))
n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("\\<br /\\>"), []byte("<br />"))
}
case ast.NodeInlineMath:
withMath = true
case ast.NodeLinkDest:
dest := n.TokensStr()
if strings.HasPrefix(dest, "data:image") && strings.Contains(dest, ";base64,") {
processBase64Img(n, dest, assetDirPath, boxID)
}
}
return ast.WalkContinue
})
return
}
func ImportSY(zipPath, boxID, toPath string) (err error) {
_, err = importSY(zipPath, boxID, toPath, false, false)
return
}
func ImportSYNotebook(zipPath string) (boxID string, err error) {
return importSY(zipPath, "", "/", true, false)
}
var ErrSYTargetNotebookRequired = errors.New("target notebook required")
func ImportSYAuto(zipPath, boxID, toPath string) (createdBoxID string, notebook bool, err error) {
createdBoxID, err = importSY(zipPath, boxID, toPath, false, true)
notebook = err == nil && createdBoxID != boxID
return
}
func isSYNotebookExport(hasBoxConf, hasBoxDocMeta bool) bool {
return hasBoxConf || hasBoxDocMeta
}
func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (createdBoxID string, err error) {
util.PushEndlessProgress(Conf.Language(73))
defer util.ClearPushProgress(100)
lockSync()
defer unlockSync()
baseName := filepath.Base(zipPath)
ext := filepath.Ext(baseName)
baseName = strings.TrimSuffix(baseName, ext)
unzipPath := filepath.Join(filepath.Dir(zipPath), baseName+"-"+gulu.Rand.String(7))
err = gulu.Zip.Unzip(zipPath, unzipPath)
if err != nil {
return
}
defer os.RemoveAll(unzipPath)
var syPaths []string
filelock.Walk(unzipPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d == nil {
return nil
}
if !d.IsDir() && strings.HasSuffix(d.Name(), ".sy") {
syPaths = append(syPaths, path)
}
return nil
})
entries, err := os.ReadDir(unzipPath)
if err != nil {
logging.LogErrorf("read unzip dir [%s] failed: %s", unzipPath, err)
return
}
if 1 != len(entries) || !entries[0].IsDir() || len(syPaths) < 1 {
logging.LogErrorf("invalid .sy.zip [%v]", entries)
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)
err = errors.New(Conf.Language(199))
return
}
var importedBoxConf *conf.BoxConf
importedConfPath := filepath.Join(unzipRootPath, ".siyuan", "conf.json")
hasImportedBoxConf := filelock.IsExist(importedConfPath)
var importedMetadataErr error
if hasImportedBoxConf {
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
importedMetadataErr = unmarshalErr
}
} else {
logging.LogWarnf("read imported notebook conf failed: %s", readErr)
importedMetadataErr = readErr
}
if removeErr := filelock.Remove(importedConfPath); removeErr != nil {
err = removeErr
return
}
}
var importedBoxDocID string
importedBoxDocPath := filepath.Join(unzipRootPath, ".siyuan", boxDocMetaName)
hasImportedBoxDocMeta := filelock.IsExist(importedBoxDocPath)
if hasImportedBoxDocMeta {
metaData, readErr := filelock.ReadFile(importedBoxDocPath)
if readErr == nil {
meta := &boxDocMeta{}
if unmarshalErr := gulu.JSON.UnmarshalJSON(metaData, meta); unmarshalErr != nil {
logging.LogWarnf("parse imported notebook document metadata failed: %s", unmarshalErr)
importedMetadataErr = unmarshalErr
} else if meta.Spec != boxDocMetaSpec || !ast.IsNodeIDPattern(meta.BoxDocID) {
logging.LogWarnf("invalid imported notebook document metadata [spec=%d, id=%s]", meta.Spec, meta.BoxDocID)
importedMetadataErr = errors.New("invalid imported notebook document metadata")
} else {
importedBoxDocID = meta.BoxDocID
}
} else {
logging.LogWarnf("read imported notebook document metadata failed: %s", readErr)
importedMetadataErr = readErr
}
if removeErr := filelock.Remove(importedBoxDocPath); removeErr != nil {
err = removeErr
return
}
}
if autoDetect {
if importedMetadataErr != nil {
err = errors.New(Conf.Language(199))
return
}
createNotebook = isSYNotebookExport(hasImportedBoxConf, hasImportedBoxDocMeta)
}
if autoDetect && !createNotebook && boxID == "" {
err = ErrSYTargetNotebookRequired
return
}
if !createNotebook && nil == Conf.Box(boxID) {
err = errors.New(Conf.Language(0))
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 = filterBoxIcon(importedBoxConf.Icon)
boxConf.RefCreateSavePath = importedBoxConf.RefCreateSavePath
boxConf.DocCreateSavePath = importedBoxConf.DocCreateSavePath
boxConf.DocCreateTemplatePath = importedBoxConf.DocCreateTemplatePath
boxConf.DailyNoteSavePath = importedBoxConf.DailyNoteSavePath
boxConf.DailyNoteTemplatePath = importedBoxConf.DailyNoteTemplatePath
boxConf.DailyNoteDatabaseID = importedBoxConf.DailyNoteDatabaseID
boxConf.SortMode = importedBoxConf.SortMode
if err = box.SaveConf(boxConf); err != nil {
return createdBoxID, err
}
}
} else {
createdBoxID = boxID
}
encryptedTarget := IsEncryptedBox(boxID)
storageRiffDir := filepath.Join(unzipRootPath, "storage", "riff")
if encryptedTarget && gulu.File.IsExist(storageRiffDir) {
return createdBoxID, errors.New(Conf.Language(313))
}
toPath = normalizeBoxDocTarget(boxID, toPath)
luteEngine := util.NewLute()
blockIDs := map[string]string{}
trees := map[string]*parse.Tree{}
importedBoxDoc := false
containsFlashcardAttrs := false
// 重新生成块 ID
for i, syPath := range syPaths {
data, readErr := os.ReadFile(syPath)
if nil != readErr {
logging.LogErrorf("read .sy [%s] failed: %s", syPath, readErr)
err = readErr
return
}
tree, _, parseErr := dataparser.ParseJSON(data, luteEngine.ParseOptions)
if nil != parseErr {
logging.LogErrorf("parse .sy [%s] failed: %s", syPath, parseErr)
err = parseErr
return
}
oldRootID := tree.Root.ID
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
if encryptedTarget && n.IsBlock() && n.IALAttr(NodeAttrRiffDecks) != "" {
containsFlashcardAttrs = true
}
if "" == n.ID {
return ast.WalkContinue
}
// 新 ID 保留时间部分,仅修改随机值,避免时间变化导致更新时间早于创建时间
// Keep original creation time when importing .sy.zip https://github.com/siyuan-note/siyuan/issues/9923
newNodeID := util.TimeFromID(n.ID) + "-" + util.RandString(7)
if createNotebook && oldRootID == importedBoxDocID && n.ID == importedBoxDocID {
newNodeID = boxID
}
blockIDs[n.ID] = newNodeID
n.ID = newNodeID
n.SetIALAttr("id", newNodeID)
if icon := n.IALAttr("icon"); "" != icon {
// XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
icon = filterBoxIcon(icon)
n.SetIALAttr("icon", icon)
}
return ast.WalkContinue
})
tree.ID = tree.Root.ID
tree.Path = filepath.ToSlash(strings.TrimPrefix(syPath, unzipRootPath))
if createNotebook && oldRootID == importedBoxDocID {
importedBoxDoc = true
tree.Root.SetIALAttr(DocHiddenAttr, "true")
} else if oldRootID == importedBoxDocID {
removeBoxDocHiddenAttr(tree)
}
trees[tree.ID] = tree
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d", i+1, len(syPaths))))
}
if containsFlashcardAttrs {
return createdBoxID, errors.New(Conf.Language(313))
}
if importedBoxDoc {
if err = writeBoxDocID(boxID); err != nil {
return
}
}
// 引用和嵌入指向重新生成的块 ID
for _, tree := range trees {
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
if treenode.IsBlockRef(n) {
defID, _, _ := treenode.GetBlockRef(n)
newDefID := blockIDs[defID]
if "" != newDefID {
n.TextMarkBlockRefID = newDefID
}
} else if ast.NodeTextMark == n.Type && n.IsTextMarkType("a") && strings.HasPrefix(n.TextMarkAHref, "siyuan://blocks/") {
// Block hyperlinks do not point to regenerated block IDs when importing .sy.zip https://github.com/siyuan-note/siyuan/issues/9083
defID := strings.TrimPrefix(n.TextMarkAHref, "siyuan://blocks/")
newDefID := blockIDs[defID]
if "" != newDefID {
n.TextMarkAHref = "siyuan://blocks/" + newDefID
}
} else if ast.NodeBlockQueryEmbedScript == n.Type {
for oldID, newID := range blockIDs {
// 导入 `.sy.zip` 后查询嵌入块失效 https://github.com/siyuan-note/siyuan/issues/5316
n.Tokens = bytes.ReplaceAll(n.Tokens, []byte(oldID), []byte(newID))
}
}
return ast.WalkContinue
})
}
var replacements []string
for oldID, newID := range blockIDs {
replacements = append(replacements, oldID, newID)
}
blockIDReplacer := strings.NewReplacer(replacements...)
// 将关联的数据库文件移动到 data/storage/av/ 下
storage := filepath.Join(unzipRootPath, "storage")
storageAvDir := filepath.Join(storage, "av")
avIDs := map[string]string{}
renameAvPaths := map[string]string{}
if gulu.File.IsExist(storageAvDir) {
// 重新生成数据库数据
filelock.Walk(storageAvDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d == nil {
return nil
}
if ".json" == d.Name() { // https://github.com/siyuan-note/siyuan/issues/16637
if removeErr := os.RemoveAll(path); nil != removeErr {
logging.LogErrorf("remove empty av file [%s] failed: %s", path, removeErr)
}
return nil
}
if !strings.HasSuffix(path, ".json") || !ast.IsNodeIDPattern(strings.TrimSuffix(d.Name(), ".json")) {
return nil
}
// 重命名数据库
newAvID := ast.NewNodeID()
oldAvID := strings.TrimSuffix(d.Name(), ".json")
newPath := filepath.Join(filepath.Dir(path), newAvID+".json")
renameAvPaths[path] = newPath
avIDs[oldAvID] = newAvID
return nil
})
// 重命名数据库文件
for oldPath, newPath := range renameAvPaths {
data, readErr := os.ReadFile(oldPath)
if nil != readErr {
logging.LogErrorf("read av file [%s] failed: %s", oldPath, readErr)
err = readErr
return
}
// 将数据库文件中的 ID 替换为新的 ID
newData := data
for oldAvID, newAvID := range avIDs {
newData = bytes.ReplaceAll(newData, []byte(oldAvID), []byte(newAvID))
}
newData = []byte(blockIDReplacer.Replace(string(newData)))
if !bytes.Equal(data, newData) {
if writeErr := os.WriteFile(oldPath, newData, 0644); nil != writeErr {
logging.LogErrorf("write av file [%s] failed: %s", oldPath, writeErr)
err = writeErr
return
}
}
if err = os.Rename(oldPath, newPath); err != nil {
logging.LogErrorf("rename av file from [%s] to [%s] failed: %s", oldPath, newPath, err)
return
}
}
// 加密笔记本的 AV 定义不能拷到全局目录(明文泄漏 + 路由冲突),
// 需要先加密写入 <boxID>/storage/av/,后续 mirror/relation 操作才能正确路由
if !IsEncryptedBox(boxID) {
targetStorageAvDir := filepath.Join(util.DataDir, "storage", "av")
if copyErr := filelock.Copy(storageAvDir, targetStorageAvDir); nil != copyErr {
logging.LogErrorf("copy storage av dir from [%s] to [%s] failed: %s", storageAvDir, targetStorageAvDir, copyErr)
}
} else {
// 加密笔记本:先把 AV 定义加密写入笔记本级目录,建立 box 映射后 mirror/relation 才能正确路由
if err = encryptBoxAVFiles(boxID, storageAvDir); err != nil {
return
}
}
// 重新指向数据库属性值
for _, tree := range trees {
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || "" == n.ID {
return ast.WalkContinue
}
ial := parse.IAL2Map(n.KramdownIAL)
for k, v := range ial {
if strings.HasPrefix(k, av.NodeAttrNameAvs) {
newKey, newVal := k, v
for oldAvID, newAvID := range avIDs {
newKey = strings.ReplaceAll(newKey, oldAvID, newAvID)
newVal = strings.ReplaceAll(newVal, oldAvID, newAvID)
}
n.RemoveIALAttr(k)
n.SetIALAttr(newKey, newVal)
}
}
if ast.NodeAttributeView == n.Type {
n.AttributeViewID = avIDs[n.AttributeViewID]
}
return ast.WalkContinue
})
}
// 如果数据库中绑定的块不在导入的文档中,则需要单独更新这些绑定块的属性
var attrViewIDs []string
for _, avID := range avIDs {
attrViewIDs = append(attrViewIDs, avID)
}
updateBoundBlockAvsAttribute(attrViewIDs)
// 插入关联关系 https://github.com/siyuan-note/siyuan/issues/11628
relationAvs := map[string]string{}
for _, avID := range avIDs {
attrView, _ := av.ParseAttributeView(avID)
if nil == attrView {
continue
}
for _, keyValues := range attrView.KeyValues {
if nil != keyValues.Key && av.KeyTypeRelation == keyValues.Key.Type && nil != keyValues.Key.Relation {
relationAvs[avID] = keyValues.Key.Relation.AvID
}
}
}
for srcAvID, destAvID := range relationAvs {
av.UpsertAvBackRel(srcAvID, destAvID)
}
}
// 将关联的闪卡数据合并到默认卡包 data/storage/riff/20230218211946-2kw8jgx 中
storageRiffDir = filepath.Join(storage, "riff")
if gulu.File.IsExist(storageRiffDir) {
deckToImport, loadErr := riff.LoadDeck(storageRiffDir, builtinDeckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)
if nil != loadErr {
logging.LogErrorf("load deck [%s] failed: %s", name, loadErr)
} else {
deck := Decks[builtinDeckID]
if nil == deck {
var createErr error
deck, createErr = createDeck0("Built-in Deck", builtinDeckID)
if nil == createErr {
Decks[deck.ID] = deck
}
}
bIDs := deckToImport.GetBlockIDs()
cards := deckToImport.GetCardsByBlockIDs(bIDs)
for _, card := range cards {
deck.AddCard(ast.NewNodeID(), blockIDs[card.BlockID()])
}
if 0 < len(cards) {
if saveErr := deck.Save(); nil != saveErr {
logging.LogErrorf("save deck [%s] failed: %s", name, saveErr)
}
}
}
}
// storage 文件夹已在上方处理,所以这里删除源 storage 文件夹,避免后面被拷贝到导入目录下 targetDir
// 加密笔记本已在上面完成 notebook 级 AV 拷贝,安全删除
if removeErr := os.RemoveAll(storage); nil != removeErr {
logging.LogErrorf("remove temp storage av dir [%s] failed: %s", storage, removeErr)
}
if 1 > len(avIDs) { // 如果本次没有导入数据库,则清理掉文档中的数据库属性 https://github.com/siyuan-note/siyuan/issues/13011
for _, tree := range trees {
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || !n.IsBlock() {
return ast.WalkContinue
}
n.RemoveIALAttr(av.NodeAttrNameAvs)
return ast.WalkContinue
})
}
}
// 写回 .sy
for _, tree := range trees {
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))
syPath := filepath.Join(unzipRootPath, tree.Path)
// 加密前确定最终文件名:tree.ID + ".sy",确保加密 AAD 用的是最终 box-relative path
finalSyName := tree.ID + ".sy"
finalRelPath := filepath.ToSlash(filepath.Join(filepath.Dir(tree.Path), finalSyName))
treenode.UpgradeSpec(tree)
renderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)
data := renderer.Render()
if !util.UseSingleLineSave {
buf := bytes.Buffer{}
buf.Grow(1024 * 1024 * 2)
if err = json.Indent(&buf, data, "", "\t"); err != nil {
return
}
data = buf.Bytes()
}
newSyPath := filepath.Join(filepath.Dir(syPath), finalSyName)
if err = writeImportedTree(boxID, syPath, newSyPath, finalRelPath, data); err != nil {
logging.LogErrorf("write imported .sy [%s] failed: %s", syPath, err)
return
}
tree.Path = finalRelPath
}
// 合并 sort.json
fullSortIDs := map[string]int{}
sortIDs := map[string]int{}
var sortData []byte
var sortErr error
sortPath := filepath.Join(unzipRootPath, ".siyuan", "sort.json")
if filelock.IsExist(sortPath) {
sortData, sortErr = filelock.ReadFile(sortPath)
if nil != sortErr {
logging.LogErrorf("read import sort conf failed: %s", sortErr)
}
if sortErr = gulu.JSON.UnmarshalJSON(sortData, &sortIDs); nil != sortErr {
logging.LogErrorf("unmarshal sort conf failed: %s", sortErr)
}
boxSortPath := filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")
if filelock.IsExist(boxSortPath) {
sortData, sortErr = filelock.ReadFile(boxSortPath)
if nil != sortErr {
logging.LogErrorf("read box sort conf failed: %s", sortErr)
}
if sortErr = gulu.JSON.UnmarshalJSON(sortData, &fullSortIDs); nil != sortErr {
logging.LogErrorf("unmarshal box sort conf failed: %s", sortErr)
}
}
for oldID, sort := range sortIDs {
if newID := blockIDs[oldID]; "" != newID {
fullSortIDs[newID] = sort
}
}
sortData, sortErr = gulu.JSON.MarshalJSON(fullSortIDs)
if nil != sortErr {
logging.LogErrorf("marshal box full sort conf failed: %s", sortErr)
} else {
sortErr = filelock.WriteFile(boxSortPath, sortData)
if nil != sortErr {
logging.LogErrorf("write box full sort conf failed: %s", sortErr)
}
}
if removeErr := os.RemoveAll(sortPath); nil != removeErr {
logging.LogErrorf("remove temp sort conf failed: %s", removeErr)
}
}
// 重命名文件路径
renamePaths := map[string]string{}
filelock.Walk(unzipRootPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d == nil {
return nil
}
if d.IsDir() && ast.IsNodeIDPattern(d.Name()) {
renamePaths[path] = path
}
return nil
})
for p := range renamePaths {
originalPath := p
p = strings.TrimPrefix(p, unzipRootPath)
p = filepath.ToSlash(p)
parts := strings.Split(p, "/")
buf := bytes.Buffer{}
buf.WriteString("/")
for i, part := range parts {
if "" == part {
continue
}
newNodeID := blockIDs[part]
if "" != newNodeID {
buf.WriteString(newNodeID)
} else {
buf.WriteString(part)
}
if i < len(parts)-1 {
buf.WriteString("/")
}
}
newPath := buf.String()
renamePaths[originalPath] = filepath.Join(unzipRootPath, newPath)
}
var oldPaths []string
for oldPath := range renamePaths {
oldPaths = append(oldPaths, oldPath)
}
sort.Slice(oldPaths, func(i, j int) bool {
return strings.Count(oldPaths[i], string(os.PathSeparator)) < strings.Count(oldPaths[j], string(os.PathSeparator))
})
for i, oldPath := range oldPaths {
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)
err = errors.New("rename path failed")
return
}
delete(renamePaths, oldPath)
var toRemoves []string
newRenamedPaths := map[string]string{}
for oldP, newP := range renamePaths {
if strings.HasPrefix(oldP, oldPath) {
renamedOldP := strings.Replace(oldP, oldPath, newPath, 1)
newRenamedPaths[renamedOldP] = newP
toRemoves = append(toRemoves, oldPath)
}
}
for _, toRemove := range toRemoves {
delete(renamePaths, toRemove)
}
maps.Copy(renamePaths, newRenamedPaths)
for j := i + 1; j < len(oldPaths); j++ {
if strings.HasPrefix(oldPaths[j], oldPath) {
renamedOldP := strings.Replace(oldPaths[j], oldPath, newPath, 1)
oldPaths[j] = renamedOldP
}
}
}
// 将包含的资源文件统一移动到 assets 下
// 加密笔记本拷到 <boxID>/assets/,普通笔记本拷到全局 data/assets/
// 加密笔记本同时收集「原始名 → 脱敏名」映射,用于后续更新文档内的引用路径
assetNameMap := map[string]string{} // 原始文件名 → 脱敏文件名
var assetsDirs []string
filelock.Walk(unzipRootPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d == nil || unzipRootPath == path {
return nil
}
if d.Name() == "assets" && d.IsDir() {
assetsDirs = append(assetsDirs, path)
}
return nil
})
dataAssets := filepath.Join(util.DataDir, "assets")
if IsEncryptedBox(boxID) {
// 加密笔记本的资源文件拷到笔记本级 assets 目录,文件名脱敏 + 内容加密
boxAssetsDir := filepath.Join(util.DataDir, boxID, "assets")
if err = os.MkdirAll(boxAssetsDir, 0755); err != nil {
return
}
for _, assets := range assetsDirs {
if gulu.File.IsDir(assets) {
filelock.Walk(assets, func(path string, d fs.DirEntry, err error) error {
if err != nil || d == nil || d.IsDir() {
return err
}
originalName := d.Name()
ext := filepath.Ext(originalName)
blockID := ast.NewNodeID()
diskName := encryptedAssetName(ext, blockID)
assetNameMap[originalName] = diskName
// 读取明文内容 → 加密 → 写入脱敏文件名
src, readErr := filelock.ReadFile(path)
if readErr != nil {
return readErr
}
if err = writeAssetFile(filepath.Join(boxAssetsDir, diskName), bytes.NewReader(src), boxID, originalName); err != nil {
return err
}
return nil
})
if err != nil {
return
}
}
os.RemoveAll(assets)
}
} else {
for _, assets := range assetsDirs {
if gulu.File.IsDir(assets) {
if err = filelock.Copy(assets, dataAssets); err != nil {
logging.LogErrorf("copy assets from [%s] to [%s] failed: %s", assets, dataAssets, err)
return
}
}
os.RemoveAll(assets)
}
}
// AV 定义已在 storage 删除前处理(加密笔记本DEK 加密拷到笔记本级,
// 普通 box 拷到全局 storage/av/),这里不再重复处理
// 将包含的自定义表情统一移动到 data/emojis/ 下
unzipRootEmojisPath := filepath.Join(unzipRootPath, "emojis")
filelock.Walk(unzipRootEmojisPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d == nil {
return nil
}
if !util.IsValidUploadFileName(d.Name()) {
emojiFullName := path
fullPathFilteredName := filepath.Join(filepath.Dir(path), util.FilterUploadEmojiFileName(d.Name()))
// XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
logging.LogWarnf("renaming invalid custom emoji file [%s] to [%s]", d.Name(), fullPathFilteredName)
if removeErr := filelock.Rename(emojiFullName, fullPathFilteredName); nil != removeErr {
logging.LogErrorf("renaming invalid custom emoji file to [%s] failed: %s", fullPathFilteredName, removeErr)
}
}
return nil
})
var emojiDirs []string
filelock.Walk(unzipRootPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d == nil || unzipRootPath == path {
return nil
}
if d.Name() == "emojis" && d.IsDir() {
emojiDirs = append(emojiDirs, path)
}
return nil
})
dataEmojis := filepath.Join(util.DataDir, "emojis")
for _, emojis := range emojiDirs {
if gulu.File.IsDir(emojis) {
if err = filelock.Copy(emojis, dataEmojis); err != nil {
logging.LogErrorf("copy emojis from [%s] to [%s] failed: %s", emojis, dataEmojis, err)
return
}
}
os.RemoveAll(emojis)
}
var baseTargetPath string
if "/" == toPath {
baseTargetPath = "/"
} else {
block := treenode.GetBlockTreeRootByPath(boxID, toPath)
if nil == block {
logging.LogErrorf("not found block by path [%s]", toPath)
return createdBoxID, nil
}
baseTargetPath = strings.TrimSuffix(block.Path, ".sy")
}
targetDir := filepath.Join(util.DataDir, boxID, baseTargetPath)
if err = os.MkdirAll(targetDir, 0755); err != nil {
return
}
var treePaths []string
filelock.Walk(unzipRootPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d == nil {
return nil
}
if d.IsDir() {
if strings.HasPrefix(d.Name(), ".") {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(d.Name(), ".sy") {
return nil
}
p := strings.TrimPrefix(path, unzipRootPath)
p = filepath.ToSlash(p)
treePaths = append(treePaths, p)
return nil
})
if err = filelock.Copy(unzipRootPath, targetDir); err != nil {
logging.LogErrorf("copy data dir from [%s] to [%s] failed: %s", unzipRootPath, util.DataDir, err)
err = errors.New("copy data failed")
return
}
boxAbsPath := filepath.Join(util.DataDir, boxID)
importedAvIDs := map[string]struct{}{}
for _, importedAvID := range avIDs {
importedAvIDs[importedAvID] = struct{}{}
}
for _, treePath := range treePaths {
absPath := filepath.Join(targetDir, treePath)
p := strings.TrimPrefix(absPath, boxAbsPath)
p = filepath.ToSlash(p)
cache.RemoveTreeDataInBox(util.GetTreeID(p), boxID)
cache.RemoveDocIALInBox(p, boxID)
tree, err := filesys.LoadTree(boxID, p, luteEngine)
if err != nil {
logging.LogErrorf("load tree [%s] failed: %s", treePath, err)
continue
}
// 加密笔记本:更新文档内的 assets 引用路径(原始名 → 脱敏名)
if IsEncryptedBox(boxID) && 0 < len(assetNameMap) {
updateImportedAssetRefs(tree, assetNameMap)
indexWriteTreeIndexQueue(tree)
}
treenode.IndexBlockTree(tree)
cache.PutDocIALInBox(tree.Path, tree.Box, parse.IAL2Map(tree.Root.KramdownIAL))
var avNodes []*ast.Node
for _, avNode := range tree.Root.ChildrenByType(ast.NodeAttributeView) {
if _, ok := importedAvIDs[avNode.AttributeViewID]; ok {
avNodes = append(avNodes, avNode)
}
}
av.BatchUpsertBlockRel(avNodes)
sql.IndexTreeQueue(tree)
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))
}
IncSync()
task.AppendTask(task.UpdateIDs, util.PushUpdateIDs, blockIDs)
return
}
func writeImportedTree(boxID, syPath, newSyPath, relPath string, data []byte) error {
if IsEncryptedBox(boxID) {
HoldBoxReadLock(boxID)
defer ReleaseBoxReadLock(boxID)
dek, err := GetDEKIfUnlocked(boxID)
if err != nil {
return errors.New(Conf.Language(314))
}
data, err = EncryptFile(boxID, relPath, dek, data)
if err != nil {
return err
}
}
if err := os.WriteFile(syPath, data, 0644); err != nil {
return err
}
return filelock.Rename(syPath, newSyPath)
}
// updateImportedAssetRefs 遍历树的 assets 引用路径,将原始文件名替换为脱敏文件名。
// 覆盖:链接 href、图片 src、data-src、音视频 src、文件标注等。
func updateImportedAssetRefs(tree *parse.Tree, assetNameMap map[string]string) {
boxSuffix := ""
if IsEncryptedBox(tree.Box) {
boxSuffix = "?box=" + tree.Box
}
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
switch n.Type {
case ast.NodeLink:
// 链接 dest
dest := string(n.Tokens)
if updated := replaceAssetName(dest, assetNameMap, boxSuffix); updated != dest {
n.Tokens = []byte(updated)
}
case ast.NodeImage:
// 图片 src 在 LinkDest 子节点
if dest := n.ChildByType(ast.NodeLinkDest); nil != dest {
src := string(dest.Tokens)
if updated := replaceAssetName(src, assetNameMap, boxSuffix); updated != src {
dest.Tokens = []byte(updated)
}
}
case ast.NodeAudio, ast.NodeVideo:
src := n.TokensStr()
if updated := replaceAssetName(src, assetNameMap, boxSuffix); updated != src {
n.Tokens = []byte(updated)
}
case ast.NodeTextMark:
// 行级文本标记里的 data-href(附件链接)
if "" != n.TextMarkAHref {
if updated := replaceAssetName(n.TextMarkAHref, assetNameMap, boxSuffix); updated != n.TextMarkAHref {
n.TextMarkAHref = updated
}
}
}
return ast.WalkContinue
})
}
// replaceAssetName 在 assets 路径中替换原始文件名为脱敏文件名,并按需追加 box query。
func replaceAssetName(path string, assetNameMap map[string]string, boxSuffix string) string {
if !strings.Contains(path, "assets/") {