file.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2017 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package tool
  5. import (
  6. "fmt"
  7. "math"
  8. "net/http"
  9. "strings"
  10. )
  11. func IsOdmlFile(data []byte) bool {
  12. if len(data) == 0 {
  13. return true
  14. }
  15. return strings.Contains(string(data), "<odML version=")
  16. }
  17. // IsTextFile returns true if file content format is plain text or empty.
  18. func IsTextFile(data []byte) bool {
  19. if len(data) == 0 {
  20. return true
  21. }
  22. return strings.Contains(http.DetectContentType(data), "text/")
  23. }
  24. func IsAnnexedFile(data []byte) bool {
  25. const ANNEXSNIFFSIZE = 5000
  26. if !(len(data) < ANNEXSNIFFSIZE) {
  27. data = data[:ANNEXSNIFFSIZE]
  28. }
  29. if strings.Contains(http.DetectContentType(data), "text/") {
  30. return strings.Contains(string(data), "/annex/objects")
  31. }
  32. return false
  33. }
  34. func IsImageFile(data []byte) bool {
  35. return strings.Contains(http.DetectContentType(data), "image/")
  36. }
  37. func IsPDFFile(data []byte) bool {
  38. return strings.Contains(http.DetectContentType(data), "application/pdf")
  39. }
  40. func IsVideoFile(data []byte) bool {
  41. return strings.Contains(http.DetectContentType(data), "video/")
  42. }
  43. const (
  44. Byte = 1
  45. KByte = Byte * 1024
  46. MByte = KByte * 1024
  47. GByte = MByte * 1024
  48. TByte = GByte * 1024
  49. PByte = TByte * 1024
  50. EByte = PByte * 1024
  51. )
  52. var bytesSizeTable = map[string]uint64{
  53. "b": Byte,
  54. "kb": KByte,
  55. "mb": MByte,
  56. "gb": GByte,
  57. "tb": TByte,
  58. "pb": PByte,
  59. "eb": EByte,
  60. }
  61. func logn(n, b float64) float64 {
  62. return math.Log(n) / math.Log(b)
  63. }
  64. func humanateBytes(s uint64, base float64, sizes []string) string {
  65. if s < 10 {
  66. return fmt.Sprintf("%d B", s)
  67. }
  68. e := math.Floor(logn(float64(s), base))
  69. suffix := sizes[int(e)]
  70. val := float64(s) / math.Pow(base, math.Floor(e))
  71. f := "%.0f"
  72. if val < 10 {
  73. f = "%.1f"
  74. }
  75. return fmt.Sprintf(f+" %s", val, suffix)
  76. }
  77. // FileSize calculates the file size and generate user-friendly string.
  78. func FileSize(s int64) string {
  79. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  80. return humanateBytes(uint64(s), 1024, sizes)
  81. }