tool.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. // verify time limit code
  35. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  36. if len(code) <= 18 {
  37. return false
  38. }
  39. // split code
  40. start := code[:12]
  41. lives := code[12:18]
  42. if d, err := StrTo(lives).Int(); err == nil {
  43. minutes = d
  44. }
  45. // right active code
  46. retCode := CreateTimeLimitCode(data, minutes, start)
  47. if retCode == code && minutes > 0 {
  48. // check time is expired or not
  49. before, _ := DateParse(start, "YmdHi")
  50. now := time.Now()
  51. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  52. return true
  53. }
  54. }
  55. return false
  56. }
  57. const TimeLimitCodeLength = 12 + 6 + 40
  58. // create a time limit code
  59. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  60. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  61. format := "YmdHi"
  62. var start, end time.Time
  63. var startStr, endStr string
  64. if startInf == nil {
  65. // Use now time create code
  66. start = time.Now()
  67. startStr = DateFormat(start, format)
  68. } else {
  69. // use start string create code
  70. startStr = startInf.(string)
  71. start, _ = DateParse(startStr, format)
  72. startStr = DateFormat(start, format)
  73. }
  74. end = start.Add(time.Minute * time.Duration(minutes))
  75. endStr = DateFormat(end, format)
  76. // create sha1 encode string
  77. sh := sha1.New()
  78. sh.Write([]byte(data + SecretKey + startStr + endStr + ToStr(minutes)))
  79. encoded := hex.EncodeToString(sh.Sum(nil))
  80. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  81. return code
  82. }
  83. // AvatarLink returns avatar link by given e-mail.
  84. func AvatarLink(email string) string {
  85. return "http://1.gravatar.com/avatar/" + EncodeMd5(email)
  86. }
  87. // Seconds-based time units
  88. const (
  89. Minute = 60
  90. Hour = 60 * Minute
  91. Day = 24 * Hour
  92. Week = 7 * Day
  93. Month = 30 * Day
  94. Year = 12 * Month
  95. )
  96. func computeTimeDiff(diff int64) (int64, string) {
  97. diffStr := ""
  98. switch {
  99. case diff <= 0:
  100. diff = 0
  101. diffStr = "now"
  102. case diff < 2:
  103. diff = 0
  104. diffStr = "1 second"
  105. case diff < 1*Minute:
  106. diffStr = fmt.Sprintf("%d seconds", diff)
  107. diff = 0
  108. case diff < 2*Minute:
  109. diff -= 1 * Minute
  110. diffStr = "1 minute"
  111. case diff < 1*Hour:
  112. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  113. diff -= diff / Minute * Minute
  114. case diff < 2*Hour:
  115. diff -= 1 * Hour
  116. diffStr = "1 hour"
  117. case diff < 1*Day:
  118. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  119. diff -= diff / Hour * Hour
  120. case diff < 2*Day:
  121. diff -= 1 * Day
  122. diffStr = "1 day"
  123. case diff < 1*Week:
  124. diffStr = fmt.Sprintf("%d days", diff/Day)
  125. diff -= diff / Day * Day
  126. case diff < 2*Week:
  127. diff -= 1 * Week
  128. diffStr = "1 week"
  129. case diff < 1*Month:
  130. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  131. diff -= diff / Week * Week
  132. case diff < 2*Month:
  133. diff -= 1 * Month
  134. diffStr = "1 month"
  135. case diff < 1*Year:
  136. diffStr = fmt.Sprintf("%d months", diff/Month)
  137. diff -= diff / Month * Month
  138. case diff < 2*Year:
  139. diff -= 1 * Year
  140. diffStr = "1 year"
  141. default:
  142. diffStr = fmt.Sprintf("%d years", diff/Year)
  143. diff = 0
  144. }
  145. return diff, diffStr
  146. }
  147. // TimeSincePro calculates the time interval and generate full user-friendly string.
  148. func TimeSincePro(then time.Time) string {
  149. now := time.Now()
  150. diff := now.Unix() - then.Unix()
  151. if then.After(now) {
  152. return "future"
  153. }
  154. var timeStr, diffStr string
  155. for {
  156. if diff == 0 {
  157. break
  158. }
  159. diff, diffStr = computeTimeDiff(diff)
  160. timeStr += ", " + diffStr
  161. }
  162. return strings.TrimPrefix(timeStr, ", ")
  163. }
  164. // TimeSince calculates the time interval and generate user-friendly string.
  165. func TimeSince(then time.Time) string {
  166. now := time.Now()
  167. lbl := "ago"
  168. diff := now.Unix() - then.Unix()
  169. if then.After(now) {
  170. lbl = "from now"
  171. diff = then.Unix() - now.Unix()
  172. }
  173. switch {
  174. case diff <= 0:
  175. return "now"
  176. case diff <= 2:
  177. return fmt.Sprintf("1 second %s", lbl)
  178. case diff < 1*Minute:
  179. return fmt.Sprintf("%d seconds %s", diff, lbl)
  180. case diff < 2*Minute:
  181. return fmt.Sprintf("1 minute %s", lbl)
  182. case diff < 1*Hour:
  183. return fmt.Sprintf("%d minutes %s", diff/Minute, lbl)
  184. case diff < 2*Hour:
  185. return fmt.Sprintf("1 hour %s", lbl)
  186. case diff < 1*Day:
  187. return fmt.Sprintf("%d hours %s", diff/Hour, lbl)
  188. case diff < 2*Day:
  189. return fmt.Sprintf("1 day %s", lbl)
  190. case diff < 1*Week:
  191. return fmt.Sprintf("%d days %s", diff/Day, lbl)
  192. case diff < 2*Week:
  193. return fmt.Sprintf("1 week %s", lbl)
  194. case diff < 1*Month:
  195. return fmt.Sprintf("%d weeks %s", diff/Week, lbl)
  196. case diff < 2*Month:
  197. return fmt.Sprintf("1 month %s", lbl)
  198. case diff < 1*Year:
  199. return fmt.Sprintf("%d months %s", diff/Month, lbl)
  200. case diff < 2*Year:
  201. return fmt.Sprintf("1 year %s", lbl)
  202. default:
  203. return fmt.Sprintf("%d years %s", diff/Year, lbl)
  204. }
  205. return then.String()
  206. }
  207. const (
  208. Byte = 1
  209. KByte = Byte * 1024
  210. MByte = KByte * 1024
  211. GByte = MByte * 1024
  212. TByte = GByte * 1024
  213. PByte = TByte * 1024
  214. EByte = PByte * 1024
  215. )
  216. var bytesSizeTable = map[string]uint64{
  217. "b": Byte,
  218. "kb": KByte,
  219. "mb": MByte,
  220. "gb": GByte,
  221. "tb": TByte,
  222. "pb": PByte,
  223. "eb": EByte,
  224. }
  225. func logn(n, b float64) float64 {
  226. return math.Log(n) / math.Log(b)
  227. }
  228. func humanateBytes(s uint64, base float64, sizes []string) string {
  229. if s < 10 {
  230. return fmt.Sprintf("%dB", s)
  231. }
  232. e := math.Floor(logn(float64(s), base))
  233. suffix := sizes[int(e)]
  234. val := float64(s) / math.Pow(base, math.Floor(e))
  235. f := "%.0f"
  236. if val < 10 {
  237. f = "%.1f"
  238. }
  239. return fmt.Sprintf(f+"%s", val, suffix)
  240. }
  241. // FileSize calculates the file size and generate user-friendly string.
  242. func FileSize(s int64) string {
  243. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  244. return humanateBytes(uint64(s), 1024, sizes)
  245. }
  246. // Subtract deals with subtraction of all types of number.
  247. func Subtract(left interface{}, right interface{}) interface{} {
  248. var rleft, rright int64
  249. var fleft, fright float64
  250. var isInt bool = true
  251. switch left.(type) {
  252. case int:
  253. rleft = int64(left.(int))
  254. case int8:
  255. rleft = int64(left.(int8))
  256. case int16:
  257. rleft = int64(left.(int16))
  258. case int32:
  259. rleft = int64(left.(int32))
  260. case int64:
  261. rleft = left.(int64)
  262. case float32:
  263. fleft = float64(left.(float32))
  264. isInt = false
  265. case float64:
  266. fleft = left.(float64)
  267. isInt = false
  268. }
  269. switch right.(type) {
  270. case int:
  271. rright = int64(right.(int))
  272. case int8:
  273. rright = int64(right.(int8))
  274. case int16:
  275. rright = int64(right.(int16))
  276. case int32:
  277. rright = int64(right.(int32))
  278. case int64:
  279. rright = right.(int64)
  280. case float32:
  281. fright = float64(left.(float32))
  282. isInt = false
  283. case float64:
  284. fleft = left.(float64)
  285. isInt = false
  286. }
  287. if isInt {
  288. return rleft - rright
  289. } else {
  290. return fleft + float64(rleft) - (fright + float64(rright))
  291. }
  292. }
  293. // DateFormat pattern rules.
  294. var datePatterns = []string{
  295. // year
  296. "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  297. "y", "06", //A two digit representation of a year Examples: 99 or 03
  298. // month
  299. "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
  300. "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
  301. "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
  302. "F", "January", // A full textual representation of a month, such as January or March January through December
  303. // day
  304. "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
  305. "j", "2", // Day of the month without leading zeros 1 to 31
  306. // week
  307. "D", "Mon", // A textual representation of a day, three letters Mon through Sun
  308. "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
  309. // time
  310. "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
  311. "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
  312. "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
  313. "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
  314. "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
  315. "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
  316. "i", "04", // Minutes with leading zeros 00 to 59
  317. "s", "05", // Seconds, with leading zeros 00 through 59
  318. // time zone
  319. "T", "MST",
  320. "P", "-07:00",
  321. "O", "-0700",
  322. // RFC 2822
  323. "r", time.RFC1123Z,
  324. }
  325. // Parse Date use PHP time format.
  326. func DateParse(dateString, format string) (time.Time, error) {
  327. replacer := strings.NewReplacer(datePatterns...)
  328. format = replacer.Replace(format)
  329. return time.ParseInLocation(format, dateString, time.Local)
  330. }
  331. // Date takes a PHP like date func to Go's time format.
  332. func DateFormat(t time.Time, format string) string {
  333. replacer := strings.NewReplacer(datePatterns...)
  334. format = replacer.Replace(format)
  335. return t.Format(format)
  336. }
  337. // convert string to specify type
  338. type StrTo string
  339. func (f StrTo) Exist() bool {
  340. return string(f) != string(0x1E)
  341. }
  342. func (f StrTo) Int() (int, error) {
  343. v, err := strconv.ParseInt(f.String(), 10, 32)
  344. return int(v), err
  345. }
  346. func (f StrTo) String() string {
  347. if f.Exist() {
  348. return string(f)
  349. }
  350. return ""
  351. }
  352. // convert any type to string
  353. func ToStr(value interface{}, args ...int) (s string) {
  354. switch v := value.(type) {
  355. case bool:
  356. s = strconv.FormatBool(v)
  357. case float32:
  358. s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32))
  359. case float64:
  360. s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64))
  361. case int:
  362. s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
  363. case int8:
  364. s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
  365. case int16:
  366. s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
  367. case int32:
  368. s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
  369. case int64:
  370. s = strconv.FormatInt(v, argInt(args).Get(0, 10))
  371. case uint:
  372. s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
  373. case uint8:
  374. s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
  375. case uint16:
  376. s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
  377. case uint32:
  378. s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
  379. case uint64:
  380. s = strconv.FormatUint(v, argInt(args).Get(0, 10))
  381. case string:
  382. s = v
  383. case []byte:
  384. s = string(v)
  385. default:
  386. s = fmt.Sprintf("%v", v)
  387. }
  388. return s
  389. }
  390. type argInt []int
  391. func (a argInt) Get(i int, args ...int) (r int) {
  392. if i >= 0 && i < len(a) {
  393. r = a[i]
  394. }
  395. if len(args) > 0 {
  396. r = args[0]
  397. }
  398. return
  399. }
  400. type Actioner interface {
  401. GetOpType() int
  402. GetActUserName() string
  403. GetRepoName() string
  404. GetContent() string
  405. }
  406. // ActionIcon accepts a int that represents action operation type
  407. // and returns a icon class name.
  408. func ActionIcon(opType int) string {
  409. switch opType {
  410. case 1: // Create repository.
  411. return "plus-circle"
  412. case 5: // Commit repository.
  413. return "arrow-circle-o-right"
  414. default:
  415. return "invalid type"
  416. }
  417. }
  418. const (
  419. TPL_CREATE_REPO = `<a href="/user/%s">%s</a> created repository <a href="/%s/%s">%s</a>`
  420. 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`
  421. 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>`
  422. )
  423. // ActionDesc accepts int that represents action operation type
  424. // and returns the description.
  425. func ActionDesc(act Actioner, avatarLink string) string {
  426. actUserName := act.GetActUserName()
  427. repoName := act.GetRepoName()
  428. content := act.GetContent()
  429. switch act.GetOpType() {
  430. case 1: // Create repository.
  431. return fmt.Sprintf(TPL_CREATE_REPO, actUserName, actUserName, actUserName, repoName, repoName)
  432. case 5: // Commit repository.
  433. var commits [][]string
  434. if err := json.Unmarshal([]byte(content), &commits); err != nil {
  435. return err.Error()
  436. }
  437. buf := bytes.NewBuffer([]byte("\n"))
  438. for _, commit := range commits {
  439. buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, avatarLink, actUserName, repoName, commit[0], commit[0][:7], commit[1]) + "\n")
  440. }
  441. return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, actUserName, repoName, "master", "master", actUserName, repoName, actUserName, repoName,
  442. buf.String())
  443. default:
  444. return "invalid type"
  445. }
  446. }