watcher.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. package read
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "time"
  8. "github.com/felamaslen/gmus-backend/pkg/database"
  9. "github.com/felamaslen/gmus-backend/pkg/logger"
  10. "github.com/felamaslen/gmus-backend/pkg/repository"
  11. "github.com/felamaslen/gmus-backend/pkg/types"
  12. "github.com/fsnotify/fsnotify"
  13. "github.com/jmoiron/sqlx"
  14. )
  15. // Watch file system for real time updates
  16. var watcher *fsnotify.Watcher
  17. func watchDir(path string, fi os.FileInfo, err error) error {
  18. if fi.Mode().IsDir() {
  19. return watcher.Add(path)
  20. }
  21. return nil
  22. }
  23. func getRelativePath(fileName string, rootDirectory string) (relativePath string, err error) {
  24. if strings.Index(fileName, rootDirectory) != 0 {
  25. return "", fmt.Errorf("File is not in root directory")
  26. }
  27. if len(fileName) < len(rootDirectory)+1 {
  28. return "", fmt.Errorf("File is empty apart from root directory")
  29. }
  30. relativePath = (fileName[len(rootDirectory)+1:])
  31. return
  32. }
  33. func handleFileRemoveOrRename(l *logger.Logger, db *sqlx.DB, rootDirectory string, event fsnotify.Event) {
  34. relativePath, err := getRelativePath(event.Name, rootDirectory)
  35. if err != nil {
  36. l.Warn("[WATCH] delete error: %v\n", err)
  37. return
  38. }
  39. l.Verbose("[WATCH] delete: basePath=%s, relativePath=%s\n", rootDirectory, relativePath)
  40. watcher.Remove(event.Name)
  41. repository.DeleteSongByPath(db, rootDirectory, relativePath)
  42. return
  43. }
  44. // This is an ugly hack to wait until a file has completed writing, since fsnotify
  45. // doesn't support the IN_CLOSE_WRITE event
  46. // See this and related issues: https://github.com/fsnotify/fsnotify/pull/313, https://github.com/fsnotify/fsnotify/issues/22
  47. const WRITE_WAIT_TIME = 2 * time.Second
  48. var writeWaitMap = map[string]*time.Timer{}
  49. func handleFileOnceWritten(l *logger.Logger, db *sqlx.DB, rootDirectory string, filePath string) {
  50. relativePath, err := getRelativePath(filePath, rootDirectory)
  51. l.Verbose("[WATCH] create: basePath=%s, relativePath=%s\n", rootDirectory, relativePath)
  52. if err != nil {
  53. l.Warn("[WATCH] invalid path: %v\n", err)
  54. return
  55. }
  56. file, err := os.Stat(filePath)
  57. if err != nil {
  58. l.Warn("[WATCH] error reading file: %v\n", err)
  59. return
  60. }
  61. if file.IsDir() {
  62. return
  63. }
  64. validFile := GetFileInfo(file, relativePath)
  65. if validFile == nil {
  66. l.Warn("[WATCH] invalid file: %s\n", filePath)
  67. return
  68. }
  69. song, err := ReadFile(rootDirectory, validFile)
  70. if err != nil {
  71. l.Warn("[WATCH] error scanning file (file: %v): %v\n", validFile, err)
  72. return
  73. }
  74. var batch [BATCH_SIZE]*types.Song
  75. batch[0] = song
  76. if err := repository.BatchUpsertSongs(db, &batch, 1); err != nil {
  77. l.Error("[WATCH] error adding file: %v\n", err)
  78. }
  79. }
  80. func waitUntilFileIsWritten(l *logger.Logger, db *sqlx.DB, rootDirectory string, event fsnotify.Event) {
  81. var filePath = event.Name
  82. if writeWaitMap[filePath] != nil {
  83. writeWaitMap[filePath].Stop()
  84. }
  85. writeWaitMap[filePath] = time.NewTimer(WRITE_WAIT_TIME)
  86. go func() {
  87. <-writeWaitMap[filePath].C
  88. handleFileOnceWritten(l, db, rootDirectory, filePath)
  89. delete(writeWaitMap, filePath)
  90. }()
  91. }
  92. func handleFileCreateEvent(l *logger.Logger, db *sqlx.DB, rootDirectory string, event fsnotify.Event) {
  93. filePath := event.Name
  94. file, err := os.Stat(filePath)
  95. if err != nil {
  96. l.Warn("[WATCH] error reading file: %v\n", err)
  97. return
  98. }
  99. if file.IsDir() {
  100. l.Verbose("[WATCH] adding directory to watcher: %s\n", filePath)
  101. watcher.Add(filePath)
  102. } else {
  103. waitUntilFileIsWritten(l, db, rootDirectory, event)
  104. }
  105. }
  106. func handleWatcherEvent(l *logger.Logger, db *sqlx.DB, rootDirectory string, event fsnotify.Event) {
  107. switch event.Op {
  108. case fsnotify.Remove:
  109. handleFileRemoveOrRename(l, db, rootDirectory, event)
  110. case fsnotify.Rename:
  111. handleFileRemoveOrRename(l, db, rootDirectory, event)
  112. case fsnotify.Create:
  113. handleFileCreateEvent(l, db, rootDirectory, event)
  114. case fsnotify.Write:
  115. waitUntilFileIsWritten(l, db, rootDirectory, event)
  116. }
  117. }
  118. func WatchLibraryRecursive(l *logger.Logger, rootDirectory string) {
  119. watcher, _ = fsnotify.NewWatcher()
  120. defer watcher.Close()
  121. if err := filepath.Walk(rootDirectory, watchDir); err != nil {
  122. l.Error("[WATCH] walk error: %s\n", err.Error())
  123. }
  124. db := database.GetConnection()
  125. done := make(chan bool)
  126. go func() {
  127. for {
  128. select {
  129. case event := <-watcher.Events:
  130. handleWatcherEvent(l, db, rootDirectory, event)
  131. case err := <-watcher.Errors:
  132. l.Error("[WATCH] error: %v\n", err)
  133. }
  134. }
  135. }()
  136. <-done
  137. }