tool.go 12 KB

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