functions.go 5.3 KB

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