functions.go 5.1 KB

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