file.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. func logn(n, b float64) float64 {
  45. return math.Log(n) / math.Log(b)
  46. }
  47. func humanateBytes(s uint64, base float64, sizes []string) string {
  48. if s < 10 {
  49. return fmt.Sprintf("%d B", s)
  50. }
  51. e := math.Floor(logn(float64(s), base))
  52. suffix := sizes[int(e)]
  53. val := float64(s) / math.Pow(base, math.Floor(e))
  54. f := "%.0f"
  55. if val < 10 {
  56. f = "%.1f"
  57. }
  58. return fmt.Sprintf(f+" %s", val, suffix)
  59. }
  60. // FileSize calculates the file size and generate user-friendly string.
  61. func FileSize(s int64) string {
  62. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  63. return humanateBytes(uint64(s), 1024, sizes)
  64. }