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

tool.go 13 kB

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