You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tool.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. "crypto/md5"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "crypto/sha256"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "fmt"
  13. "html/template"
  14. "io"
  15. "math"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "runtime"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "unicode"
  26. "code.gitea.io/gitea/modules/git"
  27. "code.gitea.io/gitea/modules/log"
  28. "code.gitea.io/gitea/modules/setting"
  29. "code.gitea.io/gitea/modules/util"
  30. "github.com/Unknwon/com"
  31. "github.com/Unknwon/i18n"
  32. )
  33. // EncodeMD5 encodes string to md5 hex value.
  34. func EncodeMD5(str string) string {
  35. m := md5.New()
  36. _, _ = m.Write([]byte(str))
  37. return hex.EncodeToString(m.Sum(nil))
  38. }
  39. // EncodeSha1 string to sha1 hex value.
  40. func EncodeSha1(str string) string {
  41. h := sha1.New()
  42. _, _ = h.Write([]byte(str))
  43. return hex.EncodeToString(h.Sum(nil))
  44. }
  45. // EncodeSha256 string to sha1 hex value.
  46. func EncodeSha256(str string) string {
  47. h := sha256.New()
  48. _, _ = h.Write([]byte(str))
  49. return hex.EncodeToString(h.Sum(nil))
  50. }
  51. // ShortSha is basically just truncating.
  52. // It is DEPRECATED and will be removed in the future.
  53. func ShortSha(sha1 string) string {
  54. return TruncateString(sha1, 10)
  55. }
  56. // BasicAuthDecode decode basic auth string
  57. func BasicAuthDecode(encoded string) (string, string, error) {
  58. s, err := base64.StdEncoding.DecodeString(encoded)
  59. if err != nil {
  60. return "", "", err
  61. }
  62. auth := strings.SplitN(string(s), ":", 2)
  63. return auth[0], auth[1], nil
  64. }
  65. // BasicAuthEncode encode basic auth string
  66. func BasicAuthEncode(username, password string) string {
  67. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  68. }
  69. // GetRandomBytesAsBase64 generates a random base64 string from n bytes
  70. func GetRandomBytesAsBase64(n int) string {
  71. bytes := make([]byte, 32)
  72. _, err := io.ReadFull(rand.Reader, bytes)
  73. if err != nil {
  74. log.Fatal("Error reading random bytes: %v", err)
  75. }
  76. return base64.RawURLEncoding.EncodeToString(bytes)
  77. }
  78. // VerifyTimeLimitCode verify time limit code
  79. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  80. if len(code) <= 18 {
  81. return false
  82. }
  83. // split code
  84. start := code[:12]
  85. lives := code[12:18]
  86. if d, err := com.StrTo(lives).Int(); err == nil {
  87. minutes = d
  88. }
  89. // right active code
  90. retCode := CreateTimeLimitCode(data, minutes, start)
  91. if retCode == code && minutes > 0 {
  92. // check time is expired or not
  93. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  94. now := time.Now()
  95. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  96. return true
  97. }
  98. }
  99. return false
  100. }
  101. // TimeLimitCodeLength default value for time limit code
  102. const TimeLimitCodeLength = 12 + 6 + 40
  103. // CreateTimeLimitCode create a time limit code
  104. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  105. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  106. format := "200601021504"
  107. var start, end time.Time
  108. var startStr, endStr string
  109. if startInf == nil {
  110. // Use now time create code
  111. start = time.Now()
  112. startStr = start.Format(format)
  113. } else {
  114. // use start string create code
  115. startStr = startInf.(string)
  116. start, _ = time.ParseInLocation(format, startStr, time.Local)
  117. startStr = start.Format(format)
  118. }
  119. end = start.Add(time.Minute * time.Duration(minutes))
  120. endStr = end.Format(format)
  121. // create sha1 encode string
  122. sh := sha1.New()
  123. _, _ = sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  124. encoded := hex.EncodeToString(sh.Sum(nil))
  125. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  126. return code
  127. }
  128. // HashEmail hashes email address to MD5 string.
  129. // https://en.gravatar.com/site/implement/hash/
  130. func HashEmail(email string) string {
  131. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  132. }
  133. // DefaultAvatarLink the default avatar link
  134. func DefaultAvatarLink() string {
  135. return setting.AppSubURL + "/img/avatar_default.png"
  136. }
  137. // DefaultAvatarSize is a sentinel value for the default avatar size, as
  138. // determined by the avatar-hosting service.
  139. const DefaultAvatarSize = -1
  140. // libravatarURL returns the URL for the given email. This function should only
  141. // be called if a federated avatar service is enabled.
  142. func libravatarURL(email string) (*url.URL, error) {
  143. urlStr, err := setting.LibravatarService.FromEmail(email)
  144. if err != nil {
  145. log.Error("LibravatarService.FromEmail(email=%s): error %v", email, err)
  146. return nil, err
  147. }
  148. u, err := url.Parse(urlStr)
  149. if err != nil {
  150. log.Error("Failed to parse libravatar url(%s): error %v", urlStr, err)
  151. return nil, err
  152. }
  153. return u, nil
  154. }
  155. // SizedAvatarLink returns a sized link to the avatar for the given email
  156. // address.
  157. func SizedAvatarLink(email string, size int) string {
  158. var avatarURL *url.URL
  159. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  160. var err error
  161. avatarURL, err = libravatarURL(email)
  162. if err != nil {
  163. return DefaultAvatarLink()
  164. }
  165. } else if !setting.DisableGravatar {
  166. // copy GravatarSourceURL, because we will modify its Path.
  167. copyOfGravatarSourceURL := *setting.GravatarSourceURL
  168. avatarURL = &copyOfGravatarSourceURL
  169. avatarURL.Path = path.Join(avatarURL.Path, HashEmail(email))
  170. } else {
  171. return DefaultAvatarLink()
  172. }
  173. vals := avatarURL.Query()
  174. vals.Set("d", "identicon")
  175. if size != DefaultAvatarSize {
  176. vals.Set("s", strconv.Itoa(size))
  177. }
  178. avatarURL.RawQuery = vals.Encode()
  179. return avatarURL.String()
  180. }
  181. // AvatarLink returns relative avatar link to the site domain by given email,
  182. // which includes app sub-url as prefix. However, it is possible
  183. // to return full URL if user enables Gravatar-like service.
  184. func AvatarLink(email string) string {
  185. return SizedAvatarLink(email, DefaultAvatarSize)
  186. }
  187. // Seconds-based time units
  188. const (
  189. Minute = 60
  190. Hour = 60 * Minute
  191. Day = 24 * Hour
  192. Week = 7 * Day
  193. Month = 30 * Day
  194. Year = 12 * Month
  195. )
  196. func computeTimeDiff(diff int64, lang string) (int64, string) {
  197. diffStr := ""
  198. switch {
  199. case diff <= 0:
  200. diff = 0
  201. diffStr = i18n.Tr(lang, "tool.now")
  202. case diff < 2:
  203. diff = 0
  204. diffStr = i18n.Tr(lang, "tool.1s")
  205. case diff < 1*Minute:
  206. diffStr = i18n.Tr(lang, "tool.seconds", diff)
  207. diff = 0
  208. case diff < 2*Minute:
  209. diff -= 1 * Minute
  210. diffStr = i18n.Tr(lang, "tool.1m")
  211. case diff < 1*Hour:
  212. diffStr = i18n.Tr(lang, "tool.minutes", diff/Minute)
  213. diff -= diff / Minute * Minute
  214. case diff < 2*Hour:
  215. diff -= 1 * Hour
  216. diffStr = i18n.Tr(lang, "tool.1h")
  217. case diff < 1*Day:
  218. diffStr = i18n.Tr(lang, "tool.hours", diff/Hour)
  219. diff -= diff / Hour * Hour
  220. case diff < 2*Day:
  221. diff -= 1 * Day
  222. diffStr = i18n.Tr(lang, "tool.1d")
  223. case diff < 1*Week:
  224. diffStr = i18n.Tr(lang, "tool.days", diff/Day)
  225. diff -= diff / Day * Day
  226. case diff < 2*Week:
  227. diff -= 1 * Week
  228. diffStr = i18n.Tr(lang, "tool.1w")
  229. case diff < 1*Month:
  230. diffStr = i18n.Tr(lang, "tool.weeks", diff/Week)
  231. diff -= diff / Week * Week
  232. case diff < 2*Month:
  233. diff -= 1 * Month
  234. diffStr = i18n.Tr(lang, "tool.1mon")
  235. case diff < 1*Year:
  236. diffStr = i18n.Tr(lang, "tool.months", diff/Month)
  237. diff -= diff / Month * Month
  238. case diff < 2*Year:
  239. diff -= 1 * Year
  240. diffStr = i18n.Tr(lang, "tool.1y")
  241. default:
  242. diffStr = i18n.Tr(lang, "tool.years", diff/Year)
  243. diff -= (diff / Year) * Year
  244. }
  245. return diff, diffStr
  246. }
  247. // MinutesToFriendly returns a user friendly string with number of minutes
  248. // converted to hours and minutes.
  249. func MinutesToFriendly(minutes int, lang string) string {
  250. duration := time.Duration(minutes) * time.Minute
  251. return TimeSincePro(time.Now().Add(-duration), lang)
  252. }
  253. // TimeSincePro calculates the time interval and generate full user-friendly string.
  254. func TimeSincePro(then time.Time, lang string) string {
  255. return timeSincePro(then, time.Now(), lang)
  256. }
  257. func timeSincePro(then, now time.Time, lang string) string {
  258. diff := now.Unix() - then.Unix()
  259. if then.After(now) {
  260. return i18n.Tr(lang, "tool.future")
  261. }
  262. if diff == 0 {
  263. return i18n.Tr(lang, "tool.now")
  264. }
  265. var timeStr, diffStr string
  266. for {
  267. if diff == 0 {
  268. break
  269. }
  270. diff, diffStr = computeTimeDiff(diff, lang)
  271. timeStr += ", " + diffStr
  272. }
  273. return strings.TrimPrefix(timeStr, ", ")
  274. }
  275. func timeSince(then, now time.Time, lang string) string {
  276. return timeSinceUnix(then.Unix(), now.Unix(), lang)
  277. }
  278. func timeSinceUnix(then, now int64, lang string) string {
  279. lbl := "tool.ago"
  280. diff := now - then
  281. if then > now {
  282. lbl = "tool.from_now"
  283. diff = then - now
  284. }
  285. if diff <= 0 {
  286. return i18n.Tr(lang, "tool.now")
  287. }
  288. _, diffStr := computeTimeDiff(diff, lang)
  289. return i18n.Tr(lang, lbl, diffStr)
  290. }
  291. // RawTimeSince retrieves i18n key of time since t
  292. func RawTimeSince(t time.Time, lang string) string {
  293. return timeSince(t, time.Now(), lang)
  294. }
  295. // TimeSince calculates the time interval and generate user-friendly string.
  296. func TimeSince(then time.Time, lang string) template.HTML {
  297. return htmlTimeSince(then, time.Now(), lang)
  298. }
  299. func htmlTimeSince(then, now time.Time, lang string) template.HTML {
  300. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  301. then.Format(setting.TimeFormat),
  302. timeSince(then, now, lang)))
  303. }
  304. // TimeSinceUnix calculates the time interval and generate user-friendly string.
  305. func TimeSinceUnix(then util.TimeStamp, lang string) template.HTML {
  306. return htmlTimeSinceUnix(then, util.TimeStamp(time.Now().Unix()), lang)
  307. }
  308. func htmlTimeSinceUnix(then, now util.TimeStamp, lang string) template.HTML {
  309. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  310. then.Format(setting.TimeFormat),
  311. timeSinceUnix(int64(then), int64(now), lang)))
  312. }
  313. // Storage space size types
  314. const (
  315. Byte = 1
  316. KByte = Byte * 1024
  317. MByte = KByte * 1024
  318. GByte = MByte * 1024
  319. TByte = GByte * 1024
  320. PByte = TByte * 1024
  321. EByte = PByte * 1024
  322. )
  323. func logn(n, b float64) float64 {
  324. return math.Log(n) / math.Log(b)
  325. }
  326. func humanateBytes(s uint64, base float64, sizes []string) string {
  327. if s < 10 {
  328. return fmt.Sprintf("%dB", s)
  329. }
  330. e := math.Floor(logn(float64(s), base))
  331. suffix := sizes[int(e)]
  332. val := float64(s) / math.Pow(base, math.Floor(e))
  333. f := "%.0f"
  334. if val < 10 {
  335. f = "%.1f"
  336. }
  337. return fmt.Sprintf(f+"%s", val, suffix)
  338. }
  339. // FileSize calculates the file size and generate user-friendly string.
  340. func FileSize(s int64) string {
  341. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  342. return humanateBytes(uint64(s), 1024, sizes)
  343. }
  344. // Subtract deals with subtraction of all types of number.
  345. func Subtract(left interface{}, right interface{}) interface{} {
  346. var rleft, rright int64
  347. var fleft, fright float64
  348. var isInt = true
  349. switch v := left.(type) {
  350. case int:
  351. rleft = int64(v)
  352. case int8:
  353. rleft = int64(v)
  354. case int16:
  355. rleft = int64(v)
  356. case int32:
  357. rleft = int64(v)
  358. case int64:
  359. rleft = v
  360. case float32:
  361. fleft = float64(v)
  362. isInt = false
  363. case float64:
  364. fleft = v
  365. isInt = false
  366. }
  367. switch v := right.(type) {
  368. case int:
  369. rright = int64(v)
  370. case int8:
  371. rright = int64(v)
  372. case int16:
  373. rright = int64(v)
  374. case int32:
  375. rright = int64(v)
  376. case int64:
  377. rright = v
  378. case float32:
  379. fright = float64(v)
  380. isInt = false
  381. case float64:
  382. fright = v
  383. isInt = false
  384. }
  385. if isInt {
  386. return rleft - rright
  387. }
  388. return fleft + float64(rleft) - (fright + float64(rright))
  389. }
  390. // EllipsisString returns a truncated short string,
  391. // it appends '...' in the end of the length of string is too large.
  392. func EllipsisString(str string, length int) string {
  393. if length <= 3 {
  394. return "..."
  395. }
  396. if len(str) <= length {
  397. return str
  398. }
  399. return str[:length-3] + "..."
  400. }
  401. // TruncateString returns a truncated string with given limit,
  402. // it returns input string if length is not reached limit.
  403. func TruncateString(str string, limit int) string {
  404. if len(str) < limit {
  405. return str
  406. }
  407. return str[:limit]
  408. }
  409. // StringsToInt64s converts a slice of string to a slice of int64.
  410. func StringsToInt64s(strs []string) ([]int64, error) {
  411. ints := make([]int64, len(strs))
  412. for i := range strs {
  413. n, err := com.StrTo(strs[i]).Int64()
  414. if err != nil {
  415. return ints, err
  416. }
  417. ints[i] = n
  418. }
  419. return ints, nil
  420. }
  421. // Int64sToStrings converts a slice of int64 to a slice of string.
  422. func Int64sToStrings(ints []int64) []string {
  423. strs := make([]string, len(ints))
  424. for i := range ints {
  425. strs[i] = strconv.FormatInt(ints[i], 10)
  426. }
  427. return strs
  428. }
  429. // Int64sToMap converts a slice of int64 to a int64 map.
  430. func Int64sToMap(ints []int64) map[int64]bool {
  431. m := make(map[int64]bool)
  432. for _, i := range ints {
  433. m[i] = true
  434. }
  435. return m
  436. }
  437. // Int64sContains returns if a int64 in a slice of int64
  438. func Int64sContains(intsSlice []int64, a int64) bool {
  439. for _, c := range intsSlice {
  440. if c == a {
  441. return true
  442. }
  443. }
  444. return false
  445. }
  446. // IsLetter reports whether the rune is a letter (category L).
  447. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  448. func IsLetter(ch rune) bool {
  449. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  450. }
  451. // IsTextFile returns true if file content format is plain text or empty.
  452. func IsTextFile(data []byte) bool {
  453. if len(data) == 0 {
  454. return true
  455. }
  456. return strings.Contains(http.DetectContentType(data), "text/")
  457. }
  458. // IsImageFile detects if data is an image format
  459. func IsImageFile(data []byte) bool {
  460. return strings.Contains(http.DetectContentType(data), "image/")
  461. }
  462. // IsPDFFile detects if data is a pdf format
  463. func IsPDFFile(data []byte) bool {
  464. return strings.Contains(http.DetectContentType(data), "application/pdf")
  465. }
  466. // IsVideoFile detects if data is an video format
  467. func IsVideoFile(data []byte) bool {
  468. return strings.Contains(http.DetectContentType(data), "video/")
  469. }
  470. // IsAudioFile detects if data is an video format
  471. func IsAudioFile(data []byte) bool {
  472. return strings.Contains(http.DetectContentType(data), "audio/")
  473. }
  474. // EntryIcon returns the octicon class for displaying files/directories
  475. func EntryIcon(entry *git.TreeEntry) string {
  476. switch {
  477. case entry.IsLink():
  478. te, err := entry.FollowLink()
  479. if err != nil {
  480. log.Debug(err.Error())
  481. return "file-symlink-file"
  482. }
  483. if te.IsDir() {
  484. return "file-symlink-directory"
  485. }
  486. return "file-symlink-file"
  487. case entry.IsDir():
  488. return "file-directory"
  489. case entry.IsSubModule():
  490. return "file-submodule"
  491. }
  492. return "file-text"
  493. }
  494. // SetupGiteaRoot Sets GITEA_ROOT if it is not already set and returns the value
  495. func SetupGiteaRoot() string {
  496. giteaRoot := os.Getenv("GITEA_ROOT")
  497. if giteaRoot == "" {
  498. _, filename, _, _ := runtime.Caller(0)
  499. giteaRoot = strings.TrimSuffix(filename, "modules/base/tool.go")
  500. wd, err := os.Getwd()
  501. if err != nil {
  502. rel, err := filepath.Rel(giteaRoot, wd)
  503. if err != nil && strings.HasPrefix(filepath.ToSlash(rel), "../") {
  504. giteaRoot = wd
  505. }
  506. }
  507. if _, err := os.Stat(filepath.Join(giteaRoot, "gitea")); os.IsNotExist(err) {
  508. giteaRoot = ""
  509. } else if err := os.Setenv("GITEA_ROOT", giteaRoot); err != nil {
  510. giteaRoot = ""
  511. }
  512. }
  513. return giteaRoot
  514. }