tool.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 base
  5. import (
  6. "bytes"
  7. "crypto/md5"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "encoding/hex"
  11. "encoding/json"
  12. "fmt"
  13. "math"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. // Encode string to md5 hex value
  19. func EncodeMd5(str string) string {
  20. m := md5.New()
  21. m.Write([]byte(str))
  22. return hex.EncodeToString(m.Sum(nil))
  23. }
  24. // Random generate string
  25. func GetRandomString(n int) string {
  26. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  27. var bytes = make([]byte, n)
  28. rand.Read(bytes)
  29. for i, b := range bytes {
  30. bytes[i] = alphanum[b%byte(len(alphanum))]
  31. }
  32. return string(bytes)
  33. }
  34. // create a time limit code
  35. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  36. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  37. format := "YmdHi"
  38. var start, end time.Time
  39. var startStr, endStr string
  40. if startInf == nil {
  41. // Use now time create code
  42. start = time.Now()
  43. startStr = DateFormat(start, format)
  44. } else {
  45. // use start string create code
  46. startStr = startInf.(string)
  47. start, _ = DateParse(startStr, format)
  48. startStr = DateFormat(start, format)
  49. }
  50. end = start.Add(time.Minute * time.Duration(minutes))
  51. endStr = DateFormat(end, format)
  52. // create sha1 encode string
  53. sh := sha1.New()
  54. sh.Write([]byte(data + SecretKey + startStr + endStr + ToStr(minutes)))
  55. encoded := hex.EncodeToString(sh.Sum(nil))
  56. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  57. return code
  58. }
  59. // AvatarLink returns avatar link by given e-mail.
  60. func AvatarLink(email string) string {
  61. return "http://1.gravatar.com/avatar/" + EncodeMd5(email)
  62. }
  63. // Seconds-based time units
  64. const (
  65. Minute = 60
  66. Hour = 60 * Minute
  67. Day = 24 * Hour
  68. Week = 7 * Day
  69. Month = 30 * Day
  70. Year = 12 * Month
  71. )
  72. // TimeSince calculates the time interval and generate user-friendly string.
  73. func TimeSince(then time.Time) string {
  74. now := time.Now()
  75. lbl := "ago"
  76. diff := now.Unix() - then.Unix()
  77. if then.After(now) {
  78. lbl = "from now"
  79. diff = then.Unix() - now.Unix()
  80. }
  81. switch {
  82. case diff <= 0:
  83. return "now"
  84. case diff <= 2:
  85. return fmt.Sprintf("1 second %s", lbl)
  86. case diff < 1*Minute:
  87. return fmt.Sprintf("%d seconds %s", diff, lbl)
  88. case diff < 2*Minute:
  89. return fmt.Sprintf("1 minute %s", lbl)
  90. case diff < 1*Hour:
  91. return fmt.Sprintf("%d minutes %s", diff/Minute, lbl)
  92. case diff < 2*Hour:
  93. return fmt.Sprintf("1 hour %s", lbl)
  94. case diff < 1*Day:
  95. return fmt.Sprintf("%d hours %s", diff/Hour, lbl)
  96. case diff < 2*Day:
  97. return fmt.Sprintf("1 day %s", lbl)
  98. case diff < 1*Week:
  99. return fmt.Sprintf("%d days %s", diff/Day, lbl)
  100. case diff < 2*Week:
  101. return fmt.Sprintf("1 week %s", lbl)
  102. case diff < 1*Month:
  103. return fmt.Sprintf("%d weeks %s", diff/Week, lbl)
  104. case diff < 2*Month:
  105. return fmt.Sprintf("1 month %s", lbl)
  106. case diff < 1*Year:
  107. return fmt.Sprintf("%d months %s", diff/Month, lbl)
  108. case diff < 18*Month:
  109. return fmt.Sprintf("1 year %s", lbl)
  110. }
  111. return then.String()
  112. }
  113. const (
  114. Byte = 1
  115. KByte = Byte * 1024
  116. MByte = KByte * 1024
  117. GByte = MByte * 1024
  118. TByte = GByte * 1024
  119. PByte = TByte * 1024
  120. EByte = PByte * 1024
  121. )
  122. var bytesSizeTable = map[string]uint64{
  123. "b": Byte,
  124. "kb": KByte,
  125. "mb": MByte,
  126. "gb": GByte,
  127. "tb": TByte,
  128. "pb": PByte,
  129. "eb": EByte,
  130. }
  131. func logn(n, b float64) float64 {
  132. return math.Log(n) / math.Log(b)
  133. }
  134. func humanateBytes(s uint64, base float64, sizes []string) string {
  135. if s < 10 {
  136. return fmt.Sprintf("%dB", s)
  137. }
  138. e := math.Floor(logn(float64(s), base))
  139. suffix := sizes[int(e)]
  140. val := float64(s) / math.Pow(base, math.Floor(e))
  141. f := "%.0f"
  142. if val < 10 {
  143. f = "%.1f"
  144. }
  145. return fmt.Sprintf(f+"%s", val, suffix)
  146. }
  147. // FileSize calculates the file size and generate user-friendly string.
  148. func FileSize(s int64) string {
  149. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  150. return humanateBytes(uint64(s), 1024, sizes)
  151. }
  152. // Subtract deals with subtraction of all types of number.
  153. func Subtract(left interface{}, right interface{}) interface{} {
  154. var rleft, rright int64
  155. var fleft, fright float64
  156. var isInt bool = true
  157. switch left.(type) {
  158. case int:
  159. rleft = int64(left.(int))
  160. case int8:
  161. rleft = int64(left.(int8))
  162. case int16:
  163. rleft = int64(left.(int16))
  164. case int32:
  165. rleft = int64(left.(int32))
  166. case int64:
  167. rleft = left.(int64)
  168. case float32:
  169. fleft = float64(left.(float32))
  170. isInt = false
  171. case float64:
  172. fleft = left.(float64)
  173. isInt = false
  174. }
  175. switch right.(type) {
  176. case int:
  177. rright = int64(right.(int))
  178. case int8:
  179. rright = int64(right.(int8))
  180. case int16:
  181. rright = int64(right.(int16))
  182. case int32:
  183. rright = int64(right.(int32))
  184. case int64:
  185. rright = right.(int64)
  186. case float32:
  187. fright = float64(left.(float32))
  188. isInt = false
  189. case float64:
  190. fleft = left.(float64)
  191. isInt = false
  192. }
  193. if isInt {
  194. return rleft - rright
  195. } else {
  196. return fleft + float64(rleft) - (fright + float64(rright))
  197. }
  198. }
  199. // DateFormat pattern rules.
  200. var datePatterns = []string{
  201. // year
  202. "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  203. "y", "06", //A two digit representation of a year Examples: 99 or 03
  204. // month
  205. "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
  206. "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
  207. "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
  208. "F", "January", // A full textual representation of a month, such as January or March January through December
  209. // day
  210. "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
  211. "j", "2", // Day of the month without leading zeros 1 to 31
  212. // week
  213. "D", "Mon", // A textual representation of a day, three letters Mon through Sun
  214. "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
  215. // time
  216. "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
  217. "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
  218. "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
  219. "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
  220. "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
  221. "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
  222. "i", "04", // Minutes with leading zeros 00 to 59
  223. "s", "05", // Seconds, with leading zeros 00 through 59
  224. // time zone
  225. "T", "MST",
  226. "P", "-07:00",
  227. "O", "-0700",
  228. // RFC 2822
  229. "r", time.RFC1123Z,
  230. }
  231. // Parse Date use PHP time format.
  232. func DateParse(dateString, format string) (time.Time, error) {
  233. replacer := strings.NewReplacer(datePatterns...)
  234. format = replacer.Replace(format)
  235. return time.ParseInLocation(format, dateString, time.Local)
  236. }
  237. // Date takes a PHP like date func to Go's time format.
  238. func DateFormat(t time.Time, format string) string {
  239. replacer := strings.NewReplacer(datePatterns...)
  240. format = replacer.Replace(format)
  241. return t.Format(format)
  242. }
  243. type argInt []int
  244. func (a argInt) Get(i int, args ...int) (r int) {
  245. if i >= 0 && i < len(a) {
  246. r = a[i]
  247. }
  248. if len(args) > 0 {
  249. r = args[0]
  250. }
  251. return
  252. }
  253. // convert any type to string
  254. func ToStr(value interface{}, args ...int) (s string) {
  255. switch v := value.(type) {
  256. case bool:
  257. s = strconv.FormatBool(v)
  258. case float32:
  259. s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32))
  260. case float64:
  261. s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64))
  262. case int:
  263. s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
  264. case int8:
  265. s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
  266. case int16:
  267. s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
  268. case int32:
  269. s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
  270. case int64:
  271. s = strconv.FormatInt(v, argInt(args).Get(0, 10))
  272. case uint:
  273. s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
  274. case uint8:
  275. s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
  276. case uint16:
  277. s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
  278. case uint32:
  279. s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
  280. case uint64:
  281. s = strconv.FormatUint(v, argInt(args).Get(0, 10))
  282. case string:
  283. s = v
  284. case []byte:
  285. s = string(v)
  286. default:
  287. s = fmt.Sprintf("%v", v)
  288. }
  289. return s
  290. }
  291. type Actioner interface {
  292. GetOpType() int
  293. GetActUserName() string
  294. GetRepoName() string
  295. GetContent() string
  296. }
  297. // ActionIcon accepts a int that represents action operation type
  298. // and returns a icon class name.
  299. func ActionIcon(opType int) string {
  300. switch opType {
  301. case 1: // Create repository.
  302. return "plus-circle"
  303. case 5: // Commit repository.
  304. return "arrow-circle-o-right"
  305. default:
  306. return "invalid type"
  307. }
  308. }
  309. const (
  310. TPL_CREATE_REPO = `<a href="/user/%s">%s</a> created repository <a href="/%s/%s">%s</a>`
  311. TPL_COMMIT_REPO = `<a href="/user/%s">%s</a> pushed to <a href="/%s/%s/tree/%s">%s</a> at <a href="/%s/%s">%s/%s</a>%s`
  312. TPL_COMMIT_REPO_LI = `<div><img id="gogs-user-avatar-commit" src="%s?s=16" alt="user-avatar" title="username"/> <a href="/%s/%s/commit/%s">%s</a> %s</div>`
  313. )
  314. // ActionDesc accepts int that represents action operation type
  315. // and returns the description.
  316. func ActionDesc(act Actioner, avatarLink string) string {
  317. actUserName := act.GetActUserName()
  318. repoName := act.GetRepoName()
  319. content := act.GetContent()
  320. switch act.GetOpType() {
  321. case 1: // Create repository.
  322. return fmt.Sprintf(TPL_CREATE_REPO, actUserName, actUserName, actUserName, repoName, repoName)
  323. case 5: // Commit repository.
  324. var commits [][]string
  325. if err := json.Unmarshal([]byte(content), &commits); err != nil {
  326. return err.Error()
  327. }
  328. buf := bytes.NewBuffer([]byte("\n"))
  329. for _, commit := range commits {
  330. buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, avatarLink, actUserName, repoName, commit[0], commit[0][:7], commit[1]) + "\n")
  331. }
  332. return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, actUserName, repoName, "master", "master", actUserName, repoName, actUserName, repoName,
  333. buf.String())
  334. default:
  335. return "invalid type"
  336. }
  337. }