scanner.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package services
  2. import (
  3. "github.com/felamaslen/gmus-backend/pkg/config"
  4. "github.com/felamaslen/gmus-backend/pkg/database"
  5. "github.com/felamaslen/gmus-backend/pkg/logger"
  6. "github.com/felamaslen/gmus-backend/pkg/read"
  7. "github.com/felamaslen/gmus-backend/pkg/repository"
  8. )
  9. const LOG_EVERY = 100
  10. const BATCH_SIZE = 100
  11. func UpsertSongsFromChannel(songs chan *read.Song) {
  12. var l = logger.CreateLogger(config.GetConfig().LogLevel)
  13. db := database.GetConnection()
  14. var batch [BATCH_SIZE]*read.Song
  15. var batchSize = 0
  16. var numAdded = 0
  17. var processBatch = func() {
  18. if batchSize == 0 {
  19. return
  20. }
  21. l.Debug("[INSERT] Processing batch\n")
  22. if err := repository.BatchUpsertSongs(db, &batch, batchSize); err != nil {
  23. panic(err)
  24. }
  25. l.Debug("[INSERT] Processed batch\n")
  26. batchSize = 0
  27. }
  28. for {
  29. select {
  30. case song, more := <-songs:
  31. if !more {
  32. processBatch()
  33. l.Verbose("[INSERT] Finished inserting %d songs\n", numAdded)
  34. return
  35. }
  36. batch[batchSize] = song
  37. batchSize++
  38. numAdded++
  39. if numAdded%LOG_EVERY == 0 {
  40. l.Verbose("[INSERT] Inserted %d\n", numAdded)
  41. }
  42. if batchSize >= BATCH_SIZE {
  43. processBatch()
  44. }
  45. }
  46. }
  47. }
  48. func ScanAndInsert(musicDirectory string) {
  49. var l = logger.CreateLogger(config.GetConfig().LogLevel)
  50. l.Info("Scanning directory for files...\n")
  51. files := read.ScanDirectory(musicDirectory)
  52. l.Info("Reading files...\n")
  53. songs := read.ReadMultipleFiles(musicDirectory, files)
  54. l.Info("Inserting data...\n")
  55. UpsertSongsFromChannel(songs)
  56. l.Info("Finished scan and insert\n")
  57. }