tool.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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.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 interface{}) 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. email = strings.ToLower(strings.TrimSpace(email))
  106. h := md5.New()
  107. _, _ = h.Write([]byte(email))
  108. return hex.EncodeToString(h.Sum(nil))
  109. }
  110. // AvatarLink returns relative avatar link to the site domain by given email,
  111. // which includes app sub-url as prefix. However, it is possible
  112. // to return full URL if user enables Gravatar-like service.
  113. func AvatarLink(email string) (url string) {
  114. if conf.Picture.EnableFederatedAvatar && conf.Picture.LibravatarService != nil &&
  115. strings.Contains(email, "@") {
  116. var err error
  117. url, err = conf.Picture.LibravatarService.FromEmail(email)
  118. if err != nil {
  119. log.Warn("AvatarLink.LibravatarService.FromEmail [%s]: %v", email, err)
  120. }
  121. }
  122. if len(url) == 0 && !conf.Picture.DisableGravatar {
  123. url = conf.Picture.GravatarSource + HashEmail(email) + "?d=identicon"
  124. }
  125. if len(url) == 0 {
  126. url = conf.Server.Subpath + "/img/avatar_default.png"
  127. }
  128. return url
  129. }
  130. // AppendAvatarSize appends avatar size query parameter to the URL in the correct format.
  131. func AppendAvatarSize(url string, size int) string {
  132. if strings.Contains(url, "?") {
  133. return url + "&s=" + com.ToStr(size)
  134. }
  135. return url + "?s=" + com.ToStr(size)
  136. }
  137. // Seconds-based time units
  138. const (
  139. Minute = 60
  140. Hour = 60 * Minute
  141. Day = 24 * Hour
  142. Week = 7 * Day
  143. Month = 30 * Day
  144. Year = 12 * Month
  145. )
  146. func computeTimeDiff(diff int64) (int64, string) {
  147. diffStr := ""
  148. switch {
  149. case diff <= 0:
  150. diff = 0
  151. diffStr = "now"
  152. case diff < 2:
  153. diff = 0
  154. diffStr = "1 second"
  155. case diff < 1*Minute:
  156. diffStr = fmt.Sprintf("%d seconds", diff)
  157. diff = 0
  158. case diff < 2*Minute:
  159. diff -= 1 * Minute
  160. diffStr = "1 minute"
  161. case diff < 1*Hour:
  162. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  163. diff -= diff / Minute * Minute
  164. case diff < 2*Hour:
  165. diff -= 1 * Hour
  166. diffStr = "1 hour"
  167. case diff < 1*Day:
  168. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  169. diff -= diff / Hour * Hour
  170. case diff < 2*Day:
  171. diff -= 1 * Day
  172. diffStr = "1 day"
  173. case diff < 1*Week:
  174. diffStr = fmt.Sprintf("%d days", diff/Day)
  175. diff -= diff / Day * Day
  176. case diff < 2*Week:
  177. diff -= 1 * Week
  178. diffStr = "1 week"
  179. case diff < 1*Month:
  180. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  181. diff -= diff / Week * Week
  182. case diff < 2*Month:
  183. diff -= 1 * Month
  184. diffStr = "1 month"
  185. case diff < 1*Year:
  186. diffStr = fmt.Sprintf("%d months", diff/Month)
  187. diff -= diff / Month * Month
  188. case diff < 2*Year:
  189. diff -= 1 * Year
  190. diffStr = "1 year"
  191. default:
  192. diffStr = fmt.Sprintf("%d years", diff/Year)
  193. diff = 0
  194. }
  195. return diff, diffStr
  196. }
  197. // TimeSincePro calculates the time interval and generate full user-friendly string.
  198. func TimeSincePro(then time.Time) string {
  199. now := time.Now()
  200. diff := now.Unix() - then.Unix()
  201. if then.After(now) {
  202. return "future"
  203. }
  204. var timeStr, diffStr string
  205. for {
  206. if diff == 0 {
  207. break
  208. }
  209. diff, diffStr = computeTimeDiff(diff)
  210. timeStr += ", " + diffStr
  211. }
  212. return strings.TrimPrefix(timeStr, ", ")
  213. }
  214. func timeSince(then time.Time, lang string) string {
  215. now := time.Now()
  216. lbl := i18n.Tr(lang, "tool.ago")
  217. diff := now.Unix() - then.Unix()
  218. if then.After(now) {
  219. lbl = i18n.Tr(lang, "tool.from_now")
  220. diff = then.Unix() - now.Unix()
  221. }
  222. switch {
  223. case diff <= 0:
  224. return i18n.Tr(lang, "tool.now")
  225. case diff <= 2:
  226. return i18n.Tr(lang, "tool.1s", lbl)
  227. case diff < 1*Minute:
  228. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  229. case diff < 2*Minute:
  230. return i18n.Tr(lang, "tool.1m", lbl)
  231. case diff < 1*Hour:
  232. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  233. case diff < 2*Hour:
  234. return i18n.Tr(lang, "tool.1h", lbl)
  235. case diff < 1*Day:
  236. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  237. case diff < 2*Day:
  238. return i18n.Tr(lang, "tool.1d", lbl)
  239. case diff < 1*Week:
  240. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  241. case diff < 2*Week:
  242. return i18n.Tr(lang, "tool.1w", lbl)
  243. case diff < 1*Month:
  244. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  245. case diff < 2*Month:
  246. return i18n.Tr(lang, "tool.1mon", lbl)
  247. case diff < 1*Year:
  248. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  249. case diff < 2*Year:
  250. return i18n.Tr(lang, "tool.1y", lbl)
  251. default:
  252. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  253. }
  254. }
  255. func RawTimeSince(t time.Time, lang string) string {
  256. return timeSince(t, lang)
  257. }
  258. // TimeSince calculates the time interval and generate user-friendly string.
  259. func TimeSince(t time.Time, lang string) template.HTML {
  260. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(conf.Time.FormatLayout), timeSince(t, lang)))
  261. }
  262. // Subtract deals with subtraction of all types of number.
  263. func Subtract(left interface{}, right interface{}) interface{} {
  264. var rleft, rright int64
  265. var fleft, fright float64
  266. var isInt = true
  267. switch left := left.(type) {
  268. case int:
  269. rleft = int64(left)
  270. case int8:
  271. rleft = int64(left)
  272. case int16:
  273. rleft = int64(left)
  274. case int32:
  275. rleft = int64(left)
  276. case int64:
  277. rleft = left
  278. case float32:
  279. fleft = float64(left)
  280. isInt = false
  281. case float64:
  282. fleft = left
  283. isInt = false
  284. }
  285. switch right := right.(type) {
  286. case int:
  287. rright = int64(right)
  288. case int8:
  289. rright = int64(right)
  290. case int16:
  291. rright = int64(right)
  292. case int32:
  293. rright = int64(right)
  294. case int64:
  295. rright = right
  296. case float32:
  297. fright = float64(left.(float32))
  298. isInt = false
  299. case float64:
  300. fleft = left.(float64)
  301. isInt = false
  302. }
  303. if isInt {
  304. return rleft - rright
  305. } else {
  306. return fleft + float64(rleft) - (fright + float64(rright))
  307. }
  308. }
  309. // EllipsisString returns a truncated short string,
  310. // it appends '...' in the end of the length of string is too large.
  311. func EllipsisString(str string, length int) string {
  312. if len(str) < length {
  313. return str
  314. }
  315. return str[:length-3] + "..."
  316. }
  317. // TruncateString returns a truncated string with given limit,
  318. // it returns input string if length is not reached limit.
  319. func TruncateString(str string, limit int) string {
  320. if len(str) < limit {
  321. return str
  322. }
  323. return str[:limit]
  324. }
  325. // StringsToInt64s converts a slice of string to a slice of int64.
  326. func StringsToInt64s(strs []string) []int64 {
  327. ints := make([]int64, len(strs))
  328. for i := range strs {
  329. ints[i] = com.StrTo(strs[i]).MustInt64()
  330. }
  331. return ints
  332. }
  333. // Int64sToStrings converts a slice of int64 to a slice of string.
  334. func Int64sToStrings(ints []int64) []string {
  335. strs := make([]string, len(ints))
  336. for i := range ints {
  337. strs[i] = com.ToStr(ints[i])
  338. }
  339. return strs
  340. }
  341. // Int64sToMap converts a slice of int64 to a int64 map.
  342. func Int64sToMap(ints []int64) map[int64]bool {
  343. m := make(map[int64]bool)
  344. for _, i := range ints {
  345. m[i] = true
  346. }
  347. return m
  348. }
  349. // IsLetter reports whether the rune is a letter (category L).
  350. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  351. func IsLetter(ch rune) bool {
  352. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  353. }