functions.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package template // import "miniflux.app/template"
  5. import (
  6. "fmt"
  7. "html/template"
  8. "math"
  9. "net/mail"
  10. "strings"
  11. "time"
  12. "unicode/utf8"
  13. "miniflux.app/config"
  14. "miniflux.app/http/route"
  15. "miniflux.app/locale"
  16. "miniflux.app/model"
  17. "miniflux.app/proxy"
  18. "miniflux.app/reader/sanitizer"
  19. "miniflux.app/timezone"
  20. "miniflux.app/url"
  21. "github.com/gorilla/mux"
  22. "github.com/rylans/getlang"
  23. )
  24. type funcMap struct {
  25. router *mux.Router
  26. }
  27. // Map returns a map of template functions that are compiled during template parsing.
  28. func (f *funcMap) Map() template.FuncMap {
  29. return template.FuncMap{
  30. "formatFileSize": formatFileSize,
  31. "dict": dict,
  32. "hasKey": hasKey,
  33. "truncate": truncate,
  34. "isEmail": isEmail,
  35. "baseURL": func() string {
  36. return config.Opts.BaseURL()
  37. },
  38. "rootURL": func() string {
  39. return config.Opts.RootURL()
  40. },
  41. "hasOAuth2Provider": func(provider string) bool {
  42. return config.Opts.OAuth2Provider() == provider
  43. },
  44. "route": func(name string, args ...interface{}) string {
  45. return route.Path(f.router, name, args...)
  46. },
  47. "safeURL": func(url string) template.URL {
  48. return template.URL(url)
  49. },
  50. "noescape": func(str string) template.HTML {
  51. return template.HTML(str)
  52. },
  53. "proxyFilter": func(data string) string {
  54. return proxy.ImageProxyRewriter(f.router, data)
  55. },
  56. "proxyURL": func(link string) string {
  57. proxyImages := config.Opts.ProxyImages()
  58. if proxyImages == "all" || (proxyImages != "none" && !url.IsHTTPS(link)) {
  59. return proxy.ProxifyURL(f.router, link)
  60. }
  61. return link
  62. },
  63. "domain": func(websiteURL string) string {
  64. return url.Domain(websiteURL)
  65. },
  66. "hasPrefix": func(str, prefix string) bool {
  67. return strings.HasPrefix(str, prefix)
  68. },
  69. "contains": func(str, substr string) bool {
  70. return strings.Contains(str, substr)
  71. },
  72. "isodate": func(ts time.Time) string {
  73. return ts.Format("2006-01-02 15:04:05")
  74. },
  75. "theme_color": func(theme string) string {
  76. return model.ThemeColor(theme)
  77. },
  78. // These functions are overrided at runtime after the parsing.
  79. "elapsed": func(timezone string, t time.Time) string {
  80. return ""
  81. },
  82. "t": func(key interface{}, args ...interface{}) string {
  83. return ""
  84. },
  85. "plural": func(key string, n int, args ...interface{}) string {
  86. return ""
  87. },
  88. "timeToRead": func(content string) int {
  89. return 0
  90. },
  91. }
  92. }
  93. func dict(values ...interface{}) (map[string]interface{}, error) {
  94. if len(values)%2 != 0 {
  95. return nil, fmt.Errorf("dict expects an even number of arguments")
  96. }
  97. dict := make(map[string]interface{}, len(values)/2)
  98. for i := 0; i < len(values); i += 2 {
  99. key, ok := values[i].(string)
  100. if !ok {
  101. return nil, fmt.Errorf("dict keys must be strings")
  102. }
  103. dict[key] = values[i+1]
  104. }
  105. return dict, nil
  106. }
  107. func hasKey(dict map[string]string, key string) bool {
  108. if value, found := dict[key]; found {
  109. return value != ""
  110. }
  111. return false
  112. }
  113. func truncate(str string, max int) string {
  114. runes := 0
  115. for i := range str {
  116. runes++
  117. if runes > max {
  118. return str[:i] + "…"
  119. }
  120. }
  121. return str
  122. }
  123. func isEmail(str string) bool {
  124. _, err := mail.ParseAddress(str)
  125. if err != nil {
  126. return false
  127. }
  128. return true
  129. }
  130. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  131. if t.IsZero() {
  132. return printer.Printf("time_elapsed.not_yet")
  133. }
  134. now := timezone.Now(tz)
  135. t = timezone.Convert(tz, t)
  136. if now.Before(t) {
  137. return printer.Printf("time_elapsed.not_yet")
  138. }
  139. diff := now.Sub(t)
  140. // Duration in seconds
  141. s := diff.Seconds()
  142. // Duration in days
  143. d := int(s / 86400)
  144. switch {
  145. case s < 60:
  146. return printer.Printf("time_elapsed.now")
  147. case s < 3600:
  148. minutes := int(diff.Minutes())
  149. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  150. case s < 86400:
  151. hours := int(diff.Hours())
  152. return printer.Plural("time_elapsed.hours", hours, hours)
  153. case d == 1:
  154. return printer.Printf("time_elapsed.yesterday")
  155. case d < 21:
  156. return printer.Plural("time_elapsed.days", d, d)
  157. case d < 31:
  158. weeks := int(math.Round(float64(d) / 7))
  159. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  160. case d < 365:
  161. months := int(math.Round(float64(d) / 30))
  162. return printer.Plural("time_elapsed.months", months, months)
  163. default:
  164. years := int(math.Round(float64(d) / 365))
  165. return printer.Plural("time_elapsed.years", years, years)
  166. }
  167. }
  168. func formatFileSize(b int64) string {
  169. const unit = 1024
  170. if b < unit {
  171. return fmt.Sprintf("%d B", b)
  172. }
  173. div, exp := int64(unit), 0
  174. for n := b / unit; n >= unit; n /= unit {
  175. div *= unit
  176. exp++
  177. }
  178. return fmt.Sprintf("%.1f %ciB",
  179. float64(b)/float64(div), "KMGTPE"[exp])
  180. }
  181. func timeToRead(content string) int {
  182. sanitizedContent := sanitizer.StripTags(content)
  183. languageInfo := getlang.FromString(sanitizedContent)
  184. var timeToReadInt int
  185. if languageInfo.LanguageCode() == "ko" || languageInfo.LanguageCode() == "zh" || languageInfo.LanguageCode() == "jp" {
  186. timeToReadInt = int(math.Ceil(float64(utf8.RuneCountInString(sanitizedContent)) / 500))
  187. } else {
  188. nbOfWords := len(strings.Fields(sanitizedContent))
  189. timeToReadInt = int(math.Ceil(float64(nbOfWords) / 265))
  190. }
  191. return timeToReadInt
  192. }