files.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package read
  2. import (
  3. "io/ioutil"
  4. "path/filepath"
  5. config "github.com/felamaslen/go-music-player/pkg/config"
  6. "github.com/felamaslen/go-music-player/pkg/logger"
  7. )
  8. func ReadMultipleFiles(basePath string, files chan string) chan *Song {
  9. var l = logger.CreateLogger(config.GetConfig().LogLevel)
  10. songs := make(chan *Song)
  11. go func() {
  12. defer func() {
  13. l.Verbose("Finished reading files")
  14. close(songs)
  15. }()
  16. for {
  17. select {
  18. case file, more := <- files:
  19. if more {
  20. l.Verbose("Reading file: %s\n", file)
  21. song, err := ReadFile(basePath, file)
  22. if err == nil {
  23. songs <- song
  24. } else {
  25. l.Error("Error reading file (%s): %s\n", file, err)
  26. }
  27. } else {
  28. return
  29. }
  30. }
  31. }
  32. }()
  33. return songs
  34. }
  35. func isValidFile(file string) bool {
  36. // TODO: support FLAC/MP3
  37. return filepath.Ext(file) == ".ogg"
  38. }
  39. func recursiveDirScan(l *logger.Logger, directory string, output *chan string, root bool, basePath string) {
  40. if (root) {
  41. l.Verbose("Scanning root directory: %s\n", directory)
  42. defer func() {
  43. l.Verbose("Finished recursive directory scan")
  44. close(*output)
  45. }()
  46. } else {
  47. l.Debug("Scanning subdirectory: %s\n", directory)
  48. }
  49. files, err := ioutil.ReadDir(directory)
  50. if err != nil {
  51. l.Fatal("Error scanning directory: (%s): %s", directory, err)
  52. return
  53. }
  54. for _, file := range(files) {
  55. absolutePath := filepath.Join(directory, file.Name())
  56. relativePath := filepath.Join(basePath, file.Name())
  57. if file.IsDir() {
  58. recursiveDirScan(l, absolutePath, output, false, relativePath)
  59. } else if isValidFile(file.Name()) {
  60. l.Verbose("Found file: %s\n", relativePath)
  61. *output <- relativePath
  62. }
  63. }
  64. }
  65. func ScanDirectory(directory string) chan string {
  66. l := logger.CreateLogger(config.GetConfig().LogLevel)
  67. files := make(chan string)
  68. go func() {
  69. recursiveDirScan(l, directory, &files, true, "")
  70. }()
  71. return files
  72. }