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.

545 lines
13 KiB

10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "html/template"
  13. "io"
  14. "math"
  15. "math/big"
  16. "net/http"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "unicode"
  21. "unicode/utf8"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/setting"
  24. "github.com/Unknwon/com"
  25. "github.com/Unknwon/i18n"
  26. "github.com/gogits/chardet"
  27. )
  28. // EncodeMD5 encodes string to md5 hex value.
  29. func EncodeMD5(str string) string {
  30. m := md5.New()
  31. m.Write([]byte(str))
  32. return hex.EncodeToString(m.Sum(nil))
  33. }
  34. // EncodeSha1 string to sha1 hex value.
  35. func EncodeSha1(str string) string {
  36. h := sha1.New()
  37. h.Write([]byte(str))
  38. return hex.EncodeToString(h.Sum(nil))
  39. }
  40. // ShortSha is basically just truncating.
  41. // It is DEPRECATED and will be removed in the future.
  42. func ShortSha(sha1 string) string {
  43. return TruncateString(sha1, 10)
  44. }
  45. // DetectEncoding detect the encoding of content
  46. func DetectEncoding(content []byte) (string, error) {
  47. if utf8.Valid(content) {
  48. log.Debug("Detected encoding: utf-8 (fast)")
  49. return "UTF-8", nil
  50. }
  51. result, err := chardet.NewTextDetector().DetectBest(content)
  52. if err != nil {
  53. return "", err
  54. }
  55. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  56. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  57. return setting.Repository.AnsiCharset, err
  58. }
  59. log.Debug("Detected encoding: %s", result.Charset)
  60. return result.Charset, err
  61. }
  62. // BasicAuthDecode decode basic auth string
  63. func BasicAuthDecode(encoded string) (string, string, error) {
  64. s, err := base64.StdEncoding.DecodeString(encoded)
  65. if err != nil {
  66. return "", "", err
  67. }
  68. auth := strings.SplitN(string(s), ":", 2)
  69. return auth[0], auth[1], nil
  70. }
  71. // BasicAuthEncode encode basic auth string
  72. func BasicAuthEncode(username, password string) string {
  73. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  74. }
  75. // GetRandomString generate random string by specify chars.
  76. func GetRandomString(n int) (string, error) {
  77. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  78. buffer := make([]byte, n)
  79. max := big.NewInt(int64(len(alphanum)))
  80. for i := 0; i < n; i++ {
  81. index, err := randomInt(max)
  82. if err != nil {
  83. return "", err
  84. }
  85. buffer[i] = alphanum[index]
  86. }
  87. return string(buffer), nil
  88. }
  89. // GetRandomBytesAsBase64 generates a random base64 string from n bytes
  90. func GetRandomBytesAsBase64(n int) string {
  91. bytes := make([]byte, 32)
  92. _, err := io.ReadFull(rand.Reader, bytes)
  93. if err != nil {
  94. log.Fatal(4, "Error reading random bytes: %v", err)
  95. }
  96. return base64.RawURLEncoding.EncodeToString(bytes)
  97. }
  98. func randomInt(max *big.Int) (int, error) {
  99. rand, err := rand.Int(rand.Reader, max)
  100. if err != nil {
  101. return 0, err
  102. }
  103. return int(rand.Int64()), nil
  104. }
  105. // VerifyTimeLimitCode verify time limit code
  106. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  107. if len(code) <= 18 {
  108. return false
  109. }
  110. // split code
  111. start := code[:12]
  112. lives := code[12:18]
  113. if d, err := com.StrTo(lives).Int(); err == nil {
  114. minutes = d
  115. }
  116. // right active code
  117. retCode := CreateTimeLimitCode(data, minutes, start)
  118. if retCode == code && minutes > 0 {
  119. // check time is expired or not
  120. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  121. now := time.Now()
  122. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  123. return true
  124. }
  125. }
  126. return false
  127. }
  128. // TimeLimitCodeLength default value for time limit code
  129. const TimeLimitCodeLength = 12 + 6 + 40
  130. // CreateTimeLimitCode create a time limit code
  131. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  132. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  133. format := "200601021504"
  134. var start, end time.Time
  135. var startStr, endStr string
  136. if startInf == nil {
  137. // Use now time create code
  138. start = time.Now()
  139. startStr = start.Format(format)
  140. } else {
  141. // use start string create code
  142. startStr = startInf.(string)
  143. start, _ = time.ParseInLocation(format, startStr, time.Local)
  144. startStr = start.Format(format)
  145. }
  146. end = start.Add(time.Minute * time.Duration(minutes))
  147. endStr = end.Format(format)
  148. // create sha1 encode string
  149. sh := sha1.New()
  150. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  151. encoded := hex.EncodeToString(sh.Sum(nil))
  152. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  153. return code
  154. }
  155. // HashEmail hashes email address to MD5 string.
  156. // https://en.gravatar.com/site/implement/hash/
  157. func HashEmail(email string) string {
  158. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  159. }
  160. // AvatarLink returns relative avatar link to the site domain by given email,
  161. // which includes app sub-url as prefix. However, it is possible
  162. // to return full URL if user enables Gravatar-like service.
  163. func AvatarLink(email string) string {
  164. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  165. // TODO: This doesn't check any error. AvatarLink should return (string, error)
  166. url, _ := setting.LibravatarService.FromEmail(email)
  167. return url
  168. }
  169. if !setting.DisableGravatar {
  170. return setting.GravatarSource + HashEmail(email)
  171. }
  172. return setting.AppSubURL + "/img/avatar_default.png"
  173. }
  174. // Seconds-based time units
  175. const (
  176. Minute = 60
  177. Hour = 60 * Minute
  178. Day = 24 * Hour
  179. Week = 7 * Day
  180. Month = 30 * Day
  181. Year = 12 * Month
  182. )
  183. func computeTimeDiff(diff int64) (int64, string) {
  184. diffStr := ""
  185. switch {
  186. case diff <= 0:
  187. diff = 0
  188. diffStr = "now"
  189. case diff < 2:
  190. diff = 0
  191. diffStr = "1 second"
  192. case diff < 1*Minute:
  193. diffStr = fmt.Sprintf("%d seconds", diff)
  194. diff = 0
  195. case diff < 2*Minute:
  196. diff -= 1 * Minute
  197. diffStr = "1 minute"
  198. case diff < 1*Hour:
  199. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  200. diff -= diff / Minute * Minute
  201. case diff < 2*Hour:
  202. diff -= 1 * Hour
  203. diffStr = "1 hour"
  204. case diff < 1*Day:
  205. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  206. diff -= diff / Hour * Hour
  207. case diff < 2*Day:
  208. diff -= 1 * Day
  209. diffStr = "1 day"
  210. case diff < 1*Week:
  211. diffStr = fmt.Sprintf("%d days", diff/Day)
  212. diff -= diff / Day * Day
  213. case diff < 2*Week:
  214. diff -= 1 * Week
  215. diffStr = "1 week"
  216. case diff < 1*Month:
  217. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  218. diff -= diff / Week * Week
  219. case diff < 2*Month:
  220. diff -= 1 * Month
  221. diffStr = "1 month"
  222. case diff < 1*Year:
  223. diffStr = fmt.Sprintf("%d months", diff/Month)
  224. diff -= diff / Month * Month
  225. case diff < 2*Year:
  226. diff -= 1 * Year
  227. diffStr = "1 year"
  228. default:
  229. diffStr = fmt.Sprintf("%d years", diff/Year)
  230. diff -= (diff / Year) * Year
  231. }
  232. return diff, diffStr
  233. }
  234. // TimeSincePro calculates the time interval and generate full user-friendly string.
  235. func TimeSincePro(then time.Time) string {
  236. return timeSincePro(then, time.Now())
  237. }
  238. func timeSincePro(then, now time.Time) string {
  239. diff := now.Unix() - then.Unix()
  240. if then.After(now) {
  241. return "future"
  242. }
  243. if diff == 0 {
  244. return "now"
  245. }
  246. var timeStr, diffStr string
  247. for {
  248. if diff == 0 {
  249. break
  250. }
  251. diff, diffStr = computeTimeDiff(diff)
  252. timeStr += ", " + diffStr
  253. }
  254. return strings.TrimPrefix(timeStr, ", ")
  255. }
  256. func timeSince(then, now time.Time, lang string) string {
  257. lbl := i18n.Tr(lang, "tool.ago")
  258. diff := now.Unix() - then.Unix()
  259. if then.After(now) {
  260. lbl = i18n.Tr(lang, "tool.from_now")
  261. diff = then.Unix() - now.Unix()
  262. }
  263. switch {
  264. case diff <= 0:
  265. return i18n.Tr(lang, "tool.now")
  266. case diff <= 1:
  267. return i18n.Tr(lang, "tool.1s", lbl)
  268. case diff < 1*Minute:
  269. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  270. case diff < 2*Minute:
  271. return i18n.Tr(lang, "tool.1m", lbl)
  272. case diff < 1*Hour:
  273. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  274. case diff < 2*Hour:
  275. return i18n.Tr(lang, "tool.1h", lbl)
  276. case diff < 1*Day:
  277. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  278. case diff < 2*Day:
  279. return i18n.Tr(lang, "tool.1d", lbl)
  280. case diff < 1*Week:
  281. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  282. case diff < 2*Week:
  283. return i18n.Tr(lang, "tool.1w", lbl)
  284. case diff < 1*Month:
  285. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  286. case diff < 2*Month:
  287. return i18n.Tr(lang, "tool.1mon", lbl)
  288. case diff < 1*Year:
  289. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  290. case diff < 2*Year:
  291. return i18n.Tr(lang, "tool.1y", lbl)
  292. default:
  293. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  294. }
  295. }
  296. // RawTimeSince retrieves i18n key of time since t
  297. func RawTimeSince(t time.Time, lang string) string {
  298. return timeSince(t, time.Now(), lang)
  299. }
  300. // TimeSince calculates the time interval and generate user-friendly string.
  301. func TimeSince(then time.Time, lang string) template.HTML {
  302. return htmlTimeSince(then, time.Now(), lang)
  303. }
  304. func htmlTimeSince(then, now time.Time, lang string) template.HTML {
  305. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  306. then.Format(setting.TimeFormat),
  307. timeSince(then, now, lang)))
  308. }
  309. // Storage space size types
  310. const (
  311. Byte = 1
  312. KByte = Byte * 1024
  313. MByte = KByte * 1024
  314. GByte = MByte * 1024
  315. TByte = GByte * 1024
  316. PByte = TByte * 1024
  317. EByte = PByte * 1024
  318. )
  319. var bytesSizeTable = map[string]uint64{
  320. "b": Byte,
  321. "kb": KByte,
  322. "mb": MByte,
  323. "gb": GByte,
  324. "tb": TByte,
  325. "pb": PByte,
  326. "eb": EByte,
  327. }
  328. func logn(n, b float64) float64 {
  329. return math.Log(n) / math.Log(b)
  330. }
  331. func humanateBytes(s uint64, base float64, sizes []string) string {
  332. if s < 10 {
  333. return fmt.Sprintf("%dB", s)
  334. }
  335. e := math.Floor(logn(float64(s), base))
  336. suffix := sizes[int(e)]
  337. val := float64(s) / math.Pow(base, math.Floor(e))
  338. f := "%.0f"
  339. if val < 10 {
  340. f = "%.1f"
  341. }
  342. return fmt.Sprintf(f+"%s", val, suffix)
  343. }
  344. // FileSize calculates the file size and generate user-friendly string.
  345. func FileSize(s int64) string {
  346. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  347. return humanateBytes(uint64(s), 1024, sizes)
  348. }
  349. // Subtract deals with subtraction of all types of number.
  350. func Subtract(left interface{}, right interface{}) interface{} {
  351. var rleft, rright int64
  352. var fleft, fright float64
  353. var isInt = true
  354. switch left.(type) {
  355. case int:
  356. rleft = int64(left.(int))
  357. case int8:
  358. rleft = int64(left.(int8))
  359. case int16:
  360. rleft = int64(left.(int16))
  361. case int32:
  362. rleft = int64(left.(int32))
  363. case int64:
  364. rleft = left.(int64)
  365. case float32:
  366. fleft = float64(left.(float32))
  367. isInt = false
  368. case float64:
  369. fleft = left.(float64)
  370. isInt = false
  371. }
  372. switch right.(type) {
  373. case int:
  374. rright = int64(right.(int))
  375. case int8:
  376. rright = int64(right.(int8))
  377. case int16:
  378. rright = int64(right.(int16))
  379. case int32:
  380. rright = int64(right.(int32))
  381. case int64:
  382. rright = right.(int64)
  383. case float32:
  384. fright = float64(right.(float32))
  385. isInt = false
  386. case float64:
  387. fright = right.(float64)
  388. isInt = false
  389. }
  390. if isInt {
  391. return rleft - rright
  392. }
  393. return fleft + float64(rleft) - (fright + float64(rright))
  394. }
  395. // EllipsisString returns a truncated short string,
  396. // it appends '...' in the end of the length of string is too large.
  397. func EllipsisString(str string, length int) string {
  398. if length <= 3 {
  399. return "..."
  400. }
  401. if len(str) <= length {
  402. return str
  403. }
  404. return str[:length-3] + "..."
  405. }
  406. // TruncateString returns a truncated string with given limit,
  407. // it returns input string if length is not reached limit.
  408. func TruncateString(str string, limit int) string {
  409. if len(str) < limit {
  410. return str
  411. }
  412. return str[:limit]
  413. }
  414. // StringsToInt64s converts a slice of string to a slice of int64.
  415. func StringsToInt64s(strs []string) ([]int64, error) {
  416. ints := make([]int64, len(strs))
  417. for i := range strs {
  418. n, err := com.StrTo(strs[i]).Int64()
  419. if err != nil {
  420. return ints, err
  421. }
  422. ints[i] = n
  423. }
  424. return ints, nil
  425. }
  426. // Int64sToStrings converts a slice of int64 to a slice of string.
  427. func Int64sToStrings(ints []int64) []string {
  428. strs := make([]string, len(ints))
  429. for i := range ints {
  430. strs[i] = strconv.FormatInt(ints[i], 10)
  431. }
  432. return strs
  433. }
  434. // Int64sToMap converts a slice of int64 to a int64 map.
  435. func Int64sToMap(ints []int64) map[int64]bool {
  436. m := make(map[int64]bool)
  437. for _, i := range ints {
  438. m[i] = true
  439. }
  440. return m
  441. }
  442. // IsLetter reports whether the rune is a letter (category L).
  443. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  444. func IsLetter(ch rune) bool {
  445. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  446. }
  447. // IsTextFile returns true if file content format is plain text or empty.
  448. func IsTextFile(data []byte) bool {
  449. if len(data) == 0 {
  450. return true
  451. }
  452. return strings.Index(http.DetectContentType(data), "text/") != -1
  453. }
  454. // IsImageFile detects if data is an image format
  455. func IsImageFile(data []byte) bool {
  456. return strings.Index(http.DetectContentType(data), "image/") != -1
  457. }
  458. // IsPDFFile detects if data is a pdf format
  459. func IsPDFFile(data []byte) bool {
  460. return strings.Index(http.DetectContentType(data), "application/pdf") != -1
  461. }
  462. // IsVideoFile detects if data is an video format
  463. func IsVideoFile(data []byte) bool {
  464. return strings.Index(http.DetectContentType(data), "video/") != -1
  465. }