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

tool.go 13 kB

11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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/hmac"
  7. "crypto/md5"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "fmt"
  13. "hash"
  14. "html/template"
  15. "math"
  16. "net/http"
  17. "strings"
  18. "time"
  19. "unicode"
  20. "unicode/utf8"
  21. "github.com/Unknwon/com"
  22. "github.com/Unknwon/i18n"
  23. "github.com/go-gitea/gitea/modules/log"
  24. "github.com/go-gitea/gitea/modules/setting"
  25. "github.com/gogits/chardet"
  26. )
  27. // EncodeMD5 encodes string to md5 hex value.
  28. func EncodeMD5(str string) string {
  29. m := md5.New()
  30. m.Write([]byte(str))
  31. return hex.EncodeToString(m.Sum(nil))
  32. }
  33. // Encode string to sha1 hex value.
  34. func EncodeSha1(str string) string {
  35. h := sha1.New()
  36. h.Write([]byte(str))
  37. return hex.EncodeToString(h.Sum(nil))
  38. }
  39. func ShortSha(sha1 string) string {
  40. if len(sha1) > 10 {
  41. return sha1[:10]
  42. }
  43. return sha1
  44. }
  45. func DetectEncoding(content []byte) (string, error) {
  46. if utf8.Valid(content) {
  47. log.Debug("Detected encoding: utf-8 (fast)")
  48. return "UTF-8", nil
  49. }
  50. result, err := chardet.NewTextDetector().DetectBest(content)
  51. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  52. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  53. return setting.Repository.AnsiCharset, err
  54. }
  55. log.Debug("Detected encoding: %s", result.Charset)
  56. return result.Charset, err
  57. }
  58. func BasicAuthDecode(encoded string) (string, string, error) {
  59. s, err := base64.StdEncoding.DecodeString(encoded)
  60. if err != nil {
  61. return "", "", err
  62. }
  63. auth := strings.SplitN(string(s), ":", 2)
  64. return auth[0], auth[1], nil
  65. }
  66. func BasicAuthEncode(username, password string) string {
  67. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  68. }
  69. // GetRandomString generate random string by specify chars.
  70. func GetRandomString(n int, alphabets ...byte) string {
  71. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  72. var bytes = make([]byte, n)
  73. rand.Read(bytes)
  74. for i, b := range bytes {
  75. if len(alphabets) == 0 {
  76. bytes[i] = alphanum[b%byte(len(alphanum))]
  77. } else {
  78. bytes[i] = alphabets[b%byte(len(alphabets))]
  79. }
  80. }
  81. return string(bytes)
  82. }
  83. // http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
  84. // FIXME: use https://godoc.org/golang.org/x/crypto/pbkdf2?
  85. func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
  86. prf := hmac.New(h, password)
  87. hashLen := prf.Size()
  88. numBlocks := (keyLen + hashLen - 1) / hashLen
  89. var buf [4]byte
  90. dk := make([]byte, 0, numBlocks*hashLen)
  91. U := make([]byte, hashLen)
  92. for block := 1; block <= numBlocks; block++ {
  93. // N.B.: || means concatenation, ^ means XOR
  94. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  95. // U_1 = PRF(password, salt || uint(i))
  96. prf.Reset()
  97. prf.Write(salt)
  98. buf[0] = byte(block >> 24)
  99. buf[1] = byte(block >> 16)
  100. buf[2] = byte(block >> 8)
  101. buf[3] = byte(block)
  102. prf.Write(buf[:4])
  103. dk = prf.Sum(dk)
  104. T := dk[len(dk)-hashLen:]
  105. copy(U, T)
  106. // U_n = PRF(password, U_(n-1))
  107. for n := 2; n <= iter; n++ {
  108. prf.Reset()
  109. prf.Write(U)
  110. U = U[:0]
  111. U = prf.Sum(U)
  112. for x := range U {
  113. T[x] ^= U[x]
  114. }
  115. }
  116. }
  117. return dk[:keyLen]
  118. }
  119. // verify time limit code
  120. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  121. if len(code) <= 18 {
  122. return false
  123. }
  124. // split code
  125. start := code[:12]
  126. lives := code[12:18]
  127. if d, err := com.StrTo(lives).Int(); err == nil {
  128. minutes = d
  129. }
  130. // right active code
  131. retCode := CreateTimeLimitCode(data, minutes, start)
  132. if retCode == code && minutes > 0 {
  133. // check time is expired or not
  134. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  135. now := time.Now()
  136. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  137. return true
  138. }
  139. }
  140. return false
  141. }
  142. const TimeLimitCodeLength = 12 + 6 + 40
  143. // create a time limit code
  144. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  145. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  146. format := "200601021504"
  147. var start, end time.Time
  148. var startStr, endStr string
  149. if startInf == nil {
  150. // Use now time create code
  151. start = time.Now()
  152. startStr = start.Format(format)
  153. } else {
  154. // use start string create code
  155. startStr = startInf.(string)
  156. start, _ = time.ParseInLocation(format, startStr, time.Local)
  157. startStr = start.Format(format)
  158. }
  159. end = start.Add(time.Minute * time.Duration(minutes))
  160. endStr = end.Format(format)
  161. // create sha1 encode string
  162. sh := sha1.New()
  163. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  164. encoded := hex.EncodeToString(sh.Sum(nil))
  165. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  166. return code
  167. }
  168. // HashEmail hashes email address to MD5 string.
  169. // https://en.gravatar.com/site/implement/hash/
  170. func HashEmail(email string) string {
  171. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  172. }
  173. // AvatarLink returns relative avatar link to the site domain by given email,
  174. // which includes app sub-url as prefix. However, it is possible
  175. // to return full URL if user enables Gravatar-like service.
  176. func AvatarLink(email string) (url string) {
  177. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  178. var err error
  179. url, err = setting.LibravatarService.FromEmail(email)
  180. if err != nil {
  181. log.Error(1, "LibravatarService.FromEmail: %v", err)
  182. }
  183. }
  184. if len(url) == 0 && !setting.DisableGravatar {
  185. url = setting.GravatarSource + HashEmail(email)
  186. }
  187. if len(url) == 0 {
  188. url = setting.AppSubUrl + "/img/avatar_default.png"
  189. }
  190. return url
  191. }
  192. // Seconds-based time units
  193. const (
  194. Minute = 60
  195. Hour = 60 * Minute
  196. Day = 24 * Hour
  197. Week = 7 * Day
  198. Month = 30 * Day
  199. Year = 12 * Month
  200. )
  201. func computeTimeDiff(diff int64) (int64, string) {
  202. diffStr := ""
  203. switch {
  204. case diff <= 0:
  205. diff = 0
  206. diffStr = "now"
  207. case diff < 2:
  208. diff = 0
  209. diffStr = "1 second"
  210. case diff < 1*Minute:
  211. diffStr = fmt.Sprintf("%d seconds", diff)
  212. diff = 0
  213. case diff < 2*Minute:
  214. diff -= 1 * Minute
  215. diffStr = "1 minute"
  216. case diff < 1*Hour:
  217. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  218. diff -= diff / Minute * Minute
  219. case diff < 2*Hour:
  220. diff -= 1 * Hour
  221. diffStr = "1 hour"
  222. case diff < 1*Day:
  223. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  224. diff -= diff / Hour * Hour
  225. case diff < 2*Day:
  226. diff -= 1 * Day
  227. diffStr = "1 day"
  228. case diff < 1*Week:
  229. diffStr = fmt.Sprintf("%d days", diff/Day)
  230. diff -= diff / Day * Day
  231. case diff < 2*Week:
  232. diff -= 1 * Week
  233. diffStr = "1 week"
  234. case diff < 1*Month:
  235. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  236. diff -= diff / Week * Week
  237. case diff < 2*Month:
  238. diff -= 1 * Month
  239. diffStr = "1 month"
  240. case diff < 1*Year:
  241. diffStr = fmt.Sprintf("%d months", diff/Month)
  242. diff -= diff / Month * Month
  243. case diff < 2*Year:
  244. diff -= 1 * Year
  245. diffStr = "1 year"
  246. default:
  247. diffStr = fmt.Sprintf("%d years", diff/Year)
  248. diff = 0
  249. }
  250. return diff, diffStr
  251. }
  252. // TimeSincePro calculates the time interval and generate full user-friendly string.
  253. func TimeSincePro(then time.Time) string {
  254. now := time.Now()
  255. diff := now.Unix() - then.Unix()
  256. if then.After(now) {
  257. return "future"
  258. }
  259. var timeStr, diffStr string
  260. for {
  261. if diff == 0 {
  262. break
  263. }
  264. diff, diffStr = computeTimeDiff(diff)
  265. timeStr += ", " + diffStr
  266. }
  267. return strings.TrimPrefix(timeStr, ", ")
  268. }
  269. func timeSince(then time.Time, lang string) string {
  270. now := time.Now()
  271. lbl := i18n.Tr(lang, "tool.ago")
  272. diff := now.Unix() - then.Unix()
  273. if then.After(now) {
  274. lbl = i18n.Tr(lang, "tool.from_now")
  275. diff = then.Unix() - now.Unix()
  276. }
  277. switch {
  278. case diff <= 0:
  279. return i18n.Tr(lang, "tool.now")
  280. case diff <= 2:
  281. return i18n.Tr(lang, "tool.1s", lbl)
  282. case diff < 1*Minute:
  283. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  284. case diff < 2*Minute:
  285. return i18n.Tr(lang, "tool.1m", lbl)
  286. case diff < 1*Hour:
  287. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  288. case diff < 2*Hour:
  289. return i18n.Tr(lang, "tool.1h", lbl)
  290. case diff < 1*Day:
  291. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  292. case diff < 2*Day:
  293. return i18n.Tr(lang, "tool.1d", lbl)
  294. case diff < 1*Week:
  295. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  296. case diff < 2*Week:
  297. return i18n.Tr(lang, "tool.1w", lbl)
  298. case diff < 1*Month:
  299. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  300. case diff < 2*Month:
  301. return i18n.Tr(lang, "tool.1mon", lbl)
  302. case diff < 1*Year:
  303. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  304. case diff < 2*Year:
  305. return i18n.Tr(lang, "tool.1y", lbl)
  306. default:
  307. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  308. }
  309. }
  310. func RawTimeSince(t time.Time, lang string) string {
  311. return timeSince(t, lang)
  312. }
  313. // TimeSince calculates the time interval and generate user-friendly string.
  314. func TimeSince(t time.Time, lang string) template.HTML {
  315. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  316. }
  317. const (
  318. Byte = 1
  319. KByte = Byte * 1024
  320. MByte = KByte * 1024
  321. GByte = MByte * 1024
  322. TByte = GByte * 1024
  323. PByte = TByte * 1024
  324. EByte = PByte * 1024
  325. )
  326. var bytesSizeTable = map[string]uint64{
  327. "b": Byte,
  328. "kb": KByte,
  329. "mb": MByte,
  330. "gb": GByte,
  331. "tb": TByte,
  332. "pb": PByte,
  333. "eb": EByte,
  334. }
  335. func logn(n, b float64) float64 {
  336. return math.Log(n) / math.Log(b)
  337. }
  338. func humanateBytes(s uint64, base float64, sizes []string) string {
  339. if s < 10 {
  340. return fmt.Sprintf("%dB", s)
  341. }
  342. e := math.Floor(logn(float64(s), base))
  343. suffix := sizes[int(e)]
  344. val := float64(s) / math.Pow(base, math.Floor(e))
  345. f := "%.0f"
  346. if val < 10 {
  347. f = "%.1f"
  348. }
  349. return fmt.Sprintf(f+"%s", val, suffix)
  350. }
  351. // FileSize calculates the file size and generate user-friendly string.
  352. func FileSize(s int64) string {
  353. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  354. return humanateBytes(uint64(s), 1024, sizes)
  355. }
  356. // Subtract deals with subtraction of all types of number.
  357. func Subtract(left interface{}, right interface{}) interface{} {
  358. var rleft, rright int64
  359. var fleft, fright float64
  360. var isInt bool = true
  361. switch left.(type) {
  362. case int:
  363. rleft = int64(left.(int))
  364. case int8:
  365. rleft = int64(left.(int8))
  366. case int16:
  367. rleft = int64(left.(int16))
  368. case int32:
  369. rleft = int64(left.(int32))
  370. case int64:
  371. rleft = left.(int64)
  372. case float32:
  373. fleft = float64(left.(float32))
  374. isInt = false
  375. case float64:
  376. fleft = left.(float64)
  377. isInt = false
  378. }
  379. switch right.(type) {
  380. case int:
  381. rright = int64(right.(int))
  382. case int8:
  383. rright = int64(right.(int8))
  384. case int16:
  385. rright = int64(right.(int16))
  386. case int32:
  387. rright = int64(right.(int32))
  388. case int64:
  389. rright = right.(int64)
  390. case float32:
  391. fright = float64(left.(float32))
  392. isInt = false
  393. case float64:
  394. fleft = left.(float64)
  395. isInt = false
  396. }
  397. if isInt {
  398. return rleft - rright
  399. } else {
  400. return fleft + float64(rleft) - (fright + float64(rright))
  401. }
  402. }
  403. // EllipsisString returns a truncated short string,
  404. // it appends '...' in the end of the length of string is too large.
  405. func EllipsisString(str string, length int) string {
  406. if len(str) < length {
  407. return str
  408. }
  409. return str[:length-3] + "..."
  410. }
  411. // TruncateString returns a truncated string with given limit,
  412. // it returns input string if length is not reached limit.
  413. func TruncateString(str string, limit int) string {
  414. if len(str) < limit {
  415. return str
  416. }
  417. return str[:limit]
  418. }
  419. // StringsToInt64s converts a slice of string to a slice of int64.
  420. func StringsToInt64s(strs []string) []int64 {
  421. ints := make([]int64, len(strs))
  422. for i := range strs {
  423. ints[i] = com.StrTo(strs[i]).MustInt64()
  424. }
  425. return ints
  426. }
  427. // Int64sToStrings converts a slice of int64 to a slice of string.
  428. func Int64sToStrings(ints []int64) []string {
  429. strs := make([]string, len(ints))
  430. for i := range ints {
  431. strs[i] = com.ToStr(ints[i])
  432. }
  433. return strs
  434. }
  435. // Int64sToMap converts a slice of int64 to a int64 map.
  436. func Int64sToMap(ints []int64) map[int64]bool {
  437. m := make(map[int64]bool)
  438. for _, i := range ints {
  439. m[i] = true
  440. }
  441. return m
  442. }
  443. // IsLetter reports whether the rune is a letter (category L).
  444. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  445. func IsLetter(ch rune) bool {
  446. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  447. }
  448. // IsTextFile returns true if file content format is plain text or empty.
  449. func IsTextFile(data []byte) bool {
  450. if len(data) == 0 {
  451. return true
  452. }
  453. return strings.Index(http.DetectContentType(data), "text/") != -1
  454. }
  455. func IsImageFile(data []byte) bool {
  456. return strings.Index(http.DetectContentType(data), "image/") != -1
  457. }
  458. func IsPDFFile(data []byte) bool {
  459. return strings.Index(http.DetectContentType(data), "application/pdf") != -1
  460. }