functions.go 4.8 KB

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