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 11KB

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