files.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package movies
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. )
  9. type FileSource struct {
  10. ID string
  11. Files []string
  12. }
  13. func (fs *FileSource) Scan(root string) error {
  14. var files []string
  15. if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
  16. if err != nil {
  17. return err
  18. }
  19. if info.IsDir() {
  20. return nil
  21. }
  22. files = append(files, path)
  23. return nil
  24. }); err != nil {
  25. return fmt.Errorf("error while walking directory %q: %w", root, err)
  26. }
  27. fs.Files = files
  28. return nil
  29. }
  30. func (fs *FileSource) Search(query string) []string {
  31. if fs == nil {
  32. return nil
  33. }
  34. split := strings.Split(query, " ")
  35. var res []string
  36. for _, path := range fs.Files {
  37. if stringContainsAll(path, split) {
  38. res = append(res, path)
  39. }
  40. }
  41. return res
  42. }
  43. func stringContainsAll(path string, split []string) bool {
  44. path = strings.ToLower(path)
  45. for _, s := range split {
  46. if !strings.Contains(path, strings.ToLower(s)) {
  47. return false
  48. }
  49. }
  50. return true
  51. }
  52. func (fs *FileSource) Serve(w http.ResponseWriter, r *http.Request, file string) {
  53. http.ServeFile(w, r, file)
  54. }