watcher.go 4.5 KB

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