tool.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 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. "github.com/Unknwon/com"
  22. "github.com/Unknwon/i18n"
  23. "gitlab.com/gitote/chardet"
  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) > 10 {
  45. return sha1[:10]
  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. // 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. const TIME_LIMIT_CODE_LENGTH = 12 + 6 + 40
  131. // CreateTimeLimitCode generates a time limit code based on given input data.
  132. // Format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  133. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  134. format := "200601021504"
  135. var start, end time.Time
  136. var startStr, endStr string
  137. if startInf == nil {
  138. // Use now time create code
  139. start = time.Now()
  140. startStr = start.Format(format)
  141. } else {
  142. // use start string create code
  143. startStr = startInf.(string)
  144. start, _ = time.ParseInLocation(format, startStr, time.Local)
  145. startStr = start.Format(format)
  146. }
  147. end = start.Add(time.Minute * time.Duration(minutes))
  148. endStr = end.Format(format)
  149. // create sha1 encode string
  150. sh := sha1.New()
  151. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  152. encoded := hex.EncodeToString(sh.Sum(nil))
  153. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  154. return code
  155. }
  156. // HashEmail hashes email address to MD5 string.
  157. // https://en.gravatar.com/site/implement/hash/
  158. func HashEmail(email string) string {
  159. email = strings.ToLower(strings.TrimSpace(email))
  160. h := md5.New()
  161. h.Write([]byte(email))
  162. return hex.EncodeToString(h.Sum(nil))
  163. }
  164. // AvatarLink returns relative avatar link to the site domain by given email,
  165. // which includes app sub-url as prefix. However, it is possible
  166. // to return full URL if user enables Gravatar-like service.
  167. func AvatarLink(email string) (url string) {
  168. if setting.EnableFederatedAvatar && setting.LibravatarService != nil &&
  169. strings.Contains(email, "@") {
  170. var err error
  171. url, err = setting.LibravatarService.FromEmail(email)
  172. if err != nil {
  173. log.Warn("AvatarLink.LibravatarService.FromEmail [%s]: %v", email, err)
  174. }
  175. }
  176. if len(url) == 0 && !setting.DisableGravatar {
  177. url = setting.GravatarSource + HashEmail(email) + "?d=identicon"
  178. }
  179. if len(url) == 0 {
  180. url = "https://unpkg.com/gitote@1.0.1/img/avatar_default.png"
  181. }
  182. return url
  183. }
  184. // AppendAvatarSize appends avatar size query parameter to the URL in the correct format.
  185. func AppendAvatarSize(url string, size int) string {
  186. if strings.Contains(url, "?") {
  187. return url + "&s=" + com.ToStr(size)
  188. }
  189. return url + "?s=" + com.ToStr(size)
  190. }
  191. // Seconds-based time units
  192. const (
  193. Minute = 60
  194. Hour = 60 * Minute
  195. Day = 24 * Hour
  196. Week = 7 * Day
  197. Month = 30 * Day
  198. Year = 12 * Month
  199. )
  200. func computeTimeDiff(diff int64) (int64, string) {
  201. diffStr := ""
  202. switch {
  203. case diff <= 0:
  204. diff = 0
  205. diffStr = "now"
  206. case diff < 2:
  207. diff = 0
  208. diffStr = "1 second"
  209. case diff < 1*Minute:
  210. diffStr = fmt.Sprintf("%d seconds", diff)
  211. diff = 0
  212. case diff < 2*Minute:
  213. diff -= 1 * Minute
  214. diffStr = "1 minute"
  215. case diff < 1*Hour:
  216. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  217. diff -= diff / Minute * Minute
  218. case diff < 2*Hour:
  219. diff -= 1 * Hour
  220. diffStr = "1 hour"
  221. case diff < 1*Day:
  222. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  223. diff -= diff / Hour * Hour
  224. case diff < 2*Day:
  225. diff -= 1 * Day
  226. diffStr = "1 day"
  227. case diff < 1*Week:
  228. diffStr = fmt.Sprintf("%d days", diff/Day)
  229. diff -= diff / Day * Day
  230. case diff < 2*Week:
  231. diff -= 1 * Week
  232. diffStr = "1 week"
  233. case diff < 1*Month:
  234. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  235. diff -= diff / Week * Week
  236. case diff < 2*Month:
  237. diff -= 1 * Month
  238. diffStr = "1 month"
  239. case diff < 1*Year:
  240. diffStr = fmt.Sprintf("%d months", diff/Month)
  241. diff -= diff / Month * Month
  242. case diff < 2*Year:
  243. diff -= 1 * Year
  244. diffStr = "1 year"
  245. default:
  246. diffStr = fmt.Sprintf("%d years", diff/Year)
  247. diff = 0
  248. }
  249. return diff, diffStr
  250. }
  251. // TimeSincePro calculates the time interval and generate full user-friendly string.
  252. func TimeSincePro(then time.Time) string {
  253. now := time.Now()
  254. diff := now.Unix() - then.Unix()
  255. if then.After(now) {
  256. return "future"
  257. }
  258. var timeStr, diffStr string
  259. for {
  260. if diff == 0 {
  261. break
  262. }
  263. diff, diffStr = computeTimeDiff(diff)
  264. timeStr += ", " + diffStr
  265. }
  266. return strings.TrimPrefix(timeStr, ", ")
  267. }
  268. func timeSince(then time.Time, lang string) string {
  269. now := time.Now()
  270. lbl := i18n.Tr(lang, "tool.ago")
  271. diff := now.Unix() - then.Unix()
  272. if then.After(now) {
  273. lbl = i18n.Tr(lang, "tool.from_now")
  274. diff = then.Unix() - now.Unix()
  275. }
  276. switch {
  277. case diff <= 0:
  278. return i18n.Tr(lang, "tool.now")
  279. case diff <= 2:
  280. return i18n.Tr(lang, "tool.1s", lbl)
  281. case diff < 1*Minute:
  282. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  283. case diff < 2*Minute:
  284. return i18n.Tr(lang, "tool.1m", lbl)
  285. case diff < 1*Hour:
  286. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  287. case diff < 2*Hour:
  288. return i18n.Tr(lang, "tool.1h", lbl)
  289. case diff < 1*Day:
  290. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  291. case diff < 2*Day:
  292. return i18n.Tr(lang, "tool.1d", lbl)
  293. case diff < 1*Week:
  294. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  295. case diff < 2*Week:
  296. return i18n.Tr(lang, "tool.1w", lbl)
  297. case diff < 1*Month:
  298. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  299. case diff < 2*Month:
  300. return i18n.Tr(lang, "tool.1mon", lbl)
  301. case diff < 1*Year:
  302. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  303. case diff < 2*Year:
  304. return i18n.Tr(lang, "tool.1y", lbl)
  305. default:
  306. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  307. }
  308. }
  309. func RawTimeSince(t time.Time, lang string) string {
  310. return timeSince(t, lang)
  311. }
  312. // TimeSince calculates the time interval and generate user-friendly string.
  313. func TimeSince(t time.Time, lang string) template.HTML {
  314. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  315. }
  316. // Subtract deals with subtraction of all types of number.
  317. func Subtract(left interface{}, right interface{}) interface{} {
  318. var rleft, rright int64
  319. var fleft, fright float64
  320. var isInt bool = true
  321. switch left.(type) {
  322. case int:
  323. rleft = int64(left.(int))
  324. case int8:
  325. rleft = int64(left.(int8))
  326. case int16:
  327. rleft = int64(left.(int16))
  328. case int32:
  329. rleft = int64(left.(int32))
  330. case int64:
  331. rleft = left.(int64)
  332. case float32:
  333. fleft = float64(left.(float32))
  334. isInt = false
  335. case float64:
  336. fleft = left.(float64)
  337. isInt = false
  338. }
  339. switch right.(type) {
  340. case int:
  341. rright = int64(right.(int))
  342. case int8:
  343. rright = int64(right.(int8))
  344. case int16:
  345. rright = int64(right.(int16))
  346. case int32:
  347. rright = int64(right.(int32))
  348. case int64:
  349. rright = right.(int64)
  350. case float32:
  351. fright = float64(left.(float32))
  352. isInt = false
  353. case float64:
  354. fleft = left.(float64)
  355. isInt = false
  356. }
  357. if isInt {
  358. return rleft - rright
  359. } else {
  360. return fleft + float64(rleft) - (fright + float64(rright))
  361. }
  362. }
  363. // EllipsisString returns a truncated short string,
  364. // it appends '...' in the end of the length of string is too large.
  365. func EllipsisString(str string, length int) string {
  366. if len(str) < length {
  367. return str
  368. }
  369. return str[:length-3] + "..."
  370. }
  371. // TruncateString returns a truncated string with given limit,
  372. // it returns input string if length is not reached limit.
  373. func TruncateString(str string, limit int) string {
  374. if len(str) < limit {
  375. return str
  376. }
  377. return str[:limit]
  378. }
  379. // StringsToInt64s converts a slice of string to a slice of int64.
  380. func StringsToInt64s(strs []string) []int64 {
  381. ints := make([]int64, len(strs))
  382. for i := range strs {
  383. ints[i] = com.StrTo(strs[i]).MustInt64()
  384. }
  385. return ints
  386. }
  387. // Int64sToStrings converts a slice of int64 to a slice of string.
  388. func Int64sToStrings(ints []int64) []string {
  389. strs := make([]string, len(ints))
  390. for i := range ints {
  391. strs[i] = com.ToStr(ints[i])
  392. }
  393. return strs
  394. }
  395. // Int64sToMap converts a slice of int64 to a int64 map.
  396. func Int64sToMap(ints []int64) map[int64]bool {
  397. m := make(map[int64]bool)
  398. for _, i := range ints {
  399. m[i] = true
  400. }
  401. return m
  402. }
  403. // IsLetter reports whether the rune is a letter (category L).
  404. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  405. func IsLetter(ch rune) bool {
  406. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  407. }