files.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package read
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "path/filepath"
  6. )
  7. func ReadMultipleFiles(basePath string, files chan string) chan *Song {
  8. songs := make(chan *Song)
  9. go func() {
  10. defer close(songs)
  11. for {
  12. select {
  13. case file, more := <- files:
  14. if more {
  15. song, err := ReadFile(basePath, file)
  16. if err == nil {
  17. songs <- song
  18. } else {
  19. fmt.Printf("Error reading file (%s): %s\n", file, err)
  20. }
  21. } else {
  22. return
  23. }
  24. }
  25. }
  26. }()
  27. return songs
  28. }
  29. func isValidFile(file string) bool {
  30. // TODO: support FLAC/MP3
  31. return filepath.Ext(file) == ".ogg"
  32. }
  33. func recursiveDirScan(directory string, output chan string, root bool, basePath string) {
  34. files, err := ioutil.ReadDir(directory)
  35. if err != nil {
  36. fmt.Printf("Error scanning directory (%s): %s", directory, err)
  37. return
  38. }
  39. for _, file := range(files) {
  40. absolutePath := filepath.Join(directory, file.Name())
  41. relativePath := filepath.Join(basePath, file.Name())
  42. if file.IsDir() {
  43. recursiveDirScan(absolutePath, output, false, relativePath)
  44. } else if isValidFile(file.Name()) {
  45. output <- relativePath
  46. }
  47. }
  48. if (root) {
  49. close(output)
  50. }
  51. }
  52. func ScanDirectory(directory string) chan string {
  53. files := make(chan string)
  54. go func() {
  55. recursiveDirScan(directory, files, true, "")
  56. }()
  57. return files
  58. }