scanner.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package read
  2. // Scan library directory all at once
  3. import (
  4. "github.com/felamaslen/gmus-backend/pkg/config"
  5. "github.com/felamaslen/gmus-backend/pkg/database"
  6. "github.com/felamaslen/gmus-backend/pkg/logger"
  7. "github.com/felamaslen/gmus-backend/pkg/repository"
  8. "github.com/felamaslen/gmus-backend/pkg/types"
  9. )
  10. func ScanDirectory(directory string) chan *types.File {
  11. db := database.GetConnection()
  12. l := logger.CreateLogger(config.GetConfig().LogLevel)
  13. filteredOutput := make(chan *types.File)
  14. allFiles := make(chan *types.File)
  15. go func() {
  16. batchFilterFiles(db, l, &filteredOutput, &allFiles, directory)
  17. }()
  18. go func() {
  19. recursiveDirScan(
  20. db,
  21. l,
  22. &allFiles,
  23. directory,
  24. "",
  25. true,
  26. )
  27. }()
  28. return filteredOutput
  29. }
  30. func UpsertSongsFromChannel(songs chan *types.Song) {
  31. var l = logger.CreateLogger(config.GetConfig().LogLevel)
  32. db := database.GetConnection()
  33. var batch [BATCH_SIZE]*types.Song
  34. var batchSize = 0
  35. var numAdded = 0
  36. var processBatch = func() {
  37. if batchSize == 0 {
  38. return
  39. }
  40. l.Debug("[INSERT] Processing batch\n")
  41. if err := repository.BatchUpsertSongs(db, &batch, batchSize); err != nil {
  42. panic(err)
  43. }
  44. l.Debug("[INSERT] Processed batch\n")
  45. batchSize = 0
  46. }
  47. for {
  48. select {
  49. case song, more := <-songs:
  50. if !more {
  51. processBatch()
  52. l.Verbose("[INSERT] Finished inserting %d songs\n", numAdded)
  53. return
  54. }
  55. batch[batchSize] = song
  56. batchSize++
  57. numAdded++
  58. if numAdded%LOG_EVERY == 0 {
  59. l.Verbose("[INSERT] Inserted %d\n", numAdded)
  60. }
  61. if batchSize >= BATCH_SIZE {
  62. processBatch()
  63. }
  64. }
  65. }
  66. }
  67. func ScanAndInsert(musicDirectory string) {
  68. var l = logger.CreateLogger(config.GetConfig().LogLevel)
  69. l.Info("Scanning directory for files...\n")
  70. files := ScanDirectory(musicDirectory)
  71. l.Info("Reading files...\n")
  72. songs := ReadMultipleFiles(musicDirectory, files)
  73. l.Info("Inserting data...\n")
  74. UpsertSongsFromChannel(songs)
  75. l.Info("Finished scan and insert\n")
  76. }