tool.go 10.0 KB

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