functions.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package template // import "miniflux.app/v2/internal/template"
  4. import (
  5. "fmt"
  6. "html/template"
  7. "math"
  8. "net/mail"
  9. "slices"
  10. "strings"
  11. "time"
  12. "miniflux.app/v2/internal/config"
  13. "miniflux.app/v2/internal/crypto"
  14. "miniflux.app/v2/internal/http/route"
  15. "miniflux.app/v2/internal/locale"
  16. "miniflux.app/v2/internal/model"
  17. "miniflux.app/v2/internal/proxy"
  18. "miniflux.app/v2/internal/timezone"
  19. "miniflux.app/v2/internal/urllib"
  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" && !urllib.IsHTTPS(link)) {
  63. return proxy.ProxifyURL(f.router, link)
  64. }
  65. return link
  66. },
  67. "mustBeProxyfied": func(mediaType string) bool {
  68. return slices.Contains(config.Opts.ProxyMediaTypes(), mediaType)
  69. },
  70. "domain": func(websiteURL string) string {
  71. return urllib.Domain(websiteURL)
  72. },
  73. "hasPrefix": func(str, prefix string) bool {
  74. return strings.HasPrefix(str, prefix)
  75. },
  76. "contains": func(str, substr string) bool {
  77. return strings.Contains(str, substr)
  78. },
  79. "replace": func(str, old, new string) string {
  80. return strings.Replace(str, old, new, 1)
  81. },
  82. "isodate": func(ts time.Time) string {
  83. return ts.Format("2006-01-02 15:04:05")
  84. },
  85. "theme_color": func(theme, colorScheme string) string {
  86. return model.ThemeColor(theme, colorScheme)
  87. },
  88. "icon": func(iconName string) template.HTML {
  89. return template.HTML(fmt.Sprintf(
  90. `<svg class="icon" aria-hidden="true"><use xlink:href="%s#icon-%s"/></svg>`,
  91. route.Path(f.router, "appIcon", "filename", "sprite.svg"),
  92. iconName,
  93. ))
  94. },
  95. "nonce": func() string {
  96. return crypto.GenerateRandomStringHex(16)
  97. },
  98. "deRef": func(i *int) int { return *i },
  99. "duration": duration,
  100. // These functions are overrode at runtime after the parsing.
  101. "elapsed": func(timezone string, t time.Time) string {
  102. return ""
  103. },
  104. "t": func(key interface{}, args ...interface{}) string {
  105. return ""
  106. },
  107. "plural": func(key string, n int, args ...interface{}) string {
  108. return ""
  109. },
  110. }
  111. }
  112. func dict(values ...interface{}) (map[string]interface{}, error) {
  113. if len(values)%2 != 0 {
  114. return nil, fmt.Errorf("dict expects an even number of arguments")
  115. }
  116. dict := make(map[string]interface{}, len(values)/2)
  117. for i := 0; i < len(values); i += 2 {
  118. key, ok := values[i].(string)
  119. if !ok {
  120. return nil, fmt.Errorf("dict keys must be strings")
  121. }
  122. dict[key] = values[i+1]
  123. }
  124. return dict, nil
  125. }
  126. func hasKey(dict map[string]string, key string) bool {
  127. if value, found := dict[key]; found {
  128. return value != ""
  129. }
  130. return false
  131. }
  132. func truncate(str string, max int) string {
  133. runes := 0
  134. for i := range str {
  135. runes++
  136. if runes > max {
  137. return str[:i] + "…"
  138. }
  139. }
  140. return str
  141. }
  142. func isEmail(str string) bool {
  143. _, err := mail.ParseAddress(str)
  144. return err == nil
  145. }
  146. // Returns the duration in human readable format (hours and minutes).
  147. func duration(t time.Time) string {
  148. return durationImpl(t, time.Now())
  149. }
  150. // Accepts now argument for easy testing
  151. func durationImpl(t time.Time, now time.Time) string {
  152. if t.IsZero() {
  153. return ""
  154. }
  155. diff := t.Sub(now)
  156. if diff < 0 {
  157. return ""
  158. }
  159. // Round to nearest second to get e.g. "14m56s" rather than "14m56.245483933s"
  160. return diff.Round(time.Second).String()
  161. }
  162. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  163. if t.IsZero() {
  164. return printer.Printf("time_elapsed.not_yet")
  165. }
  166. now := timezone.Now(tz)
  167. t = timezone.Convert(tz, t)
  168. if now.Before(t) {
  169. return printer.Printf("time_elapsed.not_yet")
  170. }
  171. diff := now.Sub(t)
  172. // Duration in seconds
  173. s := diff.Seconds()
  174. // Duration in days
  175. d := int(s / 86400)
  176. switch {
  177. case s < 60:
  178. return printer.Printf("time_elapsed.now")
  179. case s < 3600:
  180. minutes := int(diff.Minutes())
  181. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  182. case s < 86400:
  183. hours := int(diff.Hours())
  184. return printer.Plural("time_elapsed.hours", hours, hours)
  185. case d == 1:
  186. return printer.Printf("time_elapsed.yesterday")
  187. case d < 21:
  188. return printer.Plural("time_elapsed.days", d, d)
  189. case d < 31:
  190. weeks := int(math.Round(float64(d) / 7))
  191. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  192. case d < 365:
  193. months := int(math.Round(float64(d) / 30))
  194. return printer.Plural("time_elapsed.months", months, months)
  195. default:
  196. years := int(math.Round(float64(d) / 365))
  197. return printer.Plural("time_elapsed.years", years, years)
  198. }
  199. }
  200. func formatFileSize(b int64) string {
  201. const unit = 1024
  202. if b < unit {
  203. return fmt.Sprintf("%d B", b)
  204. }
  205. div, exp := int64(unit), 0
  206. for n := b / unit; n >= unit; n /= unit {
  207. div *= unit
  208. exp++
  209. }
  210. return fmt.Sprintf("%.1f %ciB",
  211. float64(b)/float64(div), "KMGTPE"[exp])
  212. }