tool.go 10 KB

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