tool.go 12 KB

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