scanner.go 1.6 KB

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