tool.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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/big"
  14. "strings"
  15. "time"
  16. "unicode"
  17. "unicode/utf8"
  18. "github.com/Unknwon/com"
  19. "github.com/Unknwon/i18n"
  20. log "gopkg.in/clog.v1"
  21. "github.com/gogits/chardet"
  22. "github.com/gogits/gogs/modules/setting"
  23. )
  24. // EncodeMD5 encodes string to md5 hex value.
  25. func EncodeMD5(str string) string {
  26. m := md5.New()
  27. m.Write([]byte(str))
  28. return hex.EncodeToString(m.Sum(nil))
  29. }
  30. // Encode string to sha1 hex value.
  31. func EncodeSha1(str string) string {
  32. h := sha1.New()
  33. h.Write([]byte(str))
  34. return hex.EncodeToString(h.Sum(nil))
  35. }
  36. func ShortSha(sha1 string) string {
  37. if len(sha1) > 10 {
  38. return sha1[:10]
  39. }
  40. return sha1
  41. }
  42. func DetectEncoding(content []byte) (string, error) {
  43. if utf8.Valid(content) {
  44. log.Trace("Detected encoding: utf-8 (fast)")
  45. return "UTF-8", nil
  46. }
  47. result, err := chardet.NewTextDetector().DetectBest(content)
  48. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  49. log.Trace("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  50. return setting.Repository.AnsiCharset, err
  51. }
  52. log.Trace("Detected encoding: %s", result.Charset)
  53. return result.Charset, err
  54. }
  55. func BasicAuthDecode(encoded string) (string, string, error) {
  56. s, err := base64.StdEncoding.DecodeString(encoded)
  57. if err != nil {
  58. return "", "", err
  59. }
  60. auth := strings.SplitN(string(s), ":", 2)
  61. return auth[0], auth[1], nil
  62. }
  63. func BasicAuthEncode(username, password string) string {
  64. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  65. }
  66. // GetRandomString generate random string by specify chars.
  67. func GetRandomString(n int) (string, error) {
  68. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  69. buffer := make([]byte, n)
  70. max := big.NewInt(int64(len(alphanum)))
  71. for i := 0; i < n; i++ {
  72. index, err := randomInt(max)
  73. if err != nil {
  74. return "", err
  75. }
  76. buffer[i] = alphanum[index]
  77. }
  78. return string(buffer), nil
  79. }
  80. func randomInt(max *big.Int) (int, error) {
  81. rand, err := rand.Int(rand.Reader, max)
  82. if err != nil {
  83. return 0, err
  84. }
  85. return int(rand.Int64()), nil
  86. }
  87. // verify time limit code
  88. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  89. if len(code) <= 18 {
  90. return false
  91. }
  92. // split code
  93. start := code[:12]
  94. lives := code[12:18]
  95. if d, err := com.StrTo(lives).Int(); err == nil {
  96. minutes = d
  97. }
  98. // right active code
  99. retCode := CreateTimeLimitCode(data, minutes, start)
  100. if retCode == code && minutes > 0 {
  101. // check time is expired or not
  102. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  103. now := time.Now()
  104. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  105. return true
  106. }
  107. }
  108. return false
  109. }
  110. const TimeLimitCodeLength = 12 + 6 + 40
  111. // create a time limit code
  112. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  113. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  114. format := "200601021504"
  115. var start, end time.Time
  116. var startStr, endStr string
  117. if startInf == nil {
  118. // Use now time create code
  119. start = time.Now()
  120. startStr = start.Format(format)
  121. } else {
  122. // use start string create code
  123. startStr = startInf.(string)
  124. start, _ = time.ParseInLocation(format, startStr, time.Local)
  125. startStr = start.Format(format)
  126. }
  127. end = start.Add(time.Minute * time.Duration(minutes))
  128. endStr = end.Format(format)
  129. // create sha1 encode string
  130. sh := sha1.New()
  131. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  132. encoded := hex.EncodeToString(sh.Sum(nil))
  133. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  134. return code
  135. }
  136. // HashEmail hashes email address to MD5 string.
  137. // https://en.gravatar.com/site/implement/hash/
  138. func HashEmail(email string) string {
  139. email = strings.ToLower(strings.TrimSpace(email))
  140. h := md5.New()
  141. h.Write([]byte(email))
  142. return hex.EncodeToString(h.Sum(nil))
  143. }
  144. // AvatarLink returns relative avatar link to the site domain by given email,
  145. // which includes app sub-url as prefix. However, it is possible
  146. // to return full URL if user enables Gravatar-like service.
  147. func AvatarLink(email string) (url string) {
  148. if setting.EnableFederatedAvatar && setting.LibravatarService != nil &&
  149. strings.Contains(email, "@") {
  150. var err error
  151. url, err = setting.LibravatarService.FromEmail(email)
  152. if err != nil {
  153. log.Warn("AvatarLink.LibravatarService.FromEmail [%s]: %v", email, err)
  154. }
  155. }
  156. if len(url) == 0 && !setting.DisableGravatar {
  157. url = setting.GravatarSource + HashEmail(email)
  158. }
  159. if len(url) == 0 {
  160. url = setting.AppSubUrl + "/img/avatar_default.png"
  161. }
  162. return url
  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 = 0
  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. now := time.Now()
  227. diff := now.Unix() - then.Unix()
  228. if then.After(now) {
  229. return "future"
  230. }
  231. var timeStr, diffStr string
  232. for {
  233. if diff == 0 {
  234. break
  235. }
  236. diff, diffStr = computeTimeDiff(diff)
  237. timeStr += ", " + diffStr
  238. }
  239. return strings.TrimPrefix(timeStr, ", ")
  240. }
  241. func timeSince(then time.Time, lang string) string {
  242. now := time.Now()
  243. lbl := i18n.Tr(lang, "tool.ago")
  244. diff := now.Unix() - then.Unix()
  245. if then.After(now) {
  246. lbl = i18n.Tr(lang, "tool.from_now")
  247. diff = then.Unix() - now.Unix()
  248. }
  249. switch {
  250. case diff <= 0:
  251. return i18n.Tr(lang, "tool.now")
  252. case diff <= 2:
  253. return i18n.Tr(lang, "tool.1s", lbl)
  254. case diff < 1*Minute:
  255. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  256. case diff < 2*Minute:
  257. return i18n.Tr(lang, "tool.1m", lbl)
  258. case diff < 1*Hour:
  259. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  260. case diff < 2*Hour:
  261. return i18n.Tr(lang, "tool.1h", lbl)
  262. case diff < 1*Day:
  263. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  264. case diff < 2*Day:
  265. return i18n.Tr(lang, "tool.1d", lbl)
  266. case diff < 1*Week:
  267. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  268. case diff < 2*Week:
  269. return i18n.Tr(lang, "tool.1w", lbl)
  270. case diff < 1*Month:
  271. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  272. case diff < 2*Month:
  273. return i18n.Tr(lang, "tool.1mon", lbl)
  274. case diff < 1*Year:
  275. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  276. case diff < 2*Year:
  277. return i18n.Tr(lang, "tool.1y", lbl)
  278. default:
  279. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  280. }
  281. }
  282. func RawTimeSince(t time.Time, lang string) string {
  283. return timeSince(t, lang)
  284. }
  285. // TimeSince calculates the time interval and generate user-friendly string.
  286. func TimeSince(t time.Time, lang string) template.HTML {
  287. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  288. }
  289. // Subtract deals with subtraction of all types of number.
  290. func Subtract(left interface{}, right interface{}) interface{} {
  291. var rleft, rright int64
  292. var fleft, fright float64
  293. var isInt bool = true
  294. switch left.(type) {
  295. case int:
  296. rleft = int64(left.(int))
  297. case int8:
  298. rleft = int64(left.(int8))
  299. case int16:
  300. rleft = int64(left.(int16))
  301. case int32:
  302. rleft = int64(left.(int32))
  303. case int64:
  304. rleft = left.(int64)
  305. case float32:
  306. fleft = float64(left.(float32))
  307. isInt = false
  308. case float64:
  309. fleft = left.(float64)
  310. isInt = false
  311. }
  312. switch right.(type) {
  313. case int:
  314. rright = int64(right.(int))
  315. case int8:
  316. rright = int64(right.(int8))
  317. case int16:
  318. rright = int64(right.(int16))
  319. case int32:
  320. rright = int64(right.(int32))
  321. case int64:
  322. rright = right.(int64)
  323. case float32:
  324. fright = float64(left.(float32))
  325. isInt = false
  326. case float64:
  327. fleft = left.(float64)
  328. isInt = false
  329. }
  330. if isInt {
  331. return rleft - rright
  332. } else {
  333. return fleft + float64(rleft) - (fright + float64(rright))
  334. }
  335. }
  336. // EllipsisString returns a truncated short string,
  337. // it appends '...' in the end of the length of string is too large.
  338. func EllipsisString(str string, length int) string {
  339. if len(str) < length {
  340. return str
  341. }
  342. return str[:length-3] + "..."
  343. }
  344. // TruncateString returns a truncated string with given limit,
  345. // it returns input string if length is not reached limit.
  346. func TruncateString(str string, limit int) string {
  347. if len(str) < limit {
  348. return str
  349. }
  350. return str[:limit]
  351. }
  352. // StringsToInt64s converts a slice of string to a slice of int64.
  353. func StringsToInt64s(strs []string) []int64 {
  354. ints := make([]int64, len(strs))
  355. for i := range strs {
  356. ints[i] = com.StrTo(strs[i]).MustInt64()
  357. }
  358. return ints
  359. }
  360. // Int64sToStrings converts a slice of int64 to a slice of string.
  361. func Int64sToStrings(ints []int64) []string {
  362. strs := make([]string, len(ints))
  363. for i := range ints {
  364. strs[i] = com.ToStr(ints[i])
  365. }
  366. return strs
  367. }
  368. // Int64sToMap converts a slice of int64 to a int64 map.
  369. func Int64sToMap(ints []int64) map[int64]bool {
  370. m := make(map[int64]bool)
  371. for _, i := range ints {
  372. m[i] = true
  373. }
  374. return m
  375. }
  376. // IsLetter reports whether the rune is a letter (category L).
  377. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  378. func IsLetter(ch rune) bool {
  379. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  380. }