file.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // IsODMLFile returns true of the file has an odML header
  12. func IsODMLFile(data []byte) bool {
  13. if !IsTextFile(data) {
  14. return false
  15. }
  16. return strings.Contains(string(data), "<odML version=")
  17. }
  18. // IsTextFile returns true if file content format is plain text or empty.
  19. func IsTextFile(data []byte) bool {
  20. if len(data) == 0 {
  21. return true
  22. }
  23. return strings.Contains(http.DetectContentType(data), "text/")
  24. }
  25. func IsAnnexedFile(data []byte) bool {
  26. const ANNEXSNIFFSIZE = 5000
  27. if !(len(data) < ANNEXSNIFFSIZE) {
  28. data = data[:ANNEXSNIFFSIZE]
  29. }
  30. if strings.Contains(http.DetectContentType(data), "text/") {
  31. return strings.Contains(string(data), "/annex/objects")
  32. }
  33. return false
  34. }
  35. func IsImageFile(data []byte) bool {
  36. return strings.Contains(http.DetectContentType(data), "image/")
  37. }
  38. func IsPDFFile(data []byte) bool {
  39. return strings.Contains(http.DetectContentType(data), "application/pdf")
  40. }
  41. func IsVideoFile(data []byte) bool {
  42. return strings.Contains(http.DetectContentType(data), "video/")
  43. }
  44. const (
  45. Byte = 1
  46. KByte = Byte * 1024
  47. MByte = KByte * 1024
  48. GByte = MByte * 1024
  49. TByte = GByte * 1024
  50. PByte = TByte * 1024
  51. EByte = PByte * 1024
  52. )
  53. var bytesSizeTable = map[string]uint64{
  54. "b": Byte,
  55. "kb": KByte,
  56. "mb": MByte,
  57. "gb": GByte,
  58. "tb": TByte,
  59. "pb": PByte,
  60. "eb": EByte,
  61. }
  62. func logn(n, b float64) float64 {
  63. return math.Log(n) / math.Log(b)
  64. }
  65. func humanateBytes(s uint64, base float64, sizes []string) string {
  66. if s < 10 {
  67. return fmt.Sprintf("%d B", s)
  68. }
  69. e := math.Floor(logn(float64(s), base))
  70. suffix := sizes[int(e)]
  71. val := float64(s) / math.Pow(base, math.Floor(e))
  72. f := "%.0f"
  73. if val < 10 {
  74. f = "%.1f"
  75. }
  76. return fmt.Sprintf(f+" %s", val, suffix)
  77. }
  78. // FileSize calculates the file size and generate user-friendly string.
  79. func FileSize(s int64) string {
  80. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  81. return humanateBytes(uint64(s), 1024, sizes)
  82. }