Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

tool.go 14KB

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