tool.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 tool
  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/pkg/setting"
  23. )
  24. // MD5Bytes encodes string to MD5 bytes.
  25. func MD5Bytes(str string) []byte {
  26. m := md5.New()
  27. m.Write([]byte(str))
  28. return m.Sum(nil)
  29. }
  30. // EncodeMD5 encodes string to MD5 hex value.
  31. func EncodeMD5(str string) string {
  32. return hex.EncodeToString(MD5Bytes(str))
  33. }
  34. // Encode string to sha1 hex value.
  35. func EncodeSha1(str string) string {
  36. h := sha1.New()
  37. h.Write([]byte(str))
  38. return hex.EncodeToString(h.Sum(nil))
  39. }
  40. func ShortSha(sha1 string) string {
  41. if len(sha1) > 10 {
  42. return sha1[:10]
  43. }
  44. return sha1
  45. }
  46. func DetectEncoding(content []byte) (string, error) {
  47. if utf8.Valid(content) {
  48. log.Trace("Detected encoding: utf-8 (fast)")
  49. return "UTF-8", nil
  50. }
  51. result, err := chardet.NewTextDetector().DetectBest(content)
  52. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  53. log.Trace("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  54. return setting.Repository.AnsiCharset, err
  55. }
  56. log.Trace("Detected encoding: %s", result.Charset)
  57. return result.Charset, err
  58. }
  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. func BasicAuthEncode(username, password string) string {
  68. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  69. }
  70. // GetRandomString generate random string by specify chars.
  71. func GetRandomString(n int) (string, error) {
  72. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  73. buffer := make([]byte, n)
  74. max := big.NewInt(int64(len(alphanum)))
  75. for i := 0; i < n; i++ {
  76. index, err := randomInt(max)
  77. if err != nil {
  78. return "", err
  79. }
  80. buffer[i] = alphanum[index]
  81. }
  82. return string(buffer), nil
  83. }
  84. func randomInt(max *big.Int) (int, error) {
  85. rand, err := rand.Int(rand.Reader, max)
  86. if err != nil {
  87. return 0, err
  88. }
  89. return int(rand.Int64()), nil
  90. }
  91. // verify time limit code
  92. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  93. if len(code) <= 18 {
  94. return false
  95. }
  96. // split code
  97. start := code[:12]
  98. lives := code[12:18]
  99. if d, err := com.StrTo(lives).Int(); err == nil {
  100. minutes = d
  101. }
  102. // right active code
  103. retCode := CreateTimeLimitCode(data, minutes, start)
  104. if retCode == code && minutes > 0 {
  105. // check time is expired or not
  106. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  107. now := time.Now()
  108. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  109. return true
  110. }
  111. }
  112. return false
  113. }
  114. const TimeLimitCodeLength = 12 + 6 + 40
  115. // create a time limit code
  116. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  117. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  118. format := "200601021504"
  119. var start, end time.Time
  120. var startStr, endStr string
  121. if startInf == nil {
  122. // Use now time create code
  123. start = time.Now()
  124. startStr = start.Format(format)
  125. } else {
  126. // use start string create code
  127. startStr = startInf.(string)
  128. start, _ = time.ParseInLocation(format, startStr, time.Local)
  129. startStr = start.Format(format)
  130. }
  131. end = start.Add(time.Minute * time.Duration(minutes))
  132. endStr = end.Format(format)
  133. // create sha1 encode string
  134. sh := sha1.New()
  135. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  136. encoded := hex.EncodeToString(sh.Sum(nil))
  137. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  138. return code
  139. }
  140. // HashEmail hashes email address to MD5 string.
  141. // https://en.gravatar.com/site/implement/hash/
  142. func HashEmail(email string) string {
  143. email = strings.ToLower(strings.TrimSpace(email))
  144. h := md5.New()
  145. h.Write([]byte(email))
  146. return hex.EncodeToString(h.Sum(nil))
  147. }
  148. // AvatarLink returns relative avatar link to the site domain by given email,
  149. // which includes app sub-url as prefix. However, it is possible
  150. // to return full URL if user enables Gravatar-like service.
  151. func AvatarLink(email string) (url string) {
  152. if setting.EnableFederatedAvatar && setting.LibravatarService != nil &&
  153. strings.Contains(email, "@") {
  154. var err error
  155. url, err = setting.LibravatarService.FromEmail(email)
  156. if err != nil {
  157. log.Warn("AvatarLink.LibravatarService.FromEmail [%s]: %v", email, err)
  158. }
  159. }
  160. if len(url) == 0 && !setting.DisableGravatar {
  161. url = setting.GravatarSource + HashEmail(email)
  162. }
  163. if len(url) == 0 {
  164. url = setting.AppSubUrl + "/img/avatar_default.png"
  165. }
  166. return url
  167. }
  168. // Seconds-based time units
  169. const (
  170. Minute = 60
  171. Hour = 60 * Minute
  172. Day = 24 * Hour
  173. Week = 7 * Day
  174. Month = 30 * Day
  175. Year = 12 * Month
  176. )
  177. func computeTimeDiff(diff int64) (int64, string) {
  178. diffStr := ""
  179. switch {
  180. case diff <= 0:
  181. diff = 0
  182. diffStr = "now"
  183. case diff < 2:
  184. diff = 0
  185. diffStr = "1 second"
  186. case diff < 1*Minute:
  187. diffStr = fmt.Sprintf("%d seconds", diff)
  188. diff = 0
  189. case diff < 2*Minute:
  190. diff -= 1 * Minute
  191. diffStr = "1 minute"
  192. case diff < 1*Hour:
  193. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  194. diff -= diff / Minute * Minute
  195. case diff < 2*Hour:
  196. diff -= 1 * Hour
  197. diffStr = "1 hour"
  198. case diff < 1*Day:
  199. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  200. diff -= diff / Hour * Hour
  201. case diff < 2*Day:
  202. diff -= 1 * Day
  203. diffStr = "1 day"
  204. case diff < 1*Week:
  205. diffStr = fmt.Sprintf("%d days", diff/Day)
  206. diff -= diff / Day * Day
  207. case diff < 2*Week:
  208. diff -= 1 * Week
  209. diffStr = "1 week"
  210. case diff < 1*Month:
  211. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  212. diff -= diff / Week * Week
  213. case diff < 2*Month:
  214. diff -= 1 * Month
  215. diffStr = "1 month"
  216. case diff < 1*Year:
  217. diffStr = fmt.Sprintf("%d months", diff/Month)
  218. diff -= diff / Month * Month
  219. case diff < 2*Year:
  220. diff -= 1 * Year
  221. diffStr = "1 year"
  222. default:
  223. diffStr = fmt.Sprintf("%d years", diff/Year)
  224. diff = 0
  225. }
  226. return diff, diffStr
  227. }
  228. // TimeSincePro calculates the time interval and generate full user-friendly string.
  229. func TimeSincePro(then time.Time) string {
  230. now := time.Now()
  231. diff := now.Unix() - then.Unix()
  232. if then.After(now) {
  233. return "future"
  234. }
  235. var timeStr, diffStr string
  236. for {
  237. if diff == 0 {
  238. break
  239. }
  240. diff, diffStr = computeTimeDiff(diff)
  241. timeStr += ", " + diffStr
  242. }
  243. return strings.TrimPrefix(timeStr, ", ")
  244. }
  245. func timeSince(then time.Time, lang string) string {
  246. now := time.Now()
  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 <= 2:
  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. func RawTimeSince(t time.Time, lang string) string {
  287. return timeSince(t, lang)
  288. }
  289. // TimeSince calculates the time interval and generate user-friendly string.
  290. func TimeSince(t time.Time, lang string) template.HTML {
  291. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  292. }
  293. // Subtract deals with subtraction of all types of number.
  294. func Subtract(left interface{}, right interface{}) interface{} {
  295. var rleft, rright int64
  296. var fleft, fright float64
  297. var isInt bool = true
  298. switch left.(type) {
  299. case int:
  300. rleft = int64(left.(int))
  301. case int8:
  302. rleft = int64(left.(int8))
  303. case int16:
  304. rleft = int64(left.(int16))
  305. case int32:
  306. rleft = int64(left.(int32))
  307. case int64:
  308. rleft = left.(int64)
  309. case float32:
  310. fleft = float64(left.(float32))
  311. isInt = false
  312. case float64:
  313. fleft = left.(float64)
  314. isInt = false
  315. }
  316. switch right.(type) {
  317. case int:
  318. rright = int64(right.(int))
  319. case int8:
  320. rright = int64(right.(int8))
  321. case int16:
  322. rright = int64(right.(int16))
  323. case int32:
  324. rright = int64(right.(int32))
  325. case int64:
  326. rright = right.(int64)
  327. case float32:
  328. fright = float64(left.(float32))
  329. isInt = false
  330. case float64:
  331. fleft = left.(float64)
  332. isInt = false
  333. }
  334. if isInt {
  335. return rleft - rright
  336. } else {
  337. return fleft + float64(rleft) - (fright + float64(rright))
  338. }
  339. }
  340. // EllipsisString returns a truncated short string,
  341. // it appends '...' in the end of the length of string is too large.
  342. func EllipsisString(str string, length int) string {
  343. if len(str) < length {
  344. return str
  345. }
  346. return str[:length-3] + "..."
  347. }
  348. // TruncateString returns a truncated string with given limit,
  349. // it returns input string if length is not reached limit.
  350. func TruncateString(str string, limit int) string {
  351. if len(str) < limit {
  352. return str
  353. }
  354. return str[:limit]
  355. }
  356. // StringsToInt64s converts a slice of string to a slice of int64.
  357. func StringsToInt64s(strs []string) []int64 {
  358. ints := make([]int64, len(strs))
  359. for i := range strs {
  360. ints[i] = com.StrTo(strs[i]).MustInt64()
  361. }
  362. return ints
  363. }
  364. // Int64sToStrings converts a slice of int64 to a slice of string.
  365. func Int64sToStrings(ints []int64) []string {
  366. strs := make([]string, len(ints))
  367. for i := range ints {
  368. strs[i] = com.ToStr(ints[i])
  369. }
  370. return strs
  371. }
  372. // Int64sToMap converts a slice of int64 to a int64 map.
  373. func Int64sToMap(ints []int64) map[int64]bool {
  374. m := make(map[int64]bool)
  375. for _, i := range ints {
  376. m[i] = true
  377. }
  378. return m
  379. }
  380. // IsLetter reports whether the rune is a letter (category L).
  381. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  382. func IsLetter(ch rune) bool {
  383. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  384. }