-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathconf.go
More file actions
1310 lines (1168 loc) · 38.9 KB
/
Copy pathconf.go
File metadata and controls
1310 lines (1168 loc) · 38.9 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"
"crypto/sha1"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/88250/gulu"
"github.com/88250/lute"
"github.com/88250/lute/ast"
"github.com/Xuanwo/go-locale"
"github.com/sashabaranov/go-openai"
"github.com/siyuan-note/eventbus"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/conf"
"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"
"golang.org/x/mod/semver"
"golang.org/x/text/language"
)
var Conf *AppConf
// AppConf 维护应用元数据,保存在 ~/.siyuan/conf.json。
type AppConf struct {
LogLevel string `json:"logLevel"` // 日志级别:off, trace, debug, info, warn, error, fatal
Appearance *conf.Appearance `json:"appearance"` // 外观
Langs []*conf.Lang `json:"langs"` // 界面语言列表
Lang string `json:"lang"` // 选择的界面语言,同 Appearance.Lang
FileTree *conf.FileTree `json:"fileTree"` // 文档面板
Tag *conf.Tag `json:"tag"` // 标签面板
Editor *conf.Editor `json:"editor"` // 编辑器配置
Export *conf.Export `json:"export"` // 导出配置
Graph *conf.Graph `json:"graph"` // 关系图配置
UILayout *conf.UILayout `json:"uiLayout"` // 界面布局。不要直接使用,使用 GetUILayout() 和 SetUILayout() 方法
UserData string `json:"userData"` // 社区用户信息,对 User 加密存储
User *conf.User `json:"-"` // 社区用户内存结构,不持久化。不要直接使用,使用 GetUser() 和 SetUser() 方法
Account *conf.Account `json:"account"` // 帐号配置
ReadOnly bool `json:"readonly"` // 是否是以只读模式运行
ServerAddrs []string `json:"serverAddrs"` // 本地服务器地址列表
AccessAuthCode string `json:"accessAuthCode"` // 访问授权码
System *conf.System `json:"system"` // 系统配置
Keymap *conf.Keymap `json:"keymap"` // 快捷键配置
Sync *conf.Sync `json:"sync"` // 同步配置
Search *conf.Search `json:"search"` // 搜索配置
Flashcard *conf.Flashcard `json:"flashcard"` // 闪卡配置
AI *conf.AI `json:"ai"` // 人工智能配置
Bazaar *conf.Bazaar `json:"bazaar"` // 集市配置
Stat *conf.Stat `json:"stat"` // 统计
Api *conf.API `json:"api"` // API
Repo *conf.Repo `json:"repo"` // 数据仓库
Publish *conf.Publish `json:"publish"` // 发布服务
OpenHelp bool `json:"openHelp"` // 启动后是否需要打开用户指南
ShowChangelog bool `json:"showChangelog"` // 是否显示版本更新日志
CloudRegion int `json:"cloudRegion"` // 云端区域,0:中国大陆,1:北美
Snippet *conf.Snpt `json:"snippet"` // 代码片段
DataIndexState int `json:"dataIndexState"` // 数据索引状态,0:已索引,1:未索引
CookieKey string `json:"cookieKey"` // 用于加密 Cookie 的密钥
m *sync.RWMutex // 配置数据锁
userLock *sync.RWMutex // 用户数据独立锁,避免与配置保存操作竞争
}
func NewAppConf() *AppConf {
return &AppConf{
LogLevel: "debug",
m: &sync.RWMutex{},
userLock: &sync.RWMutex{},
}
}
func (conf *AppConf) GetUILayout() *conf.UILayout {
conf.m.Lock()
defer conf.m.Unlock()
return conf.UILayout
}
func (conf *AppConf) SetUILayout(uiLayout *conf.UILayout) {
conf.m.Lock()
defer conf.m.Unlock()
conf.UILayout = uiLayout
}
func (conf *AppConf) GetUser() *conf.User {
conf.userLock.RLock()
defer conf.userLock.RUnlock()
return conf.User
}
func (conf *AppConf) SetUser(user *conf.User) {
conf.userLock.Lock()
defer conf.userLock.Unlock()
conf.User = user
}
func InitConf() {
initLang()
Conf = NewAppConf()
confPath := filepath.Join(util.ConfDir, "conf.json")
if gulu.File.IsExist(confPath) {
if data, err := os.ReadFile(confPath); err != nil {
logging.LogErrorf("load conf [%s] failed: %s", confPath, err)
} else {
if err = gulu.JSON.UnmarshalJSON(data, Conf); err != nil {
logging.LogErrorf("parse conf [%s] failed: %s", confPath, err)
} else {
logging.LogInfof("loaded conf [%s]", confPath)
}
}
}
if "" != util.Lang {
initialized := false
if util.IsMobileContainer() {
// 移动端以上次设置的外观语言为准
if "" != Conf.Lang && util.Lang != Conf.Lang {
util.Lang = Conf.Lang
logging.LogInfof("use the last specified language [%s]", util.Lang)
initialized = true
}
}
if !initialized {
Conf.Lang = util.Lang
logging.LogInfof("initialized the specified language [%s]", util.Lang)
}
} else {
if "" == Conf.Lang {
// 未指定外观语言时使用系统语言
if userLang, err := locale.Detect(); err == nil {
var supportLangs []language.Tag
for lang := range util.Langs {
if tag, err := language.Parse(lang); err == nil {
supportLangs = append(supportLangs, tag)
} else {
logging.LogErrorf("load language [%s] failed: %s", lang, err)
}
}
matcher := language.NewMatcher(supportLangs)
lang, _, _ := matcher.Match(userLang)
base, _ := lang.Base()
region, _ := lang.Region()
util.Lang = base.String() + "_" + region.String()
Conf.Lang = util.Lang
logging.LogInfof("initialized language [%s] based on device locale", Conf.Lang)
} else {
logging.LogDebugf("check device locale failed [%s], using default language [en_US]", err)
util.Lang = "en_US"
Conf.Lang = util.Lang
}
}
util.Lang = Conf.Lang
}
Conf.Langs = loadLangs()
if nil == Conf.Appearance {
Conf.Appearance = conf.NewAppearance()
}
var langOK bool
for _, l := range Conf.Langs {
if Conf.Lang == l.Name {
langOK = true
break
}
}
if !langOK {
Conf.Lang = "en_US"
util.Lang = Conf.Lang
}
Conf.Appearance.Lang = Conf.Lang
if "ant" == Conf.Appearance.Icon || "material" == Conf.Appearance.Icon {
// v3.7.0 移除了 ant/material 图标包,如果用户之前选择了这两个其中之一,升级后改为 litheness 图标包,避免图标显示异常 https://github.com/siyuan-note/siyuan/issues/7976
Conf.Appearance.Icon = "litheness"
}
os.RemoveAll(filepath.Join(util.IconsPath, "ant"))
os.RemoveAll(filepath.Join(util.IconsPath, "material"))
if nil == Conf.UILayout {
Conf.UILayout = &conf.UILayout{}
}
if nil == Conf.Keymap {
Conf.Keymap = &conf.Keymap{}
}
if "" == Conf.Appearance.CodeBlockThemeDark {
Conf.Appearance.CodeBlockThemeDark = "dracula"
}
if "" == Conf.Appearance.CodeBlockThemeLight {
Conf.Appearance.CodeBlockThemeLight = "github"
}
if nil == Conf.Appearance.StatusBar {
Conf.Appearance.StatusBar = &util.StatusBar{}
}
util.StatusBarCfg = Conf.Appearance.StatusBar
if nil == Conf.FileTree {
Conf.FileTree = conf.NewFileTree()
}
if 1 > Conf.FileTree.MaxListCount {
Conf.FileTree.MaxListCount = 512
}
if 1 > Conf.FileTree.MaxOpenTabCount {
Conf.FileTree.MaxOpenTabCount = 8
}
if 32 < Conf.FileTree.MaxOpenTabCount {
Conf.FileTree.MaxOpenTabCount = 32
}
Conf.FileTree.DocCreateSavePath = util.TrimSpaceInPath(Conf.FileTree.DocCreateSavePath)
Conf.FileTree.RefCreateSavePath = util.TrimSpaceInPath(Conf.FileTree.RefCreateSavePath)
Conf.FileTree.ShorthandSavePath = util.TrimSpaceInPath(Conf.FileTree.ShorthandSavePath)
util.UseSingleLineSave = Conf.FileTree.UseSingleLineSave
if 2 > Conf.FileTree.LargeFileWarningSize {
Conf.FileTree.LargeFileWarningSize = 8
}
util.LargeFileWarningSize = Conf.FileTree.LargeFileWarningSize
if nil == Conf.FileTree.CreateDocAtTop { // v3.4.0 之前的版本没有该字段,设置默认值为 true,即在顶部创建新文档,不改变用户习惯
Conf.FileTree.CreateDocAtTop = func() *bool { b := true; return &b }()
}
if conf.MinFileTreeRecentDocsListCount > Conf.FileTree.RecentDocsMaxListCount {
Conf.FileTree.RecentDocsMaxListCount = conf.MinFileTreeRecentDocsListCount
}
if conf.MaxFileTreeRecentDocsListCount < Conf.FileTree.RecentDocsMaxListCount {
Conf.FileTree.RecentDocsMaxListCount = conf.MaxFileTreeRecentDocsListCount
}
util.CurrentCloudRegion = Conf.CloudRegion
if nil == Conf.Tag {
Conf.Tag = conf.NewTag()
}
defaultEditor := conf.NewEditor()
if nil == Conf.Editor {
Conf.Editor = defaultEditor
}
// 新增字段的默认值,使用指针类型来区分字段不存在(nil)和用户设置为 0(非 nil)
if nil == Conf.Editor.BacklinkSort {
Conf.Editor.BacklinkSort = defaultEditor.BacklinkSort
}
if nil == Conf.Editor.BackmentionSort {
Conf.Editor.BackmentionSort = defaultEditor.BackmentionSort
}
if 1 > len(Conf.Editor.Emoji) {
Conf.Editor.Emoji = []string{}
}
for i, emoji := range Conf.Editor.Emoji {
if strings.Contains(emoji, ".") {
// XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
emoji = util.FilterUploadEmojiFileName(emoji)
Conf.Editor.Emoji[i] = emoji
}
}
if 9 > Conf.Editor.FontSize || 72 < Conf.Editor.FontSize {
Conf.Editor.FontSize = 16
}
if "" == Conf.Editor.PlantUMLServePath {
Conf.Editor.PlantUMLServePath = "https://www.plantuml.com/plantuml/svg/~1"
}
if 1 > Conf.Editor.BlockRefDynamicAnchorTextMaxLen {
Conf.Editor.BlockRefDynamicAnchorTextMaxLen = 64
}
if 5120 < Conf.Editor.BlockRefDynamicAnchorTextMaxLen {
Conf.Editor.BlockRefDynamicAnchorTextMaxLen = 5120
}
if nil == Conf.Editor.OpenLink {
Conf.Editor.OpenLink = defaultEditor.OpenLink
}
if 1440 < Conf.Editor.GenerateHistoryInterval {
Conf.Editor.GenerateHistoryInterval = 1440
}
if 1 > Conf.Editor.HistoryRetentionDays {
Conf.Editor.HistoryRetentionDays = 30
}
if 3650 < Conf.Editor.HistoryRetentionDays {
Conf.Editor.HistoryRetentionDays = 3650
}
if nil == Conf.Editor.FloatWindowDelay {
v := 620
Conf.Editor.FloatWindowDelay = &v
} else {
*Conf.Editor.FloatWindowDelay = max(0, min(2000, *Conf.Editor.FloatWindowDelay))
}
if conf.MinDynamicLoadBlocks > Conf.Editor.DynamicLoadBlocks {
Conf.Editor.DynamicLoadBlocks = conf.MinDynamicLoadBlocks
}
if 1 > len(Conf.Editor.SpellcheckLanguages) {
Conf.Editor.SpellcheckLanguages = []string{"en-US"}
}
if 0 > Conf.Editor.BacklinkExpandCount {
Conf.Editor.BacklinkExpandCount = 0
}
if -1 > Conf.Editor.BackmentionExpandCount {
Conf.Editor.BackmentionExpandCount = -1
}
if nil == Conf.Editor.Markdown {
Conf.Editor.Markdown = &util.Markdown{}
}
util.MarkdownSettings = Conf.Editor.Markdown
if nil == Conf.Export {
Conf.Export = conf.NewExport()
}
if 0 == Conf.Export.BlockRefMode || 1 == Conf.Export.BlockRefMode || 5 == Conf.Export.BlockRefMode {
// 废弃导出选项引用块转换为原始块和引述块 https://github.com/siyuan-note/siyuan/issues/3155
// 锚点哈希模式和脚注模式合并 https://github.com/siyuan-note/siyuan/issues/13331
Conf.Export.BlockRefMode = 4 // 改为脚注+锚点哈希
}
if "" == Conf.Export.PandocBin {
Conf.Export.PandocBin = util.PandocBinPath
}
if nil == Conf.Graph || nil == Conf.Graph.Local || nil == Conf.Graph.Global {
Conf.Graph = conf.NewGraph()
}
if nil == Conf.System {
Conf.System = conf.NewSystem()
if util.ContainerIOS != util.Container {
Conf.OpenHelp = true
}
} else {
cmp := semver.Compare("v"+util.Ver, "v"+Conf.System.KernelVersion)
if 0 < cmp {
logging.LogInfof("upgraded from version [%s] to [%s]", Conf.System.KernelVersion, util.Ver)
Conf.ShowChangelog = true
} else if 0 > cmp {
logging.LogInfof("downgraded from version [%s] to [%s]", Conf.System.KernelVersion, util.Ver)
}
Conf.System.KernelVersion = util.Ver
Conf.System.IsInsider = util.IsInsider
}
if nil == Conf.System.NetworkProxy {
Conf.System.NetworkProxy = &conf.NetworkProxy{}
}
if "" == Conf.System.ID {
Conf.System.ID = util.GetDeviceID()
}
if "" == Conf.System.Name {
Conf.System.Name = util.GetDeviceName()
}
if util.ContainerStd == util.Container {
Conf.System.ID = util.GetDeviceID()
Conf.System.Name = util.GetDeviceName()
}
Conf.System.DisabledFeatures = util.DisabledFeatures
if 1 > len(Conf.System.DisabledFeatures) {
Conf.System.DisabledFeatures = []string{}
}
Conf.System.AppDir = util.WorkingDir
Conf.System.ConfDir = util.ConfDir
Conf.System.HomeDir = util.HomeDir
Conf.System.WorkspaceDir = util.WorkspaceDir
Conf.System.DataDir = util.DataDir
Conf.System.Container = util.Container
Conf.System.IsMicrosoftStore = util.ISMicrosoftStore
if util.ISMicrosoftStore {
logging.LogInfof("using Microsoft Store edition")
}
Conf.System.OS = runtime.GOOS
Conf.System.OSPlatform = util.GetOSPlatform()
docxTemplate := util.RemoveInvalid(Conf.Export.DocxTemplate)
if "" != docxTemplate {
params := util.RemoveInvalid(Conf.Export.PandocParams)
if gulu.File.IsExist(docxTemplate) && !strings.Contains(params, "--reference-doc") && !Conf.System.IsMicrosoftStore {
if !strings.HasPrefix(docxTemplate, "\"") {
docxTemplate = "\"" + docxTemplate + "\""
}
params += " --reference-doc " + docxTemplate
Conf.Export.PandocParams = strings.TrimSpace(params)
}
Conf.Export.DocxTemplate = ""
Conf.Save()
}
if nil == Conf.Snippet {
Conf.Snippet = conf.NewSnpt()
}
if "" != Conf.UserData {
Conf.SetUser(loadUserFromConf())
}
if nil == Conf.Account {
Conf.Account = conf.NewAccount()
}
if nil == Conf.Sync {
Conf.Sync = conf.NewSync()
}
if 0 == Conf.Sync.Mode {
Conf.Sync.Mode = 1
}
if 30 > Conf.Sync.Interval {
Conf.Sync.Interval = 30
}
if 60*60*12 < Conf.Sync.Interval {
Conf.Sync.Interval = 60 * 60 * 12
}
if nil == Conf.Sync.S3 {
Conf.Sync.S3 = &conf.S3{PathStyle: true, SkipTlsVerify: true}
}
Conf.Sync.S3.Endpoint = util.NormalizeEndpoint(Conf.Sync.S3.Endpoint)
Conf.Sync.S3.Timeout = util.NormalizeTimeout(Conf.Sync.S3.Timeout)
Conf.Sync.S3.ConcurrentReqs = util.NormalizeConcurrentReqs(Conf.Sync.S3.ConcurrentReqs, conf.ProviderS3)
if nil == Conf.Sync.WebDAV {
Conf.Sync.WebDAV = &conf.WebDAV{SkipTlsVerify: true}
}
Conf.Sync.WebDAV.Endpoint = util.NormalizeEndpoint(Conf.Sync.WebDAV.Endpoint)
Conf.Sync.WebDAV.Timeout = util.NormalizeTimeout(Conf.Sync.WebDAV.Timeout)
Conf.Sync.WebDAV.ConcurrentReqs = util.NormalizeConcurrentReqs(Conf.Sync.WebDAV.ConcurrentReqs, conf.ProviderWebDAV)
if nil == Conf.Sync.Local {
Conf.Sync.Local = &conf.Local{}
}
Conf.Sync.Local.Endpoint = util.NormalizeLocalPath(Conf.Sync.Local.Endpoint)
Conf.Sync.Local.Timeout = util.NormalizeTimeout(Conf.Sync.Local.Timeout)
Conf.Sync.Local.ConcurrentReqs = util.NormalizeConcurrentReqs(Conf.Sync.Local.ConcurrentReqs, conf.ProviderLocal)
if util.ContainerDocker == util.Container {
Conf.Sync.Perception = false
}
if nil == Conf.Api {
Conf.Api = conf.NewAPI()
}
if nil == Conf.Bazaar {
Conf.Bazaar = conf.NewBazaar()
}
if nil == Conf.Publish {
Conf.Publish = conf.NewPublish()
}
if Conf.OpenHelp && Conf.Publish.Enable {
Conf.OpenHelp = false
}
if nil == Conf.Repo {
Conf.Repo = conf.NewRepo()
}
if timingEnv := os.Getenv("SIYUAN_SYNC_INDEX_TIMING"); "" != timingEnv {
val, err := strconv.Atoi(timingEnv)
if err == nil {
Conf.Repo.SyncIndexTiming = int64(val)
}
}
if 12000 > Conf.Repo.SyncIndexTiming {
Conf.Repo.SyncIndexTiming = 12 * 1000
}
if 1 > Conf.Repo.IndexRetentionDays {
Conf.Repo.IndexRetentionDays = 180
}
if 1 > Conf.Repo.RetentionIndexesDaily {
Conf.Repo.RetentionIndexesDaily = 2
}
if 0 < len(Conf.Repo.Key) {
logging.LogInfof("repo key [%x]", sha1.Sum(Conf.Repo.Key))
}
if nil == Conf.Search {
Conf.Search = conf.NewSearch()
}
if 1 > Conf.Search.Limit {
Conf.Search.Limit = 64
}
if 32 > Conf.Search.Limit {
Conf.Search.Limit = 32
}
if 1 > Conf.Search.BacklinkMentionKeywordsLimit {
Conf.Search.BacklinkMentionKeywordsLimit = 512
}
if nil == Conf.Stat {
Conf.Stat = conf.NewStat()
}
if nil == Conf.Flashcard {
Conf.Flashcard = conf.NewFlashcard()
}
if 0 > Conf.Flashcard.NewCardLimit {
Conf.Flashcard.NewCardLimit = 20
}
if 0 > Conf.Flashcard.ReviewCardLimit {
Conf.Flashcard.ReviewCardLimit = 200
}
if 0 >= Conf.Flashcard.RequestRetention || 1 <= Conf.Flashcard.RequestRetention {
Conf.Flashcard.RequestRetention = conf.NewFlashcard().RequestRetention
}
if 0 >= Conf.Flashcard.MaximumInterval || 36500 <= Conf.Flashcard.MaximumInterval {
Conf.Flashcard.MaximumInterval = conf.NewFlashcard().MaximumInterval
}
if "" == Conf.Flashcard.Weights {
Conf.Flashcard.Weights = conf.NewFlashcard().Weights
}
if 19 != len(strings.Split(Conf.Flashcard.Weights, ",")) {
defaultWeights := conf.DefaultFSRSWeights()
msg := "fsrs store weights length must be [19]"
logging.LogWarnf("%s , given [%s], reset to default weights [%s]", msg, Conf.Flashcard.Weights, defaultWeights)
Conf.Flashcard.Weights = defaultWeights
go func() {
util.WaitForUILoaded()
task.AppendAsyncTaskWithDelay(task.PushMsg, 2*time.Second, util.PushErrMsg, msg, 15000)
}()
}
isInvalidFlashcardWeights := false
for _, w := range strings.Split(Conf.Flashcard.Weights, ",") {
if _, err := strconv.ParseFloat(strings.TrimSpace(w), 64); err != nil {
isInvalidFlashcardWeights = true
break
}
}
if isInvalidFlashcardWeights {
defaultWeights := conf.DefaultFSRSWeights()
msg := "fsrs store weights contain invalid number"
logging.LogWarnf("%s, given [%s], reset to default weights [%s]", msg, Conf.Flashcard.Weights, defaultWeights)
Conf.Flashcard.Weights = defaultWeights
go func() {
util.WaitForUILoaded()
task.AppendAsyncTaskWithDelay(task.PushMsg, 2*time.Second, util.PushErrMsg, msg, 15000)
}()
}
if nil == Conf.AI {
Conf.AI = conf.NewAI()
}
if "" == Conf.AI.OpenAI.APIModel {
Conf.AI.OpenAI.APIModel = openai.GPT3Dot5Turbo
}
if "" == Conf.AI.OpenAI.APIUserAgent {
Conf.AI.OpenAI.APIUserAgent = util.UserAgent
}
if strings.HasPrefix(Conf.AI.OpenAI.APIUserAgent, "SiYuan/") {
Conf.AI.OpenAI.APIUserAgent = util.UserAgent
}
if "" == Conf.AI.OpenAI.APIProvider {
Conf.AI.OpenAI.APIProvider = "OpenAI"
}
if 0 > Conf.AI.OpenAI.APIMaxTokens {
Conf.AI.OpenAI.APIMaxTokens = 0
}
if 0 >= Conf.AI.OpenAI.APITemperature || 2 < Conf.AI.OpenAI.APITemperature {
Conf.AI.OpenAI.APITemperature = 1.0
}
if 1 > Conf.AI.OpenAI.APIMaxContexts || 64 < Conf.AI.OpenAI.APIMaxContexts {
Conf.AI.OpenAI.APIMaxContexts = 7
}
if "" != Conf.AI.OpenAI.APIKey {
logging.LogInfof("OpenAI API enabled\n"+
" userAgent=%s\n"+
" baseURL=%s\n"+
" timeout=%ds\n"+
" proxy=%s\n"+
" model=%s\n"+
" maxTokens=%d\n"+
" temperature=%.1f\n"+
" maxContexts=%d",
Conf.AI.OpenAI.APIUserAgent,
Conf.AI.OpenAI.APIBaseURL,
Conf.AI.OpenAI.APITimeout,
Conf.AI.OpenAI.APIProxy,
Conf.AI.OpenAI.APIModel,
Conf.AI.OpenAI.APIMaxTokens,
Conf.AI.OpenAI.APITemperature,
Conf.AI.OpenAI.APIMaxContexts)
}
Conf.ReadOnly = util.ReadOnly
if "" != util.AccessAuthCode {
Conf.AccessAuthCode = util.AccessAuthCode
}
Conf.AccessAuthCode = util.RemoveInvalid(Conf.AccessAuthCode)
Conf.AccessAuthCode = strings.TrimSpace(Conf.AccessAuthCode)
if 1 == Conf.DataIndexState {
// 上次未正常完成数据索引,后续会由 recoverIndexQueue() 恢复
logging.LogInfof("data index state is [%d], will recover through index queue", Conf.DataIndexState)
}
Conf.DataIndexState = 0
if cookieKey := readCookieKey(); "" != cookieKey {
Conf.CookieKey = cookieKey
} else {
if "" == Conf.CookieKey {
Conf.CookieKey = gulu.Rand.String(16)
}
writeCookieKey(Conf.CookieKey)
}
Conf.Save()
logging.SetLogLevel(Conf.LogLevel)
util.SetNetworkProxy(Conf.System.NetworkProxy.String())
go util.InitPandoc()
go util.InitTesseract()
}
func readCookieKey() (cookieKey string) {
cookieKeyPath := filepath.Join(util.HomeDir, ".config", "siyuan", "cookie.key")
if !gulu.File.IsExist(cookieKeyPath) {
return
}
data, err := os.ReadFile(cookieKeyPath)
if err != nil {
logging.LogErrorf("read cookie key file [%s] failed: %s", cookieKeyPath, err)
return
}
cookieKey = string(bytes.TrimSpace(data))
return
}
func writeCookieKey(cookieKey string) {
cookieKeyPath := filepath.Join(util.HomeDir, ".config", "siyuan", "cookie.key")
if gulu.File.IsExist(cookieKeyPath) {
return
}
if err := os.WriteFile(cookieKeyPath, []byte(cookieKey), 0644); err != nil {
logging.LogErrorf("save cookie key file [%s] failed: %s", cookieKeyPath, err)
}
}
func initLang() {
p := filepath.Join(util.WorkingDir, "appearance", "langs")
dir, err := os.Open(p)
if err != nil {
logging.LogErrorf("open language configuration folder [%s] failed: %s", p, err)
util.ReportFileSysFatalError(err)
return
}
defer dir.Close()
langNames, err := dir.Readdirnames(-1)
if err != nil {
logging.LogErrorf("list language configuration folder [%s] failed: %s", p, err)
util.ReportFileSysFatalError(err)
return
}
for _, langName := range langNames {
jsonPath := filepath.Join(p, langName)
data, err := os.ReadFile(jsonPath)
if err != nil {
logging.LogErrorf("read language configuration [%s] failed: %s", jsonPath, err)
continue
}
data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
langMap := map[string]any{}
if err := gulu.JSON.UnmarshalJSON(data, &langMap); err != nil {
logging.LogErrorf("parse language configuration failed [%s] failed: %s", jsonPath, err)
continue
}
kernelMap := map[int]string{}
label := langMap["_label"].(string)
kernelLangs := langMap["_kernel"].(map[string]any)
for k, v := range kernelLangs {
num, convErr := strconv.Atoi(k)
if nil != convErr {
logging.LogErrorf("parse language configuration [%s] item [%d] failed: %s", p, num, convErr)
continue
}
kernelMap[num] = v.(string)
}
kernelMap[-1] = label
name := langName[:strings.LastIndex(langName, ".")]
util.Langs[name] = kernelMap
util.TimeLangs[name] = langMap["_time"].(map[string]any)
util.TaskActionLangs[name] = langMap["_taskAction"].(map[string]any)
util.TrayMenuLangs[name] = langMap["_trayMenu"].(map[string]any)
util.AttrViewLangs[name] = langMap["_attrView"].(map[string]any)
}
}
func loadLangs() (ret []*conf.Lang) {
for name, langMap := range util.Langs {
lang := &conf.Lang{Label: langMap[-1], Name: name}
ret = append(ret, lang)
}
sort.Slice(ret, func(i, j int) bool {
return ret[i].Name < ret[j].Name
})
return
}
var exitLock = sync.Mutex{}
// Close 退出内核进程.
//
// force:是否不执行同步过程而直接退出
//
// setCurrentWorkspace:是否将当前工作空间放到工作空间列表的最后一个
//
// execInstallPkg:是否执行新版本安装包
//
// 0:默认按照设置项 System.DownloadInstallPkg 检查并推送提示
// 1:不执行新版本安装
// 2:执行新版本安装
//
// 返回值 exitCode:
//
// 0:正常退出
// 1:同步执行失败
// 2:提示新安装包
//
// 当 force 为 true(强制退出)并且 execInstallPkg 为 0(默认检查更新)并且同步失败并且新版本安装版已经准备就绪时,执行新版本安装 https://github.com/siyuan-note/siyuan/issues/10288
func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int) {
exitLock.Lock()
defer exitLock.Unlock()
logging.LogInfof("exiting kernel [force=%v, setCurrentWorkspace=%v, execInstallPkg=%d]", force, setCurrentWorkspace, execInstallPkg)
util.PushMsg(Conf.Language(95), 10000*60)
FlushTxQueue()
if !force {
// Stop kernel plugins early in shutdown
if OnKernelPluginsStop != nil {
OnKernelPluginsStop()
}
if Conf.Sync.Enabled && 3 != Conf.Sync.Mode &&
((IsSubscriber() && conf.ProviderSiYuan == Conf.Sync.Provider) || conf.ProviderSiYuan != Conf.Sync.Provider) {
syncData(true, false)
if 0 != ExitSyncSucc {
exitCode = 1
return
}
}
}
// Close the user guide when exiting https://github.com/siyuan-note/siyuan/issues/10322
closeUserGuide()
// Improve indexing completeness when exiting https://github.com/siyuan-note/siyuan/issues/12039
sql.FlushQueue()
util.IsExiting.Store(true)
waitSecondForExecInstallPkg := false
newVerInstallPkgPath := getNewVerInstallPkgPath()
if !skipNewVerInstallPkg() && "" != newVerInstallPkgPath {
if 2 == execInstallPkg || (force && 0 == execInstallPkg) { // 执行新版本安装
waitSecondForExecInstallPkg = true
if gulu.OS.IsWindows() {
util.PushMsg(Conf.Language(130), 1000*30)
}
go execNewVerInstallPkg(newVerInstallPkgPath)
} else if 0 == execInstallPkg { // 新版本安装包已经准备就绪
exitCode = 2
logging.LogInfof("the new version install pkg is ready [%s], waiting for the user's next instruction", newVerInstallPkgPath)
return
}
}
Conf.Close()
sql.CloseDatabase()
closePushQueue()
util.SaveAssetsTexts()
clearWorkspaceTemp()
clearCorruptedNotebooks()
clearPortJSON()
if setCurrentWorkspace {
// 将当前工作空间放到工作空间列表的最后一个
// Open the last workspace by default https://github.com/siyuan-note/siyuan/issues/10570
workspacePaths, err := util.ReadWorkspacePaths()
if err != nil {
logging.LogErrorf("read workspace paths failed: %s", err)
} else {
workspacePaths = gulu.Str.RemoveElem(workspacePaths, util.WorkspaceDir)
workspacePaths = append(workspacePaths, util.WorkspaceDir)
util.WriteWorkspacePaths(workspacePaths)
}
}
util.BroadcastByType("main", "exit", 0, "", nil)
util.UnlockWorkspace()
time.Sleep(500 * time.Millisecond)
if waitSecondForExecInstallPkg {
// 桌面端退出拉起更新安装时有时需要重启两次 https://github.com/siyuan-note/siyuan/issues/6544
// 这里多等待一段时间,等待安装程序启动
if gulu.OS.IsWindows() {
time.Sleep(30 * time.Second)
}
}
closeSyncWebSocket()
go func() {
time.Sleep(500 * time.Millisecond)
logging.LogInfof("exited kernel")
if nil != util.WebSocketServer {
util.WebSocketServer.Close()
}
if nil != util.HttpServer {
util.HttpServer.Close()
}
util.HttpServing = false
if util.IsMobileContainer() {
return
}
os.Exit(logging.ExitCodeOk)
}()
return
}
var customEmojis = sync.Map{}
func AddCustomEmoji(emojiName, imgSrc string) {
customEmojis.Store(emojiName, imgSrc)
}
func ClearCustomEmojis() {
customEmojis.Clear()
}
func NewLute() (ret *lute.Lute) {
ret = util.NewLute()
ret.SetCodeSyntaxHighlightLineNum(Conf.Editor.CodeSyntaxHighlightLineNum)
ret.SetChineseParagraphBeginningSpace(Conf.Export.ParagraphBeginningSpace)
ret.SetProtyleMarkNetImg(Conf.Editor.DisplayNetImgMark)
ret.SetSpellcheck(Conf.Editor.Spellcheck)
customEmojiMap := map[string]string{}
customEmojis.Range(func(key, value any) bool {
customEmojiMap[key.(string)] = value.(string)
return true
})
ret.PutEmojis(customEmojiMap)
return
}
func enableLuteInlineSyntax(luteEngine *lute.Lute) {
luteEngine.SetInlineAsterisk(true)
luteEngine.SetInlineUnderscore(true)
luteEngine.SetSup(true)
luteEngine.SetSub(true)
luteEngine.SetTag(true)
luteEngine.SetInlineMath(true)
luteEngine.SetGFMStrikethrough(true)
}
func (conf *AppConf) Save() {
if util.ReadOnly {
return
}
Conf.m.Lock()
defer Conf.m.Unlock()
newData, _ := gulu.JSON.MarshalIndentJSON(Conf, "", " ")
confPath := filepath.Join(util.ConfDir, "conf.json")
oldData, err := filelock.ReadFile(confPath)
if err != nil {
conf.save0(newData)
return
}
if bytes.Equal(newData, oldData) {
return
}
conf.save0(newData)
}
func (conf *AppConf) save0(data []byte) {
confPath := filepath.Join(util.ConfDir, "conf.json")
if err := filelock.WriteFile(confPath, data); err != nil {
logging.LogErrorf("write conf [%s] failed: %s", confPath, err)
util.ReportFileSysFatalError(err)
return
}
}
func (conf *AppConf) Close() {
conf.Save()
}
func (conf *AppConf) Box(boxID string) *Box {
for _, box := range conf.GetOpenedBoxes() {
if box.ID == boxID {
return box
}
}
return nil
}
func (conf *AppConf) GetBox(boxID string) *Box {
for _, box := range conf.GetBoxes() {
if box.ID == boxID {
return box
}
}
return nil
}
func (conf *AppConf) BoxNames(boxIDs []string) (ret map[string]string) {
ret = map[string]string{}
boxes := conf.GetOpenedBoxes()
for _, boxID := range boxIDs {
for _, box := range boxes {
if box.ID == boxID {
ret[boxID] = box.Name
break
}
}
}
return
}
func (conf *AppConf) GetBoxes() (ret []*Box) {
ret = []*Box{}
notebooks, err := ListNotebooks()
if err != nil {
return
}
for _, notebook := range notebooks {
id := notebook.ID
name := notebook.Name
closed := notebook.Closed
box := &Box{ID: id, Name: name, Closed: closed}
ret = append(ret, box)
}
return
}
func (conf *AppConf) GetOpenedBoxes() (ret []*Box) {
ret = []*Box{}
notebooks, err := ListNotebooks()
if err != nil {
return
}
for _, notebook := range notebooks {
if !notebook.Closed {
ret = append(ret, notebook)
}
}
return
}
func (conf *AppConf) GetClosedBoxes() (ret []*Box) {
ret = []*Box{}
notebooks, err := ListNotebooks()
if err != nil {
return
}
for _, notebook := range notebooks {
if notebook.Closed {
ret = append(ret, notebook)
}
}
return
}
func (conf *AppConf) Language(num int) (ret string) {
ret = conf.language(num)
ret = strings.ReplaceAll(ret, "${accountServer}", util.GetCloudAccountServer())
return