assets_watcher_darwin.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. //go:build darwin
  17. package model
  18. import (
  19. "path/filepath"
  20. "time"
  21. "github.com/radovskyb/watcher"
  22. "github.com/siyuan-note/logging"
  23. "github.com/siyuan-note/siyuan/kernel/cache"
  24. "github.com/siyuan-note/siyuan/kernel/util"
  25. )
  26. var assetsWatcher *watcher.Watcher
  27. func WatchAssets() {
  28. go func() {
  29. watchAssets()
  30. }()
  31. }
  32. func watchAssets() {
  33. if nil != assetsWatcher {
  34. assetsWatcher.Close()
  35. }
  36. assetsWatcher = watcher.New()
  37. assetsDir := filepath.Join(util.DataDir, "assets")
  38. go func() {
  39. for {
  40. select {
  41. case event, ok := <-assetsWatcher.Event:
  42. if !ok {
  43. return
  44. }
  45. //logging.LogInfof("assets changed: %s", event)
  46. if watcher.Write == event.Op {
  47. IncSync()
  48. }
  49. // 重新缓存资源文件,以便使用 /资源 搜索
  50. go cache.LoadAssets()
  51. if watcher.Remove == event.Op {
  52. RemoveIndexAssetContent(event.Path)
  53. } else {
  54. IndexAssetContent(event.Path)
  55. }
  56. case err, ok := <-assetsWatcher.Error:
  57. if !ok {
  58. return
  59. }
  60. logging.LogErrorf("watch assets failed: %s", err)
  61. case <-assetsWatcher.Closed:
  62. return
  63. }
  64. }
  65. }()
  66. if err := assetsWatcher.Add(assetsDir); nil != err {
  67. logging.LogErrorf("add assets watcher for folder [%s] failed: %s", assetsDir, err)
  68. return
  69. }
  70. //logging.LogInfof("added file watcher [%s]", assetsDir)
  71. if err := assetsWatcher.Start(10 * time.Second); nil != err {
  72. logging.LogErrorf("start assets watcher for folder [%s] failed: %s", assetsDir, err)
  73. return
  74. }
  75. }
  76. func CloseWatchAssets() {
  77. if nil != assetsWatcher {
  78. assetsWatcher.Close()
  79. }
  80. }