tool.go 9.4 KB

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