files.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package read
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "path/filepath"
  6. )
  7. func ReadMultipleFiles(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(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) {
  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. relativePath := filepath.Join(directory, file.Name())
  41. if file.IsDir() {
  42. recursiveDirScan(relativePath, output, false)
  43. } else if isValidFile(file.Name()) {
  44. output <- relativePath
  45. }
  46. }
  47. if (root) {
  48. close(output)
  49. }
  50. }
  51. func ScanDirectory(directory string) chan string {
  52. files := make(chan string)
  53. go func() {
  54. recursiveDirScan(directory, files, true)
  55. }()
  56. return files
  57. }