repository.go 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package model
  17. import (
  18. "bytes"
  19. "crypto/rand"
  20. "crypto/sha1"
  21. "crypto/sha256"
  22. "encoding/base64"
  23. "errors"
  24. "fmt"
  25. "math"
  26. mathRand "math/rand"
  27. "mime"
  28. "net/http"
  29. "os"
  30. "path"
  31. "path/filepath"
  32. "sort"
  33. "strings"
  34. "sync"
  35. "sync/atomic"
  36. "time"
  37. "github.com/88250/go-humanize"
  38. "github.com/88250/gulu"
  39. "github.com/88250/lute"
  40. "github.com/88250/lute/ast"
  41. "github.com/88250/lute/html"
  42. "github.com/88250/lute/parse"
  43. "github.com/88250/lute/render"
  44. "github.com/emirpasic/gods/sets/hashset"
  45. "github.com/siyuan-note/dejavu"
  46. "github.com/siyuan-note/dejavu/cloud"
  47. "github.com/siyuan-note/dejavu/entity"
  48. "github.com/siyuan-note/encryption"
  49. "github.com/siyuan-note/eventbus"
  50. "github.com/siyuan-note/httpclient"
  51. "github.com/siyuan-note/logging"
  52. "github.com/siyuan-note/siyuan/kernel/conf"
  53. "github.com/siyuan-note/siyuan/kernel/filesys"
  54. "github.com/siyuan-note/siyuan/kernel/sql"
  55. "github.com/siyuan-note/siyuan/kernel/task"
  56. "github.com/siyuan-note/siyuan/kernel/treenode"
  57. "github.com/siyuan-note/siyuan/kernel/util"
  58. "github.com/studio-b12/gowebdav"
  59. )
  60. // AutoPurgeRepoJob 自动清理数据仓库 https://github.com/siyuan-note/siyuan/issues/13091
  61. func AutoPurgeRepoJob() {
  62. task.AppendTaskWithTimeout(task.RepoAutoPurge, 12*time.Hour, autoPurgeRepo, true)
  63. }
  64. var (
  65. autoPurgeRepoAfterFirstSync = false
  66. lastAutoPurgeRepo = time.Time{}
  67. )
  68. func autoPurgeRepo(cron bool) {
  69. if cron && !autoPurgeRepoAfterFirstSync {
  70. return
  71. }
  72. if time.Since(lastAutoPurgeRepo) < 6*time.Hour {
  73. return
  74. }
  75. autoPurgeRepoAfterFirstSync = true
  76. defer func() {
  77. lastAutoPurgeRepo = time.Now()
  78. }()
  79. if 1 > len(Conf.Repo.Key) {
  80. return
  81. }
  82. repo, err := newRepository()
  83. if err != nil {
  84. return
  85. }
  86. now := time.Now()
  87. dateGroupedIndexes := map[string][]*entity.Index{} // 按照日期分组
  88. // 收集指定日期内需要保留的索引
  89. var date string
  90. page := 1
  91. for {
  92. indexes, pageCount, _, err := repo.GetIndexes(page, 512)
  93. if nil != err {
  94. logging.LogErrorf("get data repo index logs failed: %s", err)
  95. return
  96. }
  97. if 1 > len(indexes) {
  98. break
  99. }
  100. tooOld := false
  101. for _, index := range indexes {
  102. if now.UnixMilli()-index.Created <= int64(Conf.Repo.IndexRetentionDays)*24*60*60*1000 {
  103. date = time.UnixMilli(index.Created).Format("2006-01-02")
  104. if _, ok := dateGroupedIndexes[date]; !ok {
  105. dateGroupedIndexes[date] = []*entity.Index{}
  106. }
  107. dateGroupedIndexes[date] = append(dateGroupedIndexes[date], index)
  108. } else {
  109. tooOld = true
  110. break
  111. }
  112. }
  113. if tooOld {
  114. break
  115. }
  116. page++
  117. if page > pageCount {
  118. break
  119. }
  120. }
  121. todayDate := now.Format("2006-01-02")
  122. // 筛选出每日需要保留的索引
  123. var retentionIndexIDs []string
  124. for date, indexes := range dateGroupedIndexes {
  125. if len(indexes) <= Conf.Repo.RetentionIndexesDaily || todayDate == date {
  126. for _, index := range indexes {
  127. retentionIndexIDs = append(retentionIndexIDs, index.ID)
  128. }
  129. continue
  130. }
  131. keepIndexes := hashset.New()
  132. keepIndexes.Add(indexes[0]) // 每天最后一个固定保留
  133. // 随机保留指定数量的索引
  134. for i := 0; i < Conf.Repo.RetentionIndexesDaily*7; i++ {
  135. keepIndexes.Add(indexes[mathRand.Intn(len(indexes)-1)])
  136. if keepIndexes.Size() >= Conf.Repo.RetentionIndexesDaily {
  137. break
  138. }
  139. }
  140. for _, keepIndex := range keepIndexes.Values() {
  141. retentionIndexIDs = append(retentionIndexIDs, keepIndex.(*entity.Index).ID)
  142. }
  143. }
  144. retentionIndexIDs = gulu.Str.RemoveDuplicatedElem(retentionIndexIDs)
  145. if 3 > len(retentionIndexIDs) {
  146. logging.LogInfof("no index to purge [ellapsed=%.2fs]", time.Since(now).Seconds())
  147. return
  148. }
  149. _, err = repo.Purge(retentionIndexIDs...)
  150. }
  151. func GetRepoFile(fileID string) (ret []byte, p string, err error) {
  152. if 1 > len(Conf.Repo.Key) {
  153. err = errors.New(Conf.Language(26))
  154. return
  155. }
  156. repo, err := newRepository()
  157. if err != nil {
  158. return
  159. }
  160. file, err := repo.GetFile(fileID)
  161. if err != nil {
  162. return
  163. }
  164. ret, err = repo.OpenFile(file)
  165. p = file.Path
  166. return
  167. }
  168. func OpenRepoSnapshotDoc(fileID string) (title, content string, displayInText bool, updated int64, err error) {
  169. if 1 > len(Conf.Repo.Key) {
  170. err = errors.New(Conf.Language(26))
  171. return
  172. }
  173. repo, err := newRepository()
  174. if err != nil {
  175. return
  176. }
  177. file, err := repo.GetFile(fileID)
  178. if err != nil {
  179. return
  180. }
  181. data, err := repo.OpenFile(file)
  182. if err != nil {
  183. return
  184. }
  185. updated = file.Updated
  186. if strings.HasSuffix(file.Path, ".sy") {
  187. luteEngine := NewLute()
  188. var snapshotTree *parse.Tree
  189. displayInText, snapshotTree, err = parseTreeInSnapshot(data, luteEngine)
  190. if err != nil {
  191. logging.LogErrorf("parse tree from snapshot file [%s] failed", fileID)
  192. return
  193. }
  194. title = snapshotTree.Root.IALAttr("title")
  195. if !displayInText {
  196. renderTree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument}}
  197. var unlinks []*ast.Node
  198. ast.Walk(snapshotTree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  199. if !entering {
  200. return ast.WalkContinue
  201. }
  202. n.RemoveIALAttr("heading-fold")
  203. n.RemoveIALAttr("fold")
  204. return ast.WalkContinue
  205. })
  206. for _, unlink := range unlinks {
  207. unlink.Unlink()
  208. }
  209. var appends []*ast.Node
  210. for n := snapshotTree.Root.FirstChild; nil != n; n = n.Next {
  211. appends = append(appends, n)
  212. }
  213. for _, n := range appends {
  214. renderTree.Root.AppendChild(n)
  215. }
  216. snapshotTree = renderTree
  217. }
  218. luteEngine.RenderOptions.ProtyleContenteditable = false
  219. if displayInText {
  220. util.PushMsg(Conf.Language(36), 5000)
  221. formatRenderer := render.NewFormatRenderer(snapshotTree, luteEngine.RenderOptions)
  222. content = gulu.Str.FromBytes(formatRenderer.Render())
  223. } else {
  224. content = luteEngine.Tree2BlockDOM(snapshotTree, luteEngine.RenderOptions)
  225. }
  226. } else {
  227. displayInText = true
  228. title = file.Path
  229. if mimeType := mime.TypeByExtension(filepath.Ext(file.Path)); strings.HasPrefix(mimeType, "text/") || strings.Contains(mimeType, "json") {
  230. // 如果是文本文件,直接返回文本内容
  231. // All plain text formats are supported when comparing data snapshots https://github.com/siyuan-note/siyuan/issues/12975
  232. content = gulu.Str.FromBytes(data)
  233. } else {
  234. if strings.Contains(file.Path, "assets/") { // 剔除笔记本级或者文档级资源文件路径前缀
  235. file.Path = file.Path[strings.Index(file.Path, "assets/"):]
  236. if util.IsDisplayableAsset(file.Path) {
  237. dir, f := filepath.Split(file.Path)
  238. tempRepoDiffDir := filepath.Join(util.TempDir, "repo", "diff", dir)
  239. if mkErr := os.MkdirAll(tempRepoDiffDir, 0755); nil != mkErr {
  240. logging.LogErrorf("mkdir [%s] failed: %v", tempRepoDiffDir, mkErr)
  241. } else {
  242. if wrErr := os.WriteFile(filepath.Join(tempRepoDiffDir, f), data, 0644); nil != wrErr {
  243. logging.LogErrorf("write file [%s] failed: %v", filepath.Join(tempRepoDiffDir, file.Path), wrErr)
  244. }
  245. }
  246. content = path.Join("repo", "diff", file.Path)
  247. }
  248. } else {
  249. content = file.Path
  250. }
  251. }
  252. }
  253. return
  254. }
  255. type LeftRightDiff struct {
  256. LeftIndex *DiffIndex `json:"leftIndex"`
  257. RightIndex *DiffIndex `json:"rightIndex"`
  258. AddsLeft []*DiffFile `json:"addsLeft"`
  259. UpdatesLeft []*DiffFile `json:"updatesLeft"`
  260. UpdatesRight []*DiffFile `json:"updatesRight"`
  261. RemovesRight []*DiffFile `json:"removesRight"`
  262. }
  263. type DiffFile struct {
  264. FileID string `json:"fileID"`
  265. Title string `json:"title"`
  266. Path string `json:"path"`
  267. HSize string `json:"hSize"`
  268. Updated int64 `json:"updated"`
  269. }
  270. type DiffIndex struct {
  271. ID string `json:"id"`
  272. Created int64 `json:"created"`
  273. }
  274. func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
  275. if 1 > len(Conf.Repo.Key) {
  276. err = errors.New(Conf.Language(26))
  277. return
  278. }
  279. repo, err := newRepository()
  280. if err != nil {
  281. return
  282. }
  283. diff, err := repo.DiffIndex(left, right)
  284. if err != nil {
  285. return
  286. }
  287. ret = &LeftRightDiff{
  288. LeftIndex: &DiffIndex{
  289. ID: diff.LeftIndex.ID,
  290. Created: diff.LeftIndex.Created,
  291. },
  292. RightIndex: &DiffIndex{
  293. ID: diff.RightIndex.ID,
  294. Created: diff.RightIndex.Created,
  295. },
  296. }
  297. luteEngine := NewLute()
  298. for _, removeRight := range diff.RemovesRight {
  299. title, parseErr := parseTitleInSnapshot(removeRight.ID, repo, luteEngine)
  300. if "" == title || nil != parseErr {
  301. continue
  302. }
  303. ret.AddsLeft = append(ret.AddsLeft, &DiffFile{
  304. FileID: removeRight.ID,
  305. Title: title,
  306. Path: removeRight.Path,
  307. HSize: humanize.BytesCustomCeil(uint64(removeRight.Size), 2),
  308. Updated: removeRight.Updated,
  309. })
  310. }
  311. if 1 > len(ret.AddsLeft) {
  312. ret.AddsLeft = []*DiffFile{}
  313. }
  314. for _, addLeft := range diff.AddsLeft {
  315. title, parseErr := parseTitleInSnapshot(addLeft.ID, repo, luteEngine)
  316. if "" == title || nil != parseErr {
  317. continue
  318. }
  319. ret.RemovesRight = append(ret.RemovesRight, &DiffFile{
  320. FileID: addLeft.ID,
  321. Title: title,
  322. Path: addLeft.Path,
  323. HSize: humanize.BytesCustomCeil(uint64(addLeft.Size), 2),
  324. Updated: addLeft.Updated,
  325. })
  326. }
  327. if 1 > len(ret.RemovesRight) {
  328. ret.RemovesRight = []*DiffFile{}
  329. }
  330. for _, updateLeft := range diff.UpdatesLeft {
  331. title, parseErr := parseTitleInSnapshot(updateLeft.ID, repo, luteEngine)
  332. if "" == title || nil != parseErr {
  333. continue
  334. }
  335. ret.UpdatesLeft = append(ret.UpdatesLeft, &DiffFile{
  336. FileID: updateLeft.ID,
  337. Title: title,
  338. Path: updateLeft.Path,
  339. HSize: humanize.BytesCustomCeil(uint64(updateLeft.Size), 2),
  340. Updated: updateLeft.Updated,
  341. })
  342. }
  343. if 1 > len(ret.UpdatesLeft) {
  344. ret.UpdatesLeft = []*DiffFile{}
  345. }
  346. for _, updateRight := range diff.UpdatesRight {
  347. title, parseErr := parseTitleInSnapshot(updateRight.ID, repo, luteEngine)
  348. if "" == title || nil != parseErr {
  349. continue
  350. }
  351. ret.UpdatesRight = append(ret.UpdatesRight, &DiffFile{
  352. FileID: updateRight.ID,
  353. Title: title,
  354. Path: updateRight.Path,
  355. HSize: humanize.BytesCustomCeil(uint64(updateRight.Size), 2),
  356. Updated: updateRight.Updated,
  357. })
  358. }
  359. if 1 > len(ret.UpdatesRight) {
  360. ret.UpdatesRight = []*DiffFile{}
  361. }
  362. return
  363. }
  364. func parseTitleInSnapshot(fileID string, repo *dejavu.Repo, luteEngine *lute.Lute) (title string, err error) {
  365. file, err := repo.GetFile(fileID)
  366. if err != nil {
  367. logging.LogErrorf("get file [%s] failed: %s", fileID, err)
  368. return
  369. }
  370. title = path.Base(file.Path)
  371. if strings.HasSuffix(file.Path, ".sy") {
  372. var data []byte
  373. data, err = repo.OpenFile(file)
  374. if err != nil {
  375. logging.LogErrorf("open file [%s] failed: %s", fileID, err)
  376. return
  377. }
  378. var tree *parse.Tree
  379. tree, err = filesys.ParseJSONWithoutFix(data, luteEngine.ParseOptions)
  380. if err != nil {
  381. logging.LogErrorf("parse file [%s] failed: %s", fileID, err)
  382. return
  383. }
  384. title = tree.Root.IALAttr("title")
  385. }
  386. return
  387. }
  388. func parseTreeInSnapshot(data []byte, luteEngine *lute.Lute) (isLargeDoc bool, tree *parse.Tree, err error) {
  389. isLargeDoc = 1024*1024*1 <= len(data)
  390. tree, err = filesys.ParseJSONWithoutFix(data, luteEngine.ParseOptions)
  391. if err != nil {
  392. return
  393. }
  394. return
  395. }
  396. type Snapshot struct {
  397. *dejavu.Log
  398. TypesCount []*TypeCount `json:"typesCount"`
  399. }
  400. type TypeCount struct {
  401. Type string `json:"type"`
  402. Count int `json:"count"`
  403. }
  404. func GetRepoSnapshots(page int) (ret []*Snapshot, pageCount, totalCount int, err error) {
  405. ret = []*Snapshot{}
  406. if 1 > len(Conf.Repo.Key) {
  407. err = errors.New(Conf.Language(26))
  408. return
  409. }
  410. repo, err := newRepository()
  411. if err != nil {
  412. return
  413. }
  414. logs, pageCount, totalCount, err := repo.GetIndexLogs(page, 32)
  415. if err != nil {
  416. if dejavu.ErrNotFoundIndex == err {
  417. logs = []*dejavu.Log{}
  418. err = nil
  419. return
  420. }
  421. logging.LogErrorf("get data repo index logs failed: %s", err)
  422. return
  423. }
  424. ret = buildSnapshots(logs)
  425. if 1 > len(ret) {
  426. ret = []*Snapshot{}
  427. }
  428. return
  429. }
  430. func buildSnapshots(logs []*dejavu.Log) (ret []*Snapshot) {
  431. for _, l := range logs {
  432. typesCount := statTypesByPath(l.Files)
  433. l.Files = nil // 置空,否则返回前端数据量太大
  434. ret = append(ret, &Snapshot{
  435. Log: l,
  436. TypesCount: typesCount,
  437. })
  438. }
  439. return
  440. }
  441. func statTypesByPath(files []*entity.File) (ret []*TypeCount) {
  442. for _, f := range files {
  443. ext := util.Ext(f.Path)
  444. if "" == ext {
  445. ext = "NoExt"
  446. }
  447. found := false
  448. for _, tc := range ret {
  449. if tc.Type == ext {
  450. tc.Count++
  451. found = true
  452. break
  453. }
  454. }
  455. if !found {
  456. ret = append(ret, &TypeCount{Type: ext, Count: 1})
  457. }
  458. }
  459. sort.Slice(ret, func(i, j int) bool { return ret[i].Count > ret[j].Count })
  460. if 10 < len(ret) {
  461. otherCount := 0
  462. for _, tc := range ret[10:] {
  463. tc.Count += otherCount
  464. }
  465. other := &TypeCount{
  466. Type: "Other",
  467. Count: otherCount,
  468. }
  469. ret = append(ret[:10], other)
  470. }
  471. return
  472. }
  473. func ImportRepoKey(base64Key string) (retKey string, err error) {
  474. util.PushMsg(Conf.Language(136), 3000)
  475. retKey = strings.TrimSpace(base64Key)
  476. retKey = gulu.Str.RemoveInvisible(retKey)
  477. if 1 > len(retKey) {
  478. err = errors.New(Conf.Language(142))
  479. return
  480. }
  481. key, err := base64.StdEncoding.DecodeString(retKey)
  482. if err != nil {
  483. logging.LogErrorf("import data repo key failed: %s", err)
  484. return "", errors.New(Conf.Language(157))
  485. }
  486. if 32 != len(key) {
  487. return "", errors.New(Conf.Language(157))
  488. }
  489. Conf.Repo.Key = key
  490. Conf.Save()
  491. logging.LogInfof("imported repo key [%x]", sha1.Sum(Conf.Repo.Key))
  492. if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil {
  493. return
  494. }
  495. if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil {
  496. return
  497. }
  498. initDataRepo()
  499. return
  500. }
  501. func ResetRepo() (err error) {
  502. logging.LogInfof("resetting data repo...")
  503. msgId := util.PushMsg(Conf.Language(144), 1000*60)
  504. repo, err := newRepository()
  505. if err != nil {
  506. return
  507. }
  508. if err = repo.Reset(); err != nil {
  509. logging.LogErrorf("reset data repo failed: %s", err)
  510. return
  511. }
  512. logging.LogInfof("reset data repo completed")
  513. Conf.Repo.Key = nil
  514. Conf.Sync.Enabled = false
  515. Conf.Save()
  516. util.PushUpdateMsg(msgId, Conf.Language(145), 3000)
  517. task.AppendAsyncTaskWithDelay(task.ReloadUI, 2*time.Second, util.ReloadUI)
  518. return
  519. }
  520. func PurgeCloud() (err error) {
  521. msg := Conf.Language(223)
  522. util.PushEndlessProgress(msg)
  523. defer util.PushClearProgress()
  524. repo, err := newRepository()
  525. if err != nil {
  526. return
  527. }
  528. stat, err := repo.PurgeCloud()
  529. if err != nil {
  530. return
  531. }
  532. deletedIndexes := stat.Indexes
  533. deletedObjects := stat.Objects
  534. deletedSize := humanize.BytesCustomCeil(uint64(stat.Size), 2)
  535. msg = fmt.Sprintf(Conf.Language(232), deletedIndexes, deletedObjects, deletedSize)
  536. util.PushMsg(msg, 7000)
  537. return
  538. }
  539. func PurgeRepo() (err error) {
  540. msg := Conf.Language(202)
  541. util.PushEndlessProgress(msg)
  542. defer util.PushClearProgress()
  543. repo, err := newRepository()
  544. if err != nil {
  545. return
  546. }
  547. stat, err := repo.Purge()
  548. if err != nil {
  549. return
  550. }
  551. deletedIndexes := stat.Indexes
  552. deletedObjects := stat.Objects
  553. deletedSize := humanize.BytesCustomCeil(uint64(stat.Size), 2)
  554. msg = fmt.Sprintf(Conf.Language(203), deletedIndexes, deletedObjects, deletedSize)
  555. util.PushMsg(msg, 7000)
  556. return
  557. }
  558. func InitRepoKeyFromPassphrase(passphrase string) (err error) {
  559. passphrase = gulu.Str.RemoveInvisible(passphrase)
  560. passphrase = strings.TrimSpace(passphrase)
  561. if "" == passphrase {
  562. return errors.New(Conf.Language(142))
  563. }
  564. util.PushMsg(Conf.Language(136), 3000)
  565. if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil {
  566. return
  567. }
  568. if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil {
  569. return
  570. }
  571. var key []byte
  572. base64Data, base64Err := base64.StdEncoding.DecodeString(passphrase)
  573. if nil == base64Err && 32 == len(base64Data) {
  574. // 改进数据仓库 `通过密码生成密钥` https://github.com/siyuan-note/siyuan/issues/6782
  575. logging.LogInfof("passphrase is base64 encoded, use it as key directly")
  576. key = base64Data
  577. } else {
  578. salt := fmt.Sprintf("%x", sha256.Sum256([]byte(passphrase)))[:16]
  579. key, err = encryption.KDF(passphrase, salt)
  580. if err != nil {
  581. logging.LogErrorf("init data repo key failed: %s", err)
  582. return
  583. }
  584. }
  585. Conf.Repo.Key = key
  586. Conf.Save()
  587. logging.LogInfof("inited repo key [%x]", sha1.Sum(Conf.Repo.Key))
  588. initDataRepo()
  589. return
  590. }
  591. func InitRepoKey() (err error) {
  592. util.PushMsg(Conf.Language(136), 3000)
  593. if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil {
  594. return
  595. }
  596. if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil {
  597. return
  598. }
  599. randomBytes := make([]byte, 16)
  600. _, err = rand.Read(randomBytes)
  601. if err != nil {
  602. return
  603. }
  604. password := string(randomBytes)
  605. randomBytes = make([]byte, 16)
  606. _, err = rand.Read(randomBytes)
  607. if err != nil {
  608. logging.LogErrorf("init data repo key failed: %s", err)
  609. return
  610. }
  611. salt := string(randomBytes)
  612. key, err := encryption.KDF(password, salt)
  613. if err != nil {
  614. logging.LogErrorf("init data repo key failed: %s", err)
  615. return
  616. }
  617. Conf.Repo.Key = key
  618. Conf.Save()
  619. logging.LogInfof("inited repo key [%x]", sha1.Sum(Conf.Repo.Key))
  620. initDataRepo()
  621. return
  622. }
  623. func initDataRepo() {
  624. time.Sleep(1 * time.Second)
  625. util.PushMsg(Conf.Language(138), 3000)
  626. time.Sleep(1 * time.Second)
  627. if initErr := IndexRepo("[Init] Init local data repo"); nil != initErr {
  628. util.PushErrMsg(fmt.Sprintf(Conf.Language(140), initErr), 0)
  629. }
  630. }
  631. func CheckoutRepo(id string) {
  632. task.AppendTask(task.RepoCheckout, checkoutRepo, id)
  633. }
  634. func checkoutRepo(id string) {
  635. var err error
  636. if 1 > len(Conf.Repo.Key) {
  637. util.PushErrMsg(Conf.Language(26), 7000)
  638. return
  639. }
  640. repo, err := newRepository()
  641. if err != nil {
  642. logging.LogErrorf("new repository failed: %s", err)
  643. util.PushErrMsg(Conf.Language(141), 7000)
  644. return
  645. }
  646. util.PushEndlessProgress(Conf.Language(63))
  647. FlushTxQueue()
  648. CloseWatchAssets()
  649. defer WatchAssets()
  650. CloseWatchEmojis()
  651. defer WatchEmojis()
  652. // 恢复快照时自动暂停同步,避免刚刚恢复后的数据又被同步覆盖
  653. syncEnabled := Conf.Sync.Enabled
  654. Conf.Sync.Enabled = false
  655. Conf.Save()
  656. // 回滚快照时默认为当前数据创建一个快照
  657. // When rolling back a snapshot, a snapshot is created for the current data by default https://github.com/siyuan-note/siyuan/issues/12470
  658. FlushTxQueue()
  659. _, err = repo.Index("Backup before checkout", false, map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})
  660. if err != nil {
  661. logging.LogErrorf("index repository failed: %s", err)
  662. util.PushClearProgress()
  663. util.PushErrMsg(fmt.Sprintf(Conf.Language(140), err), 0)
  664. return
  665. }
  666. _, _, err = repo.Checkout(id, map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})
  667. if err != nil {
  668. logging.LogErrorf("checkout repository failed: %s", err)
  669. util.PushClearProgress()
  670. util.PushErrMsg(Conf.Language(141), 7000)
  671. return
  672. }
  673. task.AppendTask(task.DatabaseIndexFull, fullReindex)
  674. task.AppendTask(task.DatabaseIndexRef, IndexRefs)
  675. go func() {
  676. sql.FlushQueue()
  677. ResetVirtualBlockRefCache()
  678. }()
  679. task.AppendTask(task.ReloadUI, util.ReloadUIResetScroll)
  680. if syncEnabled {
  681. task.AppendAsyncTaskWithDelay(task.PushMsg, 7*time.Second, util.PushMsg, Conf.Language(134), 0)
  682. }
  683. return
  684. }
  685. func DownloadCloudSnapshot(tag, id string) (err error) {
  686. if 1 > len(Conf.Repo.Key) {
  687. err = errors.New(Conf.Language(26))
  688. return
  689. }
  690. repo, err := newRepository()
  691. if err != nil {
  692. return
  693. }
  694. switch Conf.Sync.Provider {
  695. case conf.ProviderSiYuan:
  696. if !IsSubscriber() {
  697. util.PushErrMsg(Conf.Language(29), 5000)
  698. return
  699. }
  700. case conf.ProviderWebDAV, conf.ProviderS3:
  701. if !IsPaidUser() {
  702. util.PushErrMsg(Conf.Language(214), 5000)
  703. return
  704. }
  705. }
  706. defer util.PushClearProgress()
  707. var downloadFileCount, downloadChunkCount int
  708. var downloadBytes int64
  709. if "" == tag {
  710. downloadFileCount, downloadChunkCount, downloadBytes, err = repo.DownloadIndex(id, map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})
  711. } else {
  712. downloadFileCount, downloadChunkCount, downloadBytes, err = repo.DownloadTagIndex(tag, id, map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})
  713. }
  714. if err != nil {
  715. return
  716. }
  717. msg := fmt.Sprintf(Conf.Language(153), downloadFileCount, downloadChunkCount, humanize.BytesCustomCeil(uint64(downloadBytes), 2))
  718. util.PushMsg(msg, 5000)
  719. util.PushStatusBar(msg)
  720. return
  721. }
  722. func UploadCloudSnapshot(tag, id string) (err error) {
  723. if 1 > len(Conf.Repo.Key) {
  724. err = errors.New(Conf.Language(26))
  725. return
  726. }
  727. repo, err := newRepository()
  728. if err != nil {
  729. return
  730. }
  731. switch Conf.Sync.Provider {
  732. case conf.ProviderSiYuan:
  733. if !IsSubscriber() {
  734. util.PushErrMsg(Conf.Language(29), 5000)
  735. return
  736. }
  737. case conf.ProviderWebDAV, conf.ProviderS3:
  738. if !IsPaidUser() {
  739. util.PushErrMsg(Conf.Language(214), 5000)
  740. return
  741. }
  742. }
  743. util.PushEndlessProgress(Conf.Language(116))
  744. defer util.PushClearProgress()
  745. uploadFileCount, uploadChunkCount, uploadBytes, err := repo.UploadTagIndex(tag, id, map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})
  746. if err != nil {
  747. if errors.Is(err, dejavu.ErrCloudBackupCountExceeded) {
  748. err = fmt.Errorf(Conf.Language(84), Conf.Language(154))
  749. return
  750. }
  751. err = errors.New(fmt.Sprintf(Conf.Language(84), formatRepoErrorMsg(err)))
  752. return
  753. }
  754. msg := fmt.Sprintf(Conf.Language(152), uploadFileCount, uploadChunkCount, humanize.BytesCustomCeil(uint64(uploadBytes), 2))
  755. util.PushMsg(msg, 5000)
  756. util.PushStatusBar(msg)
  757. return
  758. }
  759. func RemoveCloudRepoTag(tag string) (err error) {
  760. if 1 > len(Conf.Repo.Key) {
  761. err = errors.New(Conf.Language(26))
  762. return
  763. }
  764. if "" == tag {
  765. err = errors.New("tag is empty")
  766. return
  767. }
  768. repo, err := newRepository()
  769. if err != nil {
  770. return
  771. }
  772. switch Conf.Sync.Provider {
  773. case conf.ProviderSiYuan:
  774. if !IsSubscriber() {
  775. util.PushErrMsg(Conf.Language(29), 5000)
  776. return
  777. }
  778. case conf.ProviderWebDAV, conf.ProviderS3:
  779. if !IsPaidUser() {
  780. util.PushErrMsg(Conf.Language(214), 5000)
  781. return
  782. }
  783. }
  784. err = repo.RemoveCloudRepoTag(tag)
  785. if err != nil {
  786. return
  787. }
  788. return
  789. }
  790. func GetCloudRepoTagSnapshots() (ret []*dejavu.Log, err error) {
  791. ret = []*dejavu.Log{}
  792. if 1 > len(Conf.Repo.Key) {
  793. err = errors.New(Conf.Language(26))
  794. return
  795. }
  796. repo, err := newRepository()
  797. if err != nil {
  798. return
  799. }
  800. switch Conf.Sync.Provider {
  801. case conf.ProviderSiYuan:
  802. if !IsSubscriber() {
  803. util.PushErrMsg(Conf.Language(29), 5000)
  804. return
  805. }
  806. case conf.ProviderWebDAV, conf.ProviderS3:
  807. if !IsPaidUser() {
  808. util.PushErrMsg(Conf.Language(214), 5000)
  809. return
  810. }
  811. }
  812. logs, err := repo.GetCloudRepoTagLogs(map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar})
  813. if err != nil {
  814. return
  815. }
  816. ret = logs
  817. if 1 > len(ret) {
  818. ret = []*dejavu.Log{}
  819. }
  820. return
  821. }
  822. func GetCloudRepoSnapshots(page int) (ret []*dejavu.Log, pageCount, totalCount int, err error) {
  823. ret = []*dejavu.Log{}
  824. if 1 > len(Conf.Repo.Key) {
  825. err = errors.New(Conf.Language(26))
  826. return
  827. }
  828. repo, err := newRepository()
  829. if err != nil {
  830. return
  831. }
  832. switch Conf.Sync.Provider {
  833. case conf.ProviderSiYuan:
  834. if !IsSubscriber() {
  835. util.PushErrMsg(Conf.Language(29), 5000)
  836. return
  837. }
  838. case conf.ProviderWebDAV, conf.ProviderS3:
  839. if !IsPaidUser() {
  840. util.PushErrMsg(Conf.Language(214), 5000)
  841. return
  842. }
  843. }
  844. if 1 > page {
  845. page = 1
  846. }
  847. logs, pageCount, totalCount, err := repo.GetCloudRepoLogs(page)
  848. if err != nil {
  849. return
  850. }
  851. ret = logs
  852. if 1 > len(ret) {
  853. ret = []*dejavu.Log{}
  854. }
  855. return
  856. }
  857. func GetTagSnapshots() (ret []*Snapshot, err error) {
  858. ret = []*Snapshot{}
  859. if 1 > len(Conf.Repo.Key) {
  860. err = errors.New(Conf.Language(26))
  861. return
  862. }
  863. repo, err := newRepository()
  864. if err != nil {
  865. return
  866. }
  867. logs, err := repo.GetTagLogs()
  868. if err != nil {
  869. return
  870. }
  871. ret = buildSnapshots(logs)
  872. if 1 > len(ret) {
  873. ret = []*Snapshot{}
  874. }
  875. return
  876. }
  877. func RemoveTagSnapshot(tag string) (err error) {
  878. if 1 > len(Conf.Repo.Key) {
  879. err = errors.New(Conf.Language(26))
  880. return
  881. }
  882. repo, err := newRepository()
  883. if err != nil {
  884. return
  885. }
  886. err = repo.RemoveTag(tag)
  887. return
  888. }
  889. func TagSnapshot(id, name string) (err error) {
  890. if 1 > len(Conf.Repo.Key) {
  891. err = errors.New(Conf.Language(26))
  892. return
  893. }
  894. name = strings.TrimSpace(name)
  895. name = util.RemoveInvalid(name)
  896. if "" == name {
  897. err = errors.New(Conf.Language(142))
  898. return
  899. }
  900. if !gulu.File.IsValidFilename(name) {
  901. err = errors.New(Conf.Language(151))
  902. return
  903. }
  904. repo, err := newRepository()
  905. if err != nil {
  906. return
  907. }
  908. index, err := repo.GetIndex(id)
  909. if err != nil {
  910. return
  911. }
  912. if err = repo.AddTag(index.ID, name); err != nil {
  913. msg := fmt.Sprintf("Add tag to data snapshot [%s] failed: %s", index.ID, err)
  914. util.PushStatusBar(msg)
  915. return
  916. }
  917. return
  918. }
  919. func IndexRepo(memo string) (err error) {
  920. if 1 > len(Conf.Repo.Key) {
  921. err = errors.New(Conf.Language(26))
  922. return
  923. }
  924. memo = strings.TrimSpace(memo)
  925. memo = gulu.Str.RemoveInvisible(memo)
  926. if "" == memo {
  927. err = errors.New(Conf.Language(142))
  928. return
  929. }
  930. repo, err := newRepository()
  931. if err != nil {
  932. return
  933. }
  934. util.PushEndlessProgress(Conf.Language(143))
  935. start := time.Now()
  936. latest, _ := repo.Latest()
  937. FlushTxQueue()
  938. index, err := repo.Index(memo, true, map[string]interface{}{
  939. eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress,
  940. })
  941. if err != nil {
  942. util.PushStatusBar("Index data repo failed: " + html.EscapeString(err.Error()))
  943. return
  944. }
  945. elapsed := time.Since(start)
  946. if nil == latest || latest.ID != index.ID {
  947. msg := fmt.Sprintf(Conf.Language(147), elapsed.Seconds())
  948. util.PushStatusBar(msg)
  949. util.PushMsg(msg, 5000)
  950. } else {
  951. msg := fmt.Sprintf(Conf.Language(148), elapsed.Seconds())
  952. util.PushStatusBar(msg)
  953. util.PushMsg(msg, 5000)
  954. }
  955. util.PushClearProgress()
  956. return
  957. }
  958. var syncingFiles = sync.Map{}
  959. var syncingStorages = atomic.Bool{}
  960. func waitForSyncingStorages() {
  961. for isSyncingStorages() {
  962. time.Sleep(time.Second)
  963. }
  964. }
  965. func isSyncingStorages() bool {
  966. return syncingStorages.Load() || isBootSyncing.Load()
  967. }
  968. func IsSyncingFile(rootID string) (ret bool) {
  969. _, ret = syncingFiles.Load(rootID)
  970. return
  971. }
  972. func syncRepoDownload() (err error) {
  973. if 1 > len(Conf.Repo.Key) {
  974. planSyncAfter(fixSyncInterval)
  975. msg := Conf.Language(26)
  976. util.PushStatusBar(msg)
  977. util.PushErrMsg(msg, 0)
  978. err = errors.New(msg)
  979. return
  980. }
  981. repo, err := newRepository()
  982. if err != nil {
  983. planSyncAfter(fixSyncInterval)
  984. msg := fmt.Sprintf("sync repo failed: %s", err)
  985. logging.LogErrorf(msg)
  986. util.PushStatusBar(msg)
  987. util.PushErrMsg(msg, 0)
  988. return
  989. }
  990. logging.LogInfof("downloading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "d", true)
  991. start := time.Now()
  992. _, _, err = indexRepoBeforeCloudSync(repo)
  993. if err != nil {
  994. planSyncAfter(fixSyncInterval)
  995. logging.LogErrorf("sync data repo download failed: %s", err)
  996. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))
  997. Conf.Sync.Stat = msg
  998. Conf.Save()
  999. util.PushStatusBar(msg)
  1000. util.PushErrMsg(msg, 0)
  1001. return
  1002. }
  1003. syncContext := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}
  1004. mergeResult, trafficStat, err := repo.SyncDownload(syncContext)
  1005. elapsed := time.Since(start)
  1006. if err != nil {
  1007. planSyncAfter(fixSyncInterval)
  1008. logging.LogErrorf("sync data repo download failed: %s", err)
  1009. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))
  1010. if errors.Is(err, dejavu.ErrCloudStorageSizeExceeded) {
  1011. u := Conf.GetUser()
  1012. msg = fmt.Sprintf(Conf.Language(43), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))
  1013. if 2 == u.UserSiYuanSubscriptionPlan {
  1014. msg = fmt.Sprintf(Conf.Language(68), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))
  1015. }
  1016. }
  1017. Conf.Sync.Stat = msg
  1018. Conf.Save()
  1019. util.PushStatusBar(msg)
  1020. util.PushErrMsg(msg, 0)
  1021. return
  1022. }
  1023. util.PushStatusBar(fmt.Sprintf(Conf.Language(149), elapsed.Seconds()))
  1024. Conf.Sync.Synced = util.CurrentTimeMillis()
  1025. msg := fmt.Sprintf(Conf.Language(150), trafficStat.UploadFileCount, trafficStat.DownloadFileCount, trafficStat.UploadChunkCount, trafficStat.DownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.UploadBytes), 2), humanize.BytesCustomFloor(uint64(trafficStat.DownloadBytes), 2))
  1026. Conf.Sync.Stat = msg
  1027. Conf.Save()
  1028. autoSyncErrCount = 0
  1029. BootSyncSucc = 0
  1030. processSyncMergeResult(false, true, mergeResult, trafficStat, "d", elapsed)
  1031. return
  1032. }
  1033. func syncRepoUpload() (err error) {
  1034. if 1 > len(Conf.Repo.Key) {
  1035. planSyncAfter(fixSyncInterval)
  1036. msg := Conf.Language(26)
  1037. util.PushStatusBar(msg)
  1038. util.PushErrMsg(msg, 0)
  1039. err = errors.New(msg)
  1040. return
  1041. }
  1042. repo, err := newRepository()
  1043. if err != nil {
  1044. planSyncAfter(fixSyncInterval)
  1045. msg := fmt.Sprintf("sync repo failed: %s", err)
  1046. logging.LogErrorf(msg)
  1047. util.PushStatusBar(msg)
  1048. util.PushErrMsg(msg, 0)
  1049. return
  1050. }
  1051. logging.LogInfof("uploading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "u", true)
  1052. start := time.Now()
  1053. _, _, err = indexRepoBeforeCloudSync(repo)
  1054. if err != nil {
  1055. planSyncAfter(fixSyncInterval)
  1056. logging.LogErrorf("sync data repo upload failed: %s", err)
  1057. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))
  1058. Conf.Sync.Stat = msg
  1059. Conf.Save()
  1060. util.PushStatusBar(msg)
  1061. util.PushErrMsg(msg, 0)
  1062. return
  1063. }
  1064. syncContext := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}
  1065. trafficStat, err := repo.SyncUpload(syncContext)
  1066. elapsed := time.Since(start)
  1067. if err != nil {
  1068. planSyncAfter(fixSyncInterval)
  1069. logging.LogErrorf("sync data repo upload failed: %s", err)
  1070. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))
  1071. if errors.Is(err, dejavu.ErrCloudStorageSizeExceeded) {
  1072. u := Conf.GetUser()
  1073. msg = fmt.Sprintf(Conf.Language(43), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))
  1074. if 2 == u.UserSiYuanSubscriptionPlan {
  1075. msg = fmt.Sprintf(Conf.Language(68), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))
  1076. }
  1077. }
  1078. Conf.Sync.Stat = msg
  1079. Conf.Save()
  1080. util.PushStatusBar(msg)
  1081. util.PushErrMsg(msg, 0)
  1082. return
  1083. }
  1084. util.PushStatusBar(fmt.Sprintf(Conf.Language(149), elapsed.Seconds()))
  1085. Conf.Sync.Synced = util.CurrentTimeMillis()
  1086. msg := fmt.Sprintf(Conf.Language(150), trafficStat.UploadFileCount, trafficStat.DownloadFileCount, trafficStat.UploadChunkCount, trafficStat.DownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.UploadBytes), 2), humanize.BytesCustomCeil(uint64(trafficStat.DownloadBytes), 2))
  1087. Conf.Sync.Stat = msg
  1088. Conf.Save()
  1089. autoSyncErrCount = 0
  1090. BootSyncSucc = 0
  1091. processSyncMergeResult(false, true, &dejavu.MergeResult{}, trafficStat, "u", elapsed)
  1092. return
  1093. }
  1094. var isBootSyncing = atomic.Bool{}
  1095. func bootSyncRepo() (err error) {
  1096. if 1 > len(Conf.Repo.Key) {
  1097. autoSyncErrCount++
  1098. planSyncAfter(fixSyncInterval)
  1099. msg := Conf.Language(26)
  1100. util.PushStatusBar(msg)
  1101. util.PushErrMsg(msg, 0)
  1102. err = errors.New(msg)
  1103. return
  1104. }
  1105. repo, err := newRepository()
  1106. if err != nil {
  1107. autoSyncErrCount++
  1108. planSyncAfter(fixSyncInterval)
  1109. msg := fmt.Sprintf("sync repo failed: %s", html.EscapeString(err.Error()))
  1110. logging.LogErrorf(msg)
  1111. util.PushStatusBar(msg)
  1112. util.PushErrMsg(msg, 0)
  1113. return
  1114. }
  1115. isBootSyncing.Store(true)
  1116. start := time.Now()
  1117. waitGroup := sync.WaitGroup{}
  1118. var errs []error
  1119. waitGroup.Add(1)
  1120. go func() {
  1121. defer waitGroup.Done()
  1122. _, _, indexErr := indexRepoBeforeCloudSync(repo)
  1123. if indexErr != nil {
  1124. errs = append(errs, indexErr)
  1125. autoSyncErrCount++
  1126. planSyncAfter(fixSyncInterval)
  1127. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(indexErr))
  1128. Conf.Sync.Stat = msg
  1129. Conf.Save()
  1130. util.PushStatusBar(msg)
  1131. util.PushErrMsg(msg, 0)
  1132. BootSyncSucc = 1
  1133. isBootSyncing.Store(false)
  1134. return
  1135. }
  1136. }()
  1137. var fetchedFiles []*entity.File
  1138. waitGroup.Add(1)
  1139. go func() {
  1140. defer waitGroup.Done()
  1141. syncContext := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}
  1142. cloudLatest, getErr := repo.GetCloudLatest(syncContext)
  1143. if nil != getErr {
  1144. errs = append(errs, getErr)
  1145. if !errors.Is(getErr, cloud.ErrCloudObjectNotFound) {
  1146. logging.LogErrorf("download cloud latest failed: %s", getErr)
  1147. return
  1148. }
  1149. }
  1150. fetchedFiles, getErr = repo.GetSyncCloudFiles(cloudLatest, syncContext)
  1151. if errors.Is(getErr, dejavu.ErrRepoFatal) {
  1152. errs = append(errs, getErr)
  1153. autoSyncErrCount++
  1154. planSyncAfter(fixSyncInterval)
  1155. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(getErr))
  1156. Conf.Sync.Stat = msg
  1157. Conf.Save()
  1158. util.PushStatusBar(msg)
  1159. util.PushErrMsg(msg, 0)
  1160. BootSyncSucc = 1
  1161. isBootSyncing.Store(false)
  1162. return
  1163. }
  1164. }()
  1165. waitGroup.Wait()
  1166. if 0 < len(errs) {
  1167. err = errs[0]
  1168. return
  1169. }
  1170. syncingFiles = sync.Map{}
  1171. syncingStorages.Store(false)
  1172. for _, fetchedFile := range fetchedFiles {
  1173. name := path.Base(fetchedFile.Path)
  1174. if strings.HasSuffix(name, ".sy") {
  1175. id := name[:len(name)-3]
  1176. syncingFiles.Store(id, true)
  1177. continue
  1178. }
  1179. if strings.HasPrefix(fetchedFile.Path, "/storage/") {
  1180. syncingStorages.Store(true)
  1181. }
  1182. }
  1183. elapsed := time.Since(start)
  1184. logging.LogInfof("boot get sync cloud files elapsed [%.2fs]", elapsed.Seconds())
  1185. if err != nil {
  1186. autoSyncErrCount++
  1187. planSyncAfter(fixSyncInterval)
  1188. logging.LogErrorf("sync data repo failed: %s", err)
  1189. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))
  1190. if errors.Is(err, dejavu.ErrCloudStorageSizeExceeded) {
  1191. u := Conf.GetUser()
  1192. msg = fmt.Sprintf(Conf.Language(43), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))
  1193. if 2 == u.UserSiYuanSubscriptionPlan {
  1194. msg = fmt.Sprintf(Conf.Language(68), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))
  1195. }
  1196. }
  1197. Conf.Sync.Stat = msg
  1198. Conf.Save()
  1199. util.PushStatusBar(msg)
  1200. util.PushErrMsg(msg, 0)
  1201. BootSyncSucc = 1
  1202. isBootSyncing.Store(false)
  1203. return
  1204. }
  1205. if 0 < len(fetchedFiles) {
  1206. go func() {
  1207. _, syncErr := syncRepo(false, false)
  1208. isBootSyncing.Store(false)
  1209. if err != nil {
  1210. logging.LogErrorf("boot background sync repo failed: %s", syncErr)
  1211. return
  1212. }
  1213. }()
  1214. } else {
  1215. isBootSyncing.Store(false)
  1216. }
  1217. return
  1218. }
  1219. func syncRepo(exit, byHand bool) (dataChanged bool, err error) {
  1220. if 1 > len(Conf.Repo.Key) {
  1221. autoSyncErrCount++
  1222. planSyncAfter(fixSyncInterval)
  1223. msg := Conf.Language(26)
  1224. util.PushStatusBar(msg)
  1225. util.PushErrMsg(msg, 0)
  1226. err = errors.New(msg)
  1227. return
  1228. }
  1229. repo, err := newRepository()
  1230. if err != nil {
  1231. autoSyncErrCount++
  1232. planSyncAfter(fixSyncInterval)
  1233. msg := fmt.Sprintf("sync repo failed: %s", err)
  1234. logging.LogErrorf(msg)
  1235. util.PushStatusBar(msg)
  1236. util.PushErrMsg(msg, 0)
  1237. return
  1238. }
  1239. logging.LogInfof("syncing data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "a", byHand)
  1240. start := time.Now()
  1241. beforeIndex, afterIndex, err := indexRepoBeforeCloudSync(repo)
  1242. if err != nil {
  1243. autoSyncErrCount++
  1244. planSyncAfter(fixSyncInterval)
  1245. logging.LogErrorf("sync data repo failed: %s", err)
  1246. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))
  1247. Conf.Sync.Stat = msg
  1248. Conf.Save()
  1249. util.PushStatusBar(msg)
  1250. if 1 > autoSyncErrCount || byHand {
  1251. util.PushErrMsg(msg, 0)
  1252. }
  1253. if exit {
  1254. ExitSyncSucc = 1
  1255. }
  1256. return
  1257. }
  1258. syncContext := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}
  1259. mergeResult, trafficStat, err := repo.Sync(syncContext)
  1260. elapsed := time.Since(start)
  1261. if err != nil {
  1262. autoSyncErrCount++
  1263. planSyncAfter(fixSyncInterval)
  1264. logging.LogErrorf("sync data repo failed: %s", err)
  1265. msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))
  1266. if errors.Is(err, dejavu.ErrCloudStorageSizeExceeded) {
  1267. u := Conf.GetUser()
  1268. msg = fmt.Sprintf(Conf.Language(43), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))
  1269. if 2 == u.UserSiYuanSubscriptionPlan {
  1270. msg = fmt.Sprintf(Conf.Language(68), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))
  1271. }
  1272. }
  1273. Conf.Sync.Stat = msg
  1274. Conf.Save()
  1275. util.PushStatusBar(msg)
  1276. if 1 > autoSyncErrCount || byHand {
  1277. util.PushErrMsg(msg, 0)
  1278. }
  1279. if exit {
  1280. ExitSyncSucc = 1
  1281. }
  1282. return
  1283. }
  1284. dataChanged = nil == beforeIndex || beforeIndex.ID != afterIndex.ID || mergeResult.DataChanged()
  1285. util.PushStatusBar(fmt.Sprintf(Conf.Language(149), elapsed.Seconds()))
  1286. Conf.Sync.Synced = util.CurrentTimeMillis()
  1287. msg := fmt.Sprintf(Conf.Language(150), trafficStat.UploadFileCount, trafficStat.DownloadFileCount, trafficStat.UploadChunkCount, trafficStat.DownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.UploadBytes), 2), humanize.BytesCustomCeil(uint64(trafficStat.DownloadBytes), 2))
  1288. Conf.Sync.Stat = msg
  1289. Conf.Save()
  1290. autoSyncErrCount = 0
  1291. processSyncMergeResult(exit, byHand, mergeResult, trafficStat, "a", elapsed)
  1292. if !exit {
  1293. go func() {
  1294. // 首次数据同步执行完成后再执行索引订正 Index fixing should not be performed before data synchronization https://github.com/siyuan-note/siyuan/issues/10761
  1295. checkIndex()
  1296. // 索引订正结束后执行数据仓库清理 Automatic purge for local data repo https://github.com/siyuan-note/siyuan/issues/13091
  1297. autoPurgeRepo(false)
  1298. }()
  1299. }
  1300. return
  1301. }
  1302. func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult, trafficStat *dejavu.TrafficStat, mode string, elapsed time.Duration) {
  1303. logging.LogInfof("synced data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t, ufc=%d, dfc=%d, ucc=%d, dcc=%d, ub=%s, db=%s] in [%.2fs], merge result [conflicts=%d, upserts=%d, removes=%d]\n\n",
  1304. Conf.System.ID, KernelID, Conf.Sync.Provider, mode, byHand,
  1305. trafficStat.UploadFileCount, trafficStat.DownloadFileCount, trafficStat.UploadChunkCount, trafficStat.DownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.UploadBytes), 2), humanize.BytesCustomCeil(uint64(trafficStat.DownloadBytes), 2),
  1306. elapsed.Seconds(),
  1307. len(mergeResult.Conflicts), len(mergeResult.Upserts), len(mergeResult.Removes))
  1308. //logSyncMergeResult(mergeResult)
  1309. var needReloadFiletree bool
  1310. if 0 < len(mergeResult.Conflicts) {
  1311. luteEngine := util.NewLute()
  1312. if Conf.Sync.GenerateConflictDoc {
  1313. // 云端同步发生冲突时生成副本 https://github.com/siyuan-note/siyuan/issues/5687
  1314. for _, file := range mergeResult.Conflicts {
  1315. if !strings.HasSuffix(file.Path, ".sy") {
  1316. continue
  1317. }
  1318. parts := strings.Split(file.Path[1:], "/")
  1319. if 2 > len(parts) {
  1320. continue
  1321. }
  1322. boxID := parts[0]
  1323. absPath := filepath.Join(util.TempDir, "repo", "sync", "conflicts", mergeResult.Time.Format("2006-01-02-150405"), file.Path)
  1324. tree, loadTreeErr := loadTree(absPath, luteEngine)
  1325. if nil != loadTreeErr {
  1326. logging.LogErrorf("load conflicted file [%s] failed: %s", absPath, loadTreeErr)
  1327. continue
  1328. }
  1329. tree.Box = boxID
  1330. tree.Path = strings.TrimPrefix(file.Path, "/"+boxID)
  1331. resetTree(tree, "Conflicted", true)
  1332. createTreeTx(tree)
  1333. }
  1334. needReloadFiletree = true
  1335. }
  1336. historyDir := filepath.Join(util.HistoryDir, mergeResult.Time.Format("2006-01-02-150405")+"-sync")
  1337. indexHistoryDir(filepath.Base(historyDir), luteEngine)
  1338. }
  1339. if 1 > len(mergeResult.Upserts) && 1 > len(mergeResult.Removes) && 1 > len(mergeResult.Conflicts) { // 没有数据变更
  1340. syncSameCount.Add(1)
  1341. if 10 < syncSameCount.Load() {
  1342. syncSameCount.Store(5)
  1343. }
  1344. if !byHand {
  1345. delay := time.Minute * time.Duration(int(math.Pow(2, float64(syncSameCount.Load()))))
  1346. if fixSyncInterval.Minutes() > delay.Minutes() {
  1347. delay = time.Minute * 8
  1348. }
  1349. planSyncAfter(delay)
  1350. }
  1351. util.PushClearProgress()
  1352. return
  1353. }
  1354. // 有数据变更,需要重建索引
  1355. var upserts, removes []string
  1356. var upsertTrees int
  1357. // 可能需要重新加载部分功能
  1358. var needReloadFlashcard, needReloadOcrTexts, needReloadPlugin bool
  1359. upsertPluginSet := hashset.New()
  1360. needUnindexBoxes, needIndexBoxes := map[string]bool{}, map[string]bool{}
  1361. for _, file := range mergeResult.Upserts {
  1362. upserts = append(upserts, file.Path)
  1363. if strings.HasPrefix(file.Path, "/storage/riff/") {
  1364. needReloadFlashcard = true
  1365. }
  1366. if strings.HasPrefix(file.Path, "/assets/ocr-texts.json") {
  1367. needReloadOcrTexts = true
  1368. }
  1369. if strings.HasSuffix(file.Path, "/.siyuan/conf.json") {
  1370. needReloadFiletree = true
  1371. boxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/conf.json")
  1372. needUnindexBoxes[boxID] = true
  1373. needIndexBoxes[boxID] = true
  1374. }
  1375. if strings.HasPrefix(file.Path, "/storage/petal/") {
  1376. needReloadPlugin = true
  1377. if parts := strings.Split(file.Path, "/"); 3 < len(parts) {
  1378. if pluginName := parts[3]; "petals.json" != pluginName {
  1379. upsertPluginSet.Add(pluginName)
  1380. }
  1381. }
  1382. }
  1383. if strings.HasPrefix(file.Path, "/plugins/") {
  1384. if parts := strings.Split(file.Path, "/"); 2 < len(parts) {
  1385. needReloadPlugin = true
  1386. upsertPluginSet.Add(parts[2])
  1387. }
  1388. }
  1389. if strings.HasSuffix(file.Path, ".sy") {
  1390. upsertTrees++
  1391. }
  1392. }
  1393. removeWidgetDirSet, removePluginSet := hashset.New(), hashset.New()
  1394. for _, file := range mergeResult.Removes {
  1395. removes = append(removes, file.Path)
  1396. if strings.HasPrefix(file.Path, "/storage/riff/") {
  1397. needReloadFlashcard = true
  1398. }
  1399. if strings.HasPrefix(file.Path, "/assets/ocr-texts.json") {
  1400. needReloadOcrTexts = true
  1401. }
  1402. if strings.HasSuffix(file.Path, "/.siyuan/conf.json") {
  1403. needReloadFiletree = true
  1404. boxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/conf.json")
  1405. needUnindexBoxes[boxID] = true
  1406. }
  1407. if strings.HasPrefix(file.Path, "/storage/petal/") {
  1408. needReloadPlugin = true
  1409. if parts := strings.Split(file.Path, "/"); 3 < len(parts) {
  1410. if pluginName := parts[3]; "petals.json" != pluginName {
  1411. removePluginSet.Add(pluginName)
  1412. }
  1413. }
  1414. }
  1415. if strings.HasPrefix(file.Path, "/plugins/") {
  1416. if parts := strings.Split(file.Path, "/"); 2 < len(parts) {
  1417. needReloadPlugin = true
  1418. removePluginSet.Add(parts[2])
  1419. }
  1420. }
  1421. if strings.HasPrefix(file.Path, "/widgets/") {
  1422. if parts := strings.Split(file.Path, "/"); 2 < len(parts) {
  1423. removeWidgetDirSet.Add(parts[2])
  1424. }
  1425. }
  1426. }
  1427. if needReloadFlashcard {
  1428. LoadFlashcards()
  1429. }
  1430. if needReloadOcrTexts {
  1431. util.LoadAssetsTexts()
  1432. }
  1433. if needReloadPlugin {
  1434. pushReloadPlugin(upsertPluginSet, removePluginSet)
  1435. }
  1436. for _, widgetDir := range removeWidgetDirSet.Values() {
  1437. widgetDirPath := filepath.Join(util.DataDir, "widgets", widgetDir.(string))
  1438. gulu.File.RemoveEmptyDirs(widgetDirPath)
  1439. }
  1440. syncingFiles = sync.Map{}
  1441. syncingStorages.Store(false)
  1442. if needFullReindex(upsertTrees) { // 改进同步后全量重建索引判断 https://github.com/siyuan-note/siyuan/issues/5764
  1443. FullReindex()
  1444. return
  1445. }
  1446. if exit { // 退出时同步不用推送事件
  1447. return
  1448. }
  1449. for boxID := range needUnindexBoxes {
  1450. if box := Conf.GetBox(boxID); nil != box {
  1451. box.Unindex()
  1452. }
  1453. }
  1454. for boxID := range needIndexBoxes {
  1455. if box := Conf.GetBox(boxID); nil != box {
  1456. box.Index()
  1457. }
  1458. }
  1459. needReloadUI := 0 < len(needUnindexBoxes) || 0 < len(needIndexBoxes)
  1460. if needReloadUI {
  1461. util.ReloadUI()
  1462. }
  1463. upsertRootIDs, removeRootIDs := incReindex(upserts, removes)
  1464. needReloadFiletree = !needReloadUI && (needReloadFiletree || 0 < len(upsertRootIDs) || 0 < len(removeRootIDs))
  1465. if needReloadFiletree {
  1466. util.PushReloadFiletree()
  1467. }
  1468. go func() {
  1469. util.WaitForUILoaded()
  1470. if 0 < len(upsertRootIDs) || 0 < len(removeRootIDs) {
  1471. util.BroadcastByType("main", "syncMergeResult", 0, "",
  1472. map[string]interface{}{"upsertRootIDs": upsertRootIDs, "removeRootIDs": removeRootIDs})
  1473. }
  1474. time.Sleep(2 * time.Second)
  1475. util.PushStatusBar(fmt.Sprintf(Conf.Language(149), elapsed.Seconds()))
  1476. if 0 < len(mergeResult.Conflicts) {
  1477. syConflict := false
  1478. for _, file := range mergeResult.Conflicts {
  1479. if strings.HasSuffix(file.Path, ".sy") {
  1480. syConflict = true
  1481. break
  1482. }
  1483. }
  1484. if syConflict {
  1485. // 数据同步发生冲突时在界面上进行提醒 https://github.com/siyuan-note/siyuan/issues/7332
  1486. util.PushMsg(Conf.Language(108), 7000)
  1487. }
  1488. }
  1489. }()
  1490. }
  1491. func logSyncMergeResult(mergeResult *dejavu.MergeResult) {
  1492. if 1 > len(mergeResult.Conflicts) && 1 > len(mergeResult.Upserts) && 1 > len(mergeResult.Removes) {
  1493. return
  1494. }
  1495. if 0 < len(mergeResult.Conflicts) {
  1496. logBuilder := bytes.Buffer{}
  1497. for i, f := range mergeResult.Conflicts {
  1498. logBuilder.WriteString(" ")
  1499. logBuilder.WriteString(f.Path)
  1500. if i < len(mergeResult.Conflicts)-1 {
  1501. logBuilder.WriteString("\n")
  1502. }
  1503. }
  1504. logging.LogInfof("sync conflicts:\n%s", logBuilder.String())
  1505. }
  1506. if 0 < len(mergeResult.Upserts) {
  1507. logBuilder := bytes.Buffer{}
  1508. for i, f := range mergeResult.Upserts {
  1509. logBuilder.WriteString(" ")
  1510. logBuilder.WriteString(f.Path)
  1511. if i < len(mergeResult.Upserts)-1 {
  1512. logBuilder.WriteString("\n")
  1513. }
  1514. }
  1515. logging.LogInfof("sync merge upserts:\n%s", logBuilder.String())
  1516. }
  1517. if 0 < len(mergeResult.Removes) {
  1518. logBuilder := bytes.Buffer{}
  1519. for i, f := range mergeResult.Removes {
  1520. logBuilder.WriteString(" ")
  1521. logBuilder.WriteString(f.Path)
  1522. if i < len(mergeResult.Removes)-1 {
  1523. logBuilder.WriteString("\n")
  1524. }
  1525. }
  1526. logging.LogInfof("sync merge removes:\n%s", logBuilder.String())
  1527. }
  1528. }
  1529. func needFullReindex(upsertTrees int) bool {
  1530. return 0.2 < float64(upsertTrees)/float64(treenode.CountTrees())
  1531. }
  1532. var promotedPurgeDataRepo bool
  1533. func indexRepoBeforeCloudSync(repo *dejavu.Repo) (beforeIndex, afterIndex *entity.Index, err error) {
  1534. start := time.Now()
  1535. beforeIndex, _ = repo.Latest()
  1536. FlushTxQueue()
  1537. checkChunks := true
  1538. if util.ContainerAndroid == util.Container || util.ContainerIOS == util.Container || util.ContainerHarmony == util.Container {
  1539. // 因为移动端私有数据空间不会存在外部操作导致分块损坏的情况,所以不需要检查分块以提升性能 https://github.com/siyuan-note/siyuan/issues/13216
  1540. checkChunks = false
  1541. }
  1542. afterIndex, err = repo.Index("[Sync] Cloud sync", checkChunks,
  1543. map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar})
  1544. if err != nil {
  1545. logging.LogErrorf("index data repo before cloud sync failed: %s", err)
  1546. return
  1547. }
  1548. elapsed := time.Since(start)
  1549. if nil == beforeIndex || beforeIndex.ID != afterIndex.ID {
  1550. // 对新创建的快照需要更新备注,加入耗时统计
  1551. afterIndex.Memo = fmt.Sprintf("[Sync] Cloud sync, completed in %.2fs", elapsed.Seconds())
  1552. if err = repo.PutIndex(afterIndex); err != nil {
  1553. util.PushStatusBar("Save data snapshot for cloud sync failed")
  1554. logging.LogErrorf("put index into data repo before cloud sync failed: %s", err)
  1555. return
  1556. }
  1557. util.PushStatusBar(fmt.Sprintf(Conf.Language(147), elapsed.Seconds()))
  1558. } else {
  1559. util.PushStatusBar(fmt.Sprintf(Conf.Language(148), elapsed.Seconds()))
  1560. }
  1561. if Conf.Repo.SyncIndexTiming < elapsed.Milliseconds() {
  1562. logging.LogWarnf("index data repo before cloud sync elapsed [%dms]", elapsed.Milliseconds())
  1563. if !promotedPurgeDataRepo {
  1564. go func() {
  1565. util.WaitForUILoaded()
  1566. time.Sleep(3 * time.Second)
  1567. if indexCount, _ := repo.CountIndexes(); 128 > indexCount {
  1568. // 快照数量较少时不推送提示
  1569. return
  1570. }
  1571. util.PushMsg(Conf.language(218), 24000)
  1572. promotedPurgeDataRepo = true
  1573. }()
  1574. }
  1575. }
  1576. return
  1577. }
  1578. func newRepository() (ret *dejavu.Repo, err error) {
  1579. cloudConf, err := buildCloudConf()
  1580. if err != nil {
  1581. return
  1582. }
  1583. var cloudRepo cloud.Cloud
  1584. switch Conf.Sync.Provider {
  1585. case conf.ProviderSiYuan:
  1586. cloudRepo = cloud.NewSiYuan(&cloud.BaseCloud{Conf: cloudConf})
  1587. case conf.ProviderS3:
  1588. s3HTTPClient := &http.Client{Transport: httpclient.NewTransport(cloudConf.S3.SkipTlsVerify)}
  1589. s3HTTPClient.Timeout = time.Duration(cloudConf.S3.Timeout) * time.Second
  1590. cloudRepo = cloud.NewS3(&cloud.BaseCloud{Conf: cloudConf}, s3HTTPClient)
  1591. case conf.ProviderWebDAV:
  1592. webdavClient := gowebdav.NewClient(cloudConf.WebDAV.Endpoint, cloudConf.WebDAV.Username, cloudConf.WebDAV.Password)
  1593. a := cloudConf.WebDAV.Username + ":" + cloudConf.WebDAV.Password
  1594. auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(a))
  1595. webdavClient.SetHeader("Authorization", auth)
  1596. webdavClient.SetHeader("User-Agent", util.UserAgent)
  1597. webdavClient.SetTimeout(time.Duration(cloudConf.WebDAV.Timeout) * time.Second)
  1598. webdavClient.SetTransport(httpclient.NewTransport(cloudConf.WebDAV.SkipTlsVerify))
  1599. cloudRepo = cloud.NewWebDAV(&cloud.BaseCloud{Conf: cloudConf}, webdavClient)
  1600. default:
  1601. err = fmt.Errorf("unknown cloud provider [%d]", Conf.Sync.Provider)
  1602. return
  1603. }
  1604. ignoreLines := getSyncIgnoreLines()
  1605. ignoreLines = append(ignoreLines, "/.siyuan/conf.json") // 忽略旧版同步配置
  1606. ret, err = dejavu.NewRepo(util.DataDir, util.RepoDir, util.HistoryDir, util.TempDir, Conf.System.ID, Conf.System.Name, Conf.System.OS, Conf.Repo.Key, ignoreLines, cloudRepo)
  1607. if err != nil {
  1608. logging.LogErrorf("init data repo failed: %s", err)
  1609. return
  1610. }
  1611. return
  1612. }
  1613. func init() {
  1614. subscribeRepoEvents()
  1615. }
  1616. func subscribeRepoEvents() {
  1617. eventbus.Subscribe(eventbus.EvtIndexBeforeWalkData, func(context map[string]interface{}, path string) {
  1618. msg := fmt.Sprintf(Conf.Language(158), path)
  1619. util.SetBootDetails(msg)
  1620. util.ContextPushMsg(context, msg)
  1621. })
  1622. indexWalkDataCount := 0
  1623. eventbus.Subscribe(eventbus.EvtIndexWalkData, func(context map[string]interface{}, path string) {
  1624. msg := fmt.Sprintf(Conf.Language(158), filepath.Base(path))
  1625. if 0 == indexWalkDataCount%1024 {
  1626. util.SetBootDetails(msg)
  1627. util.ContextPushMsg(context, msg)
  1628. }
  1629. indexWalkDataCount++
  1630. })
  1631. eventbus.Subscribe(eventbus.EvtIndexBeforeGetLatestFiles, func(context map[string]interface{}, total int) {
  1632. msg := fmt.Sprintf(Conf.Language(159), 0, total)
  1633. util.SetBootDetails(msg)
  1634. util.ContextPushMsg(context, msg)
  1635. })
  1636. eventbus.Subscribe(eventbus.EvtIndexGetLatestFile, func(context map[string]interface{}, count int, total int) {
  1637. msg := fmt.Sprintf(Conf.Language(159), count, total)
  1638. if 0 == count%64 {
  1639. util.SetBootDetails(msg)
  1640. util.ContextPushMsg(context, msg)
  1641. }
  1642. })
  1643. eventbus.Subscribe(eventbus.EvtIndexUpsertFiles, func(context map[string]interface{}, total int) {
  1644. msg := fmt.Sprintf(Conf.Language(160), 0, total)
  1645. util.SetBootDetails(msg)
  1646. util.ContextPushMsg(context, msg)
  1647. })
  1648. eventbus.Subscribe(eventbus.EvtIndexUpsertFile, func(context map[string]interface{}, count int, total int) {
  1649. msg := fmt.Sprintf(Conf.Language(160), count, total)
  1650. if 0 == count%32 {
  1651. util.SetBootDetails(msg)
  1652. util.ContextPushMsg(context, msg)
  1653. }
  1654. })
  1655. eventbus.Subscribe(eventbus.EvtCheckoutBeforeWalkData, func(context map[string]interface{}, path string) {
  1656. msg := fmt.Sprintf(Conf.Language(161), path)
  1657. util.SetBootDetails(msg)
  1658. util.ContextPushMsg(context, msg)
  1659. })
  1660. coWalkDataCount := 0
  1661. eventbus.Subscribe(eventbus.EvtCheckoutWalkData, func(context map[string]interface{}, path string) {
  1662. msg := fmt.Sprintf(Conf.Language(161), filepath.Base(path))
  1663. if 0 == coWalkDataCount%512 {
  1664. util.SetBootDetails(msg)
  1665. util.ContextPushMsg(context, msg)
  1666. }
  1667. coWalkDataCount++
  1668. })
  1669. var bootProgressPart int32
  1670. eventbus.Subscribe(eventbus.EvtCheckoutUpsertFiles, func(context map[string]interface{}, total int) {
  1671. msg := fmt.Sprintf(Conf.Language(162), 0, total)
  1672. util.SetBootDetails(msg)
  1673. bootProgressPart = int32(10 / float64(total))
  1674. util.ContextPushMsg(context, msg)
  1675. })
  1676. coUpsertFileCount := 0
  1677. eventbus.Subscribe(eventbus.EvtCheckoutUpsertFile, func(context map[string]interface{}, count, total int) {
  1678. msg := fmt.Sprintf(Conf.Language(162), count, total)
  1679. util.IncBootProgress(bootProgressPart, msg)
  1680. if 0 == coUpsertFileCount%32 {
  1681. util.ContextPushMsg(context, msg)
  1682. }
  1683. coUpsertFileCount++
  1684. })
  1685. eventbus.Subscribe(eventbus.EvtCheckoutRemoveFiles, func(context map[string]interface{}, total int) {
  1686. msg := fmt.Sprintf(Conf.Language(163), 0, total)
  1687. util.SetBootDetails(msg)
  1688. bootProgressPart = int32(10 / float64(total))
  1689. util.ContextPushMsg(context, msg)
  1690. })
  1691. eventbus.Subscribe(eventbus.EvtCheckoutRemoveFile, func(context map[string]interface{}, count, total int) {
  1692. msg := fmt.Sprintf(Conf.Language(163), count, total)
  1693. util.IncBootProgress(bootProgressPart, msg)
  1694. if 0 == count%64 {
  1695. util.ContextPushMsg(context, msg)
  1696. }
  1697. })
  1698. eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadIndex, func(context map[string]interface{}, id string) {
  1699. msg := fmt.Sprintf(Conf.Language(164), id[:7])
  1700. util.IncBootProgress(1, msg)
  1701. util.ContextPushMsg(context, msg)
  1702. })
  1703. eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadFiles, func(context map[string]interface{}, total int) {
  1704. msg := fmt.Sprintf(Conf.Language(165), 0, total)
  1705. util.SetBootDetails(msg)
  1706. bootProgressPart = int32(10 / float64(total))
  1707. util.ContextPushMsg(context, msg)
  1708. })
  1709. eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadFile, func(context map[string]interface{}, count, total int) {
  1710. msg := fmt.Sprintf(Conf.Language(165), count, total)
  1711. util.IncBootProgress(bootProgressPart, msg)
  1712. if 0 == count%8 {
  1713. util.ContextPushMsg(context, msg)
  1714. }
  1715. })
  1716. eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadChunks, func(context map[string]interface{}, total int) {
  1717. msg := fmt.Sprintf(Conf.Language(166), 0, total)
  1718. util.SetBootDetails(msg)
  1719. bootProgressPart = int32(10 / float64(total))
  1720. util.ContextPushMsg(context, msg)
  1721. })
  1722. eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadChunk, func(context map[string]interface{}, count, total int) {
  1723. msg := fmt.Sprintf(Conf.Language(166), count, total)
  1724. util.IncBootProgress(bootProgressPart, msg)
  1725. if 0 == count%8 {
  1726. util.ContextPushMsg(context, msg)
  1727. }
  1728. })
  1729. eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadRef, func(context map[string]interface{}, ref string) {
  1730. msg := fmt.Sprintf(Conf.Language(167), ref)
  1731. util.IncBootProgress(1, msg)
  1732. util.ContextPushMsg(context, msg)
  1733. })
  1734. eventbus.Subscribe(eventbus.EvtCloudBeforeUploadIndex, func(context map[string]interface{}, id string) {
  1735. msg := fmt.Sprintf(Conf.Language(168), id[:7])
  1736. util.IncBootProgress(1, msg)
  1737. util.ContextPushMsg(context, msg)
  1738. })
  1739. eventbus.Subscribe(eventbus.EvtCloudBeforeUploadFiles, func(context map[string]interface{}, total int) {
  1740. msg := fmt.Sprintf(Conf.Language(169), 0, total)
  1741. util.SetBootDetails(msg)
  1742. util.ContextPushMsg(context, msg)
  1743. })
  1744. eventbus.Subscribe(eventbus.EvtCloudBeforeUploadFile, func(context map[string]interface{}, count, total int) {
  1745. msg := fmt.Sprintf(Conf.Language(169), count, total)
  1746. if 0 == count%8 {
  1747. util.SetBootDetails(msg)
  1748. util.ContextPushMsg(context, msg)
  1749. }
  1750. })
  1751. eventbus.Subscribe(eventbus.EvtCloudBeforeUploadChunks, func(context map[string]interface{}, total int) {
  1752. msg := fmt.Sprintf(Conf.Language(170), 0, total)
  1753. util.SetBootDetails(msg)
  1754. util.ContextPushMsg(context, msg)
  1755. })
  1756. eventbus.Subscribe(eventbus.EvtCloudBeforeUploadChunk, func(context map[string]interface{}, count, total int) {
  1757. msg := fmt.Sprintf(Conf.Language(170), count, total)
  1758. if 0 == count%8 {
  1759. util.SetBootDetails(msg)
  1760. util.ContextPushMsg(context, msg)
  1761. }
  1762. })
  1763. eventbus.Subscribe(eventbus.EvtCloudBeforeUploadRef, func(context map[string]interface{}, ref string) {
  1764. msg := fmt.Sprintf(Conf.Language(171), ref)
  1765. util.SetBootDetails(msg)
  1766. util.ContextPushMsg(context, msg)
  1767. })
  1768. eventbus.Subscribe(eventbus.EvtCloudLock, func(context map[string]interface{}) {
  1769. msg := fmt.Sprintf(Conf.Language(186))
  1770. util.SetBootDetails(msg)
  1771. util.ContextPushMsg(context, msg)
  1772. })
  1773. eventbus.Subscribe(eventbus.EvtCloudUnlock, func(context map[string]interface{}) {
  1774. msg := fmt.Sprintf(Conf.Language(187))
  1775. util.SetBootDetails(msg)
  1776. util.ContextPushMsg(context, msg)
  1777. })
  1778. eventbus.Subscribe(eventbus.EvtCloudBeforeUploadIndexes, func(context map[string]interface{}) {
  1779. msg := fmt.Sprintf(Conf.Language(208))
  1780. util.SetBootDetails(msg)
  1781. util.ContextPushMsg(context, msg)
  1782. })
  1783. eventbus.Subscribe(eventbus.EvtCloudBeforeUploadCheckIndex, func(context map[string]interface{}) {
  1784. msg := fmt.Sprintf(Conf.Language(209))
  1785. util.SetBootDetails(msg)
  1786. util.ContextPushMsg(context, msg)
  1787. })
  1788. eventbus.Subscribe(eventbus.EvtCloudBeforeFixObjects, func(context map[string]interface{}, count, total int) {
  1789. msg := fmt.Sprintf(Conf.Language(210), count, total)
  1790. util.SetBootDetails(msg)
  1791. util.ContextPushMsg(context, msg)
  1792. })
  1793. eventbus.Subscribe(eventbus.EvtCloudAfterFixObjects, func(context map[string]interface{}) {
  1794. msg := fmt.Sprintf(Conf.Language(211))
  1795. util.SetBootDetails(msg)
  1796. util.ContextPushMsg(context, msg)
  1797. })
  1798. eventbus.Subscribe(eventbus.EvtCloudCorrupted, func() {
  1799. util.PushErrMsg(Conf.language(220), 30000)
  1800. })
  1801. eventbus.Subscribe(eventbus.EvtCloudPurgeListObjects, func(context map[string]interface{}) {
  1802. util.ContextPushMsg(context, Conf.language(224))
  1803. })
  1804. eventbus.Subscribe(eventbus.EvtCloudPurgeListIndexes, func(context map[string]interface{}) {
  1805. util.ContextPushMsg(context, Conf.language(225))
  1806. })
  1807. eventbus.Subscribe(eventbus.EvtCloudPurgeListRefs, func(context map[string]interface{}) {
  1808. util.ContextPushMsg(context, Conf.language(226))
  1809. })
  1810. eventbus.Subscribe(eventbus.EvtCloudPurgeDownloadIndexes, func(context map[string]interface{}) {
  1811. util.ContextPushMsg(context, fmt.Sprintf(Conf.language(227)))
  1812. })
  1813. eventbus.Subscribe(eventbus.EvtCloudPurgeDownloadFiles, func(context map[string]interface{}) {
  1814. util.ContextPushMsg(context, Conf.language(228))
  1815. })
  1816. eventbus.Subscribe(eventbus.EvtCloudPurgeRemoveIndexes, func(context map[string]interface{}) {
  1817. util.ContextPushMsg(context, Conf.language(229))
  1818. })
  1819. eventbus.Subscribe(eventbus.EvtCloudPurgeRemoveIndexesV2, func(context map[string]interface{}) {
  1820. util.ContextPushMsg(context, Conf.language(230))
  1821. })
  1822. eventbus.Subscribe(eventbus.EvtCloudPurgeRemoveObjects, func(context map[string]interface{}) {
  1823. util.ContextPushMsg(context, Conf.language(231))
  1824. })
  1825. }
  1826. func buildCloudConf() (ret *cloud.Conf, err error) {
  1827. if !cloud.IsValidCloudDirName(Conf.Sync.CloudName) {
  1828. logging.LogWarnf("invalid cloud repo name, rename it to [main]")
  1829. Conf.Sync.CloudName = "main"
  1830. Conf.Save()
  1831. }
  1832. userId, token, availableSize := "0", "", int64(1024*1024*1024*1024*2)
  1833. if nil != Conf.User && conf.ProviderSiYuan == Conf.Sync.Provider {
  1834. u := Conf.GetUser()
  1835. userId = u.UserId
  1836. token = u.UserToken
  1837. availableSize = u.GetCloudRepoAvailableSize()
  1838. }
  1839. ret = &cloud.Conf{
  1840. Dir: Conf.Sync.CloudName,
  1841. UserID: userId,
  1842. Token: token,
  1843. AvailableSize: availableSize,
  1844. Server: util.GetCloudServer(),
  1845. }
  1846. switch Conf.Sync.Provider {
  1847. case conf.ProviderSiYuan:
  1848. ret.Endpoint = util.GetCloudSyncServer()
  1849. case conf.ProviderS3:
  1850. ret.S3 = &cloud.ConfS3{
  1851. Endpoint: Conf.Sync.S3.Endpoint,
  1852. AccessKey: Conf.Sync.S3.AccessKey,
  1853. SecretKey: Conf.Sync.S3.SecretKey,
  1854. Bucket: Conf.Sync.S3.Bucket,
  1855. Region: Conf.Sync.S3.Region,
  1856. PathStyle: Conf.Sync.S3.PathStyle,
  1857. SkipTlsVerify: Conf.Sync.S3.SkipTlsVerify,
  1858. Timeout: Conf.Sync.S3.Timeout,
  1859. ConcurrentReqs: Conf.Sync.S3.ConcurrentReqs,
  1860. }
  1861. case conf.ProviderWebDAV:
  1862. ret.WebDAV = &cloud.ConfWebDAV{
  1863. Endpoint: Conf.Sync.WebDAV.Endpoint,
  1864. Username: Conf.Sync.WebDAV.Username,
  1865. Password: Conf.Sync.WebDAV.Password,
  1866. SkipTlsVerify: Conf.Sync.WebDAV.SkipTlsVerify,
  1867. Timeout: Conf.Sync.WebDAV.Timeout,
  1868. ConcurrentReqs: Conf.Sync.WebDAV.ConcurrentReqs,
  1869. }
  1870. default:
  1871. err = fmt.Errorf("invalid provider [%d]", Conf.Sync.Provider)
  1872. return
  1873. }
  1874. return
  1875. }
  1876. type Backup struct {
  1877. Size int64 `json:"size"`
  1878. HSize string `json:"hSize"`
  1879. Updated string `json:"updated"`
  1880. SaveDir string `json:"saveDir"` // 本地备份数据存放目录路径
  1881. }
  1882. type Sync struct {
  1883. Size int64 `json:"size"`
  1884. HSize string `json:"hSize"`
  1885. Updated string `json:"updated"`
  1886. CloudName string `json:"cloudName"` // 云端同步数据存放目录名
  1887. SaveDir string `json:"saveDir"` // 本地同步数据存放目录路径
  1888. }
  1889. func GetCloudSpace() (s *Sync, b *Backup, hSize, hAssetSize, hTotalSize, hExchangeSize, hTrafficUploadSize, hTrafficDownloadSize, hTrafficAPIGet, hTrafficAPIPut string, err error) {
  1890. stat, err := getCloudSpace()
  1891. if err != nil {
  1892. err = errors.New(Conf.Language(30) + " " + err.Error())
  1893. return
  1894. }
  1895. syncSize := stat.Sync.Size
  1896. syncUpdated := stat.Sync.Updated
  1897. s = &Sync{
  1898. Size: syncSize,
  1899. HSize: "-",
  1900. Updated: syncUpdated,
  1901. }
  1902. backupSize := stat.Backup.Size
  1903. backupUpdated := stat.Backup.Updated
  1904. b = &Backup{
  1905. Size: backupSize,
  1906. HSize: "-",
  1907. Updated: backupUpdated,
  1908. }
  1909. assetSize := stat.AssetSize
  1910. totalSize := syncSize + backupSize + assetSize
  1911. hAssetSize = "-"
  1912. hSize = "-"
  1913. hTotalSize = "-"
  1914. hExchangeSize = "-"
  1915. hTrafficUploadSize = "-"
  1916. hTrafficDownloadSize = "-"
  1917. hTrafficAPIGet = "-"
  1918. hTrafficAPIPut = "-"
  1919. if conf.ProviderSiYuan == Conf.Sync.Provider {
  1920. s.HSize = humanize.BytesCustomCeil(uint64(syncSize), 2)
  1921. b.HSize = humanize.BytesCustomCeil(uint64(backupSize), 2)
  1922. hAssetSize = humanize.BytesCustomCeil(uint64(assetSize), 2)
  1923. hSize = humanize.BytesCustomCeil(uint64(totalSize), 2)
  1924. u := Conf.GetUser()
  1925. hTotalSize = humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2)
  1926. hExchangeSize = humanize.BytesCustomCeil(uint64(u.UserSiYuanPointExchangeRepoSize), 2)
  1927. hTrafficUploadSize = humanize.BytesCustomCeil(uint64(u.UserTrafficUpload), 2)
  1928. hTrafficDownloadSize = humanize.BytesCustomCeil(uint64(u.UserTrafficDownload), 2)
  1929. hTrafficAPIGet = humanize.SIWithDigits(u.UserTrafficAPIGet, 2, "")
  1930. hTrafficAPIPut = humanize.SIWithDigits(u.UserTrafficAPIPut, 2, "")
  1931. }
  1932. return
  1933. }
  1934. func getCloudSpace() (stat *cloud.Stat, err error) {
  1935. repo, err := newRepository()
  1936. if err != nil {
  1937. return
  1938. }
  1939. stat, err = repo.GetCloudRepoStat()
  1940. if err != nil {
  1941. logging.LogErrorf("get cloud repo stat failed: %s", err)
  1942. return
  1943. }
  1944. return
  1945. }
  1946. func pushReloadPlugin(upsertPluginSet, removePluginNameSet *hashset.Set) {
  1947. upsertPlugins, removePlugins := []string{}, []string{}
  1948. for _, n := range upsertPluginSet.Values() {
  1949. upsertPlugins = append(upsertPlugins, n.(string))
  1950. }
  1951. for _, n := range removePluginNameSet.Values() {
  1952. removePlugins = append(removePlugins, n.(string))
  1953. }
  1954. logging.LogInfof("reload plugins [upserts=%v, removes=%v]", upsertPlugins, removePlugins)
  1955. util.BroadcastByType("main", "reloadPlugin", 0, "", map[string]interface{}{
  1956. "upsertPlugins": upsertPlugins,
  1957. "removePlugins": removePlugins,
  1958. })
  1959. }