You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tool.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. // Copyright 2014 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 base
  5. import (
  6. "crypto/md5"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "html/template"
  13. "math"
  14. "net/http"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "unicode"
  19. "unicode/utf8"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/setting"
  22. "github.com/Unknwon/com"
  23. "github.com/Unknwon/i18n"
  24. "github.com/gogits/chardet"
  25. )
  26. // EncodeMD5 encodes string to md5 hex value.
  27. func EncodeMD5(str string) string {
  28. m := md5.New()
  29. m.Write([]byte(str))
  30. return hex.EncodeToString(m.Sum(nil))
  31. }
  32. // EncodeSha1 string to sha1 hex value.
  33. func EncodeSha1(str string) string {
  34. h := sha1.New()
  35. h.Write([]byte(str))
  36. return hex.EncodeToString(h.Sum(nil))
  37. }
  38. // ShortSha is basically just truncating.
  39. // It is DEPRECATED and will be removed in the future.
  40. func ShortSha(sha1 string) string {
  41. return TruncateString(sha1, 10)
  42. }
  43. // DetectEncoding detect the encoding of content
  44. func DetectEncoding(content []byte) (string, error) {
  45. if utf8.Valid(content) {
  46. log.Debug("Detected encoding: utf-8 (fast)")
  47. return "UTF-8", nil
  48. }
  49. result, err := chardet.NewTextDetector().DetectBest(content)
  50. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  51. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  52. return setting.Repository.AnsiCharset, err
  53. }
  54. log.Debug("Detected encoding: %s", result.Charset)
  55. return result.Charset, err
  56. }
  57. // BasicAuthDecode decode basic auth string
  58. func BasicAuthDecode(encoded string) (string, string, error) {
  59. s, err := base64.StdEncoding.DecodeString(encoded)
  60. if err != nil {
  61. return "", "", err
  62. }
  63. auth := strings.SplitN(string(s), ":", 2)
  64. return auth[0], auth[1], nil
  65. }
  66. // BasicAuthEncode encode basic auth string
  67. func BasicAuthEncode(username, password string) string {
  68. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  69. }
  70. // GetRandomString generate random string by specify chars.
  71. func GetRandomString(n int, alphabets ...byte) string {
  72. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  73. var bytes = make([]byte, n)
  74. rand.Read(bytes)
  75. for i, b := range bytes {
  76. if len(alphabets) == 0 {
  77. bytes[i] = alphanum[b%byte(len(alphanum))]
  78. } else {
  79. bytes[i] = alphabets[b%byte(len(alphabets))]
  80. }
  81. }
  82. return string(bytes)
  83. }
  84. // VerifyTimeLimitCode verify time limit code
  85. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  86. if len(code) <= 18 {
  87. return false
  88. }
  89. // split code
  90. start := code[:12]
  91. lives := code[12:18]
  92. if d, err := com.StrTo(lives).Int(); err == nil {
  93. minutes = d
  94. }
  95. // right active code
  96. retCode := CreateTimeLimitCode(data, minutes, start)
  97. if retCode == code && minutes > 0 {
  98. // check time is expired or not
  99. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  100. now := time.Now()
  101. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  102. return true
  103. }
  104. }
  105. return false
  106. }
  107. // TimeLimitCodeLength default value for time limit code
  108. const TimeLimitCodeLength = 12 + 6 + 40
  109. // CreateTimeLimitCode create a time limit code
  110. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  111. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  112. format := "200601021504"
  113. var start, end time.Time
  114. var startStr, endStr string
  115. if startInf == nil {
  116. // Use now time create code
  117. start = time.Now()
  118. startStr = start.Format(format)
  119. } else {
  120. // use start string create code
  121. startStr = startInf.(string)
  122. start, _ = time.ParseInLocation(format, startStr, time.Local)
  123. startStr = start.Format(format)
  124. }
  125. end = start.Add(time.Minute * time.Duration(minutes))
  126. endStr = end.Format(format)
  127. // create sha1 encode string
  128. sh := sha1.New()
  129. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  130. encoded := hex.EncodeToString(sh.Sum(nil))
  131. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  132. return code
  133. }
  134. // HashEmail hashes email address to MD5 string.
  135. // https://en.gravatar.com/site/implement/hash/
  136. func HashEmail(email string) string {
  137. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  138. }
  139. // AvatarLink returns relative avatar link to the site domain by given email,
  140. // which includes app sub-url as prefix. However, it is possible
  141. // to return full URL if user enables Gravatar-like service.
  142. func AvatarLink(email string) string {
  143. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  144. // TODO: This doesn't check any error. AvatarLink should return (string, error)
  145. url, _ := setting.LibravatarService.FromEmail(email)
  146. return url
  147. }
  148. if !setting.DisableGravatar {
  149. return setting.GravatarSource + HashEmail(email)
  150. }
  151. return setting.AppSubURL + "/img/avatar_default.png"
  152. }
  153. // Seconds-based time units
  154. const (
  155. Minute = 60
  156. Hour = 60 * Minute
  157. Day = 24 * Hour
  158. Week = 7 * Day
  159. Month = 30 * Day
  160. Year = 12 * Month
  161. )
  162. func computeTimeDiff(diff int64) (int64, string) {
  163. diffStr := ""
  164. switch {
  165. case diff <= 0:
  166. diff = 0
  167. diffStr = "now"
  168. case diff < 2:
  169. diff = 0
  170. diffStr = "1 second"
  171. case diff < 1*Minute:
  172. diffStr = fmt.Sprintf("%d seconds", diff)
  173. diff = 0
  174. case diff < 2*Minute:
  175. diff -= 1 * Minute
  176. diffStr = "1 minute"
  177. case diff < 1*Hour:
  178. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  179. diff -= diff / Minute * Minute
  180. case diff < 2*Hour:
  181. diff -= 1 * Hour
  182. diffStr = "1 hour"
  183. case diff < 1*Day:
  184. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  185. diff -= diff / Hour * Hour
  186. case diff < 2*Day:
  187. diff -= 1 * Day
  188. diffStr = "1 day"
  189. case diff < 1*Week:
  190. diffStr = fmt.Sprintf("%d days", diff/Day)
  191. diff -= diff / Day * Day
  192. case diff < 2*Week:
  193. diff -= 1 * Week
  194. diffStr = "1 week"
  195. case diff < 1*Month:
  196. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  197. diff -= diff / Week * Week
  198. case diff < 2*Month:
  199. diff -= 1 * Month
  200. diffStr = "1 month"
  201. case diff < 1*Year:
  202. diffStr = fmt.Sprintf("%d months", diff/Month)
  203. diff -= diff / Month * Month
  204. case diff < 2*Year:
  205. diff -= 1 * Year
  206. diffStr = "1 year"
  207. default:
  208. diffStr = fmt.Sprintf("%d years", diff/Year)
  209. diff = 0
  210. }
  211. return diff, diffStr
  212. }
  213. // TimeSincePro calculates the time interval and generate full user-friendly string.
  214. func TimeSincePro(then time.Time) string {
  215. now := time.Now()
  216. diff := now.Unix() - then.Unix()
  217. if then.After(now) {
  218. return "future"
  219. }
  220. var timeStr, diffStr string
  221. for {
  222. if diff == 0 {
  223. break
  224. }
  225. diff, diffStr = computeTimeDiff(diff)
  226. timeStr += ", " + diffStr
  227. }
  228. return strings.TrimPrefix(timeStr, ", ")
  229. }
  230. func timeSince(then time.Time, lang string) string {
  231. now := time.Now()
  232. lbl := i18n.Tr(lang, "tool.ago")
  233. diff := now.Unix() - then.Unix()
  234. if then.After(now) {
  235. lbl = i18n.Tr(lang, "tool.from_now")
  236. diff = then.Unix() - now.Unix()
  237. }
  238. switch {
  239. case diff <= 0:
  240. return i18n.Tr(lang, "tool.now")
  241. case diff <= 2:
  242. return i18n.Tr(lang, "tool.1s", lbl)
  243. case diff < 1*Minute:
  244. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  245. case diff < 2*Minute:
  246. return i18n.Tr(lang, "tool.1m", lbl)
  247. case diff < 1*Hour:
  248. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  249. case diff < 2*Hour:
  250. return i18n.Tr(lang, "tool.1h", lbl)
  251. case diff < 1*Day:
  252. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  253. case diff < 2*Day:
  254. return i18n.Tr(lang, "tool.1d", lbl)
  255. case diff < 1*Week:
  256. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  257. case diff < 2*Week:
  258. return i18n.Tr(lang, "tool.1w", lbl)
  259. case diff < 1*Month:
  260. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  261. case diff < 2*Month:
  262. return i18n.Tr(lang, "tool.1mon", lbl)
  263. case diff < 1*Year:
  264. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  265. case diff < 2*Year:
  266. return i18n.Tr(lang, "tool.1y", lbl)
  267. default:
  268. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  269. }
  270. }
  271. // RawTimeSince retrieves i18n key of time since t
  272. func RawTimeSince(t time.Time, lang string) string {
  273. return timeSince(t, lang)
  274. }
  275. // TimeSince calculates the time interval and generate user-friendly string.
  276. func TimeSince(t time.Time, lang string) template.HTML {
  277. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  278. }
  279. // Storage space size types
  280. const (
  281. Byte = 1
  282. KByte = Byte * 1024
  283. MByte = KByte * 1024
  284. GByte = MByte * 1024
  285. TByte = GByte * 1024
  286. PByte = TByte * 1024
  287. EByte = PByte * 1024
  288. )
  289. var bytesSizeTable = map[string]uint64{
  290. "b": Byte,
  291. "kb": KByte,
  292. "mb": MByte,
  293. "gb": GByte,
  294. "tb": TByte,
  295. "pb": PByte,
  296. "eb": EByte,
  297. }
  298. func logn(n, b float64) float64 {
  299. return math.Log(n) / math.Log(b)
  300. }
  301. func humanateBytes(s uint64, base float64, sizes []string) string {
  302. if s < 10 {
  303. return fmt.Sprintf("%dB", s)
  304. }
  305. e := math.Floor(logn(float64(s), base))
  306. suffix := sizes[int(e)]
  307. val := float64(s) / math.Pow(base, math.Floor(e))
  308. f := "%.0f"
  309. if val < 10 {
  310. f = "%.1f"
  311. }
  312. return fmt.Sprintf(f+"%s", val, suffix)
  313. }
  314. // FileSize calculates the file size and generate user-friendly string.
  315. func FileSize(s int64) string {
  316. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  317. return humanateBytes(uint64(s), 1024, sizes)
  318. }
  319. // Subtract deals with subtraction of all types of number.
  320. func Subtract(left interface{}, right interface{}) interface{} {
  321. var rleft, rright int64
  322. var fleft, fright float64
  323. var isInt = true
  324. switch left.(type) {
  325. case int:
  326. rleft = int64(left.(int))
  327. case int8:
  328. rleft = int64(left.(int8))
  329. case int16:
  330. rleft = int64(left.(int16))
  331. case int32:
  332. rleft = int64(left.(int32))
  333. case int64:
  334. rleft = left.(int64)
  335. case float32:
  336. fleft = float64(left.(float32))
  337. isInt = false
  338. case float64:
  339. fleft = left.(float64)
  340. isInt = false
  341. }
  342. switch right.(type) {
  343. case int:
  344. rright = int64(right.(int))
  345. case int8:
  346. rright = int64(right.(int8))
  347. case int16:
  348. rright = int64(right.(int16))
  349. case int32:
  350. rright = int64(right.(int32))
  351. case int64:
  352. rright = right.(int64)
  353. case float32:
  354. fright = float64(left.(float32))
  355. isInt = false
  356. case float64:
  357. fleft = left.(float64)
  358. isInt = false
  359. }
  360. if isInt {
  361. return rleft - rright
  362. }
  363. return fleft + float64(rleft) - (fright + float64(rright))
  364. }
  365. // EllipsisString returns a truncated short string,
  366. // it appends '...' in the end of the length of string is too large.
  367. func EllipsisString(str string, length int) string {
  368. if length <= 3 {
  369. return "..."
  370. }
  371. if len(str) <= length {
  372. return str
  373. }
  374. return str[:length-3] + "..."
  375. }
  376. // TruncateString returns a truncated string with given limit,
  377. // it returns input string if length is not reached limit.
  378. func TruncateString(str string, limit int) string {
  379. if len(str) < limit {
  380. return str
  381. }
  382. return str[:limit]
  383. }
  384. // StringsToInt64s converts a slice of string to a slice of int64.
  385. func StringsToInt64s(strs []string) []int64 {
  386. ints := make([]int64, len(strs))
  387. for i := range strs {
  388. ints[i] = com.StrTo(strs[i]).MustInt64()
  389. }
  390. return ints
  391. }
  392. // Int64sToStrings converts a slice of int64 to a slice of string.
  393. func Int64sToStrings(ints []int64) []string {
  394. strs := make([]string, len(ints))
  395. for i := range ints {
  396. strs[i] = strconv.FormatInt(ints[i], 10)
  397. }
  398. return strs
  399. }
  400. // Int64sToMap converts a slice of int64 to a int64 map.
  401. func Int64sToMap(ints []int64) map[int64]bool {
  402. m := make(map[int64]bool)
  403. for _, i := range ints {
  404. m[i] = true
  405. }
  406. return m
  407. }
  408. // IsLetter reports whether the rune is a letter (category L).
  409. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  410. func IsLetter(ch rune) bool {
  411. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  412. }
  413. // IsTextFile returns true if file content format is plain text or empty.
  414. func IsTextFile(data []byte) bool {
  415. if len(data) == 0 {
  416. return true
  417. }
  418. return strings.Index(http.DetectContentType(data), "text/") != -1
  419. }
  420. // IsImageFile detectes if data is an image format
  421. func IsImageFile(data []byte) bool {
  422. return strings.Index(http.DetectContentType(data), "image/") != -1
  423. }
  424. // IsPDFFile detectes if data is a pdf format
  425. func IsPDFFile(data []byte) bool {
  426. return strings.Index(http.DetectContentType(data), "application/pdf") != -1
  427. }
  428. // IsVideoFile detectes if data is an video format
  429. func IsVideoFile(data []byte) bool {
  430. return strings.Index(http.DetectContentType(data), "video/") != -1
  431. }