選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

tool.go 12KB

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