tool.go 11 KB

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