file.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package utils
  2. import (
  3. "fmt"
  4. "github.com/h2non/filetype"
  5. "github.com/h2non/filetype/types"
  6. "strings"
  7. "sync"
  8. )
  9. type SourceType string
  10. const (
  11. Image SourceType = "image"
  12. Video SourceType = "video"
  13. Archive SourceType = "archive"
  14. Audio SourceType = "audio"
  15. Document SourceType = "document"
  16. )
  17. func CheckFileType(buf []byte, sourceType SourceType, exactFileType []string, fileExt string) bool {
  18. switch sourceType {
  19. case Document:
  20. kind, err := filetype.Document(buf)
  21. if err != nil {
  22. return false
  23. }
  24. return exactFile(exactFileType, kind, fileExt)
  25. case Image:
  26. kind, err := filetype.Image(buf)
  27. if err != nil {
  28. return false
  29. }
  30. return exactFile(exactFileType, kind, fileExt)
  31. case Video:
  32. kind, err := filetype.Video(buf)
  33. if err != nil {
  34. return false
  35. }
  36. return exactFile(exactFileType, kind, fileExt)
  37. case Audio:
  38. kind, err := filetype.Audio(buf)
  39. if err != nil {
  40. return false
  41. }
  42. return exactFile(exactFileType, kind, fileExt)
  43. case Archive:
  44. kind, err := filetype.Archive(buf)
  45. if err != nil {
  46. return false
  47. }
  48. return exactFile(exactFileType, kind, fileExt)
  49. default:
  50. return false
  51. }
  52. }
  53. func exactFile(exactFileType []string, fileKind types.Type, fileExt string) bool {
  54. lowCase := strings.ToLower(fileExt)
  55. for _, fileType := range exactFileType {
  56. if fileKind.Extension == fileType {
  57. if lowCase != "" && (lowCase == fmt.Sprintf(".%s", fileKind.Extension) || (lowCase == ".jpeg" && fileKind.Extension == "jpg")) {
  58. return true
  59. }
  60. return false
  61. }
  62. }
  63. return false
  64. }
  65. func IsValidType(buf []byte, sourceTypes []SourceType, exactFileType []string, fileExt string) bool {
  66. if len(sourceTypes) == 0 {
  67. return false
  68. }
  69. var wg sync.WaitGroup
  70. resultChan := make(chan bool, len(sourceTypes))
  71. for _, sourceType := range sourceTypes {
  72. wg.Add(1)
  73. go func(st SourceType) {
  74. defer wg.Done()
  75. resultChan <- CheckFileType(buf, st, exactFileType, fileExt)
  76. }(sourceType)
  77. }
  78. wg.Wait()
  79. close(resultChan)
  80. for result := range resultChan {
  81. if result {
  82. return true
  83. }
  84. }
  85. return false
  86. }