functions.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. "net/url"
  10. "slices"
  11. "strings"
  12. "time"
  13. "miniflux.app/v2/internal/config"
  14. "miniflux.app/v2/internal/crypto"
  15. "miniflux.app/v2/internal/http/route"
  16. "miniflux.app/v2/internal/locale"
  17. "miniflux.app/v2/internal/mediaproxy"
  18. "miniflux.app/v2/internal/model"
  19. "miniflux.app/v2/internal/timezone"
  20. "miniflux.app/v2/internal/urllib"
  21. "github.com/gorilla/mux"
  22. )
  23. type funcMap struct {
  24. router *mux.Router
  25. }
  26. // Map returns a map of template functions that are compiled during template parsing.
  27. func (f *funcMap) Map() template.FuncMap {
  28. return template.FuncMap{
  29. "contains": strings.Contains,
  30. "csp": csp,
  31. "startsWith": strings.HasPrefix,
  32. "formatFileSize": formatFileSize,
  33. "dict": dict,
  34. "truncate": truncate,
  35. "isEmail": isEmail,
  36. "baseURL": config.Opts.BaseURL,
  37. "rootURL": config.Opts.RootURL,
  38. "disableLocalAuth": config.Opts.DisableLocalAuth,
  39. "oidcProviderName": config.Opts.OAuth2OIDCProviderName,
  40. "hasOAuth2Provider": func(provider string) bool {
  41. return config.Opts.OAuth2Provider() == provider
  42. },
  43. "hasAuthProxy": func() bool {
  44. return config.Opts.AuthProxyHeader() != ""
  45. },
  46. "route": func(name string, args ...any) string {
  47. return route.Path(f.router, name, args...)
  48. },
  49. "safeURL": func(url string) template.URL {
  50. return template.URL(url)
  51. },
  52. "safeCSS": func(str string) template.CSS {
  53. return template.CSS(str)
  54. },
  55. "safeJS": func(str string) template.JS {
  56. return template.JS(str)
  57. },
  58. "safeHTML": func(str string) template.HTML {
  59. return template.HTML(str)
  60. },
  61. "proxyFilter": func(data string) string {
  62. return mediaproxy.RewriteDocumentWithRelativeProxyURL(f.router, data)
  63. },
  64. "proxyURL": func(link string) string {
  65. mediaProxyMode := config.Opts.MediaProxyMode()
  66. if mediaProxyMode == "all" || (mediaProxyMode != "none" && !urllib.IsHTTPS(link)) {
  67. return mediaproxy.ProxifyRelativeURL(f.router, link)
  68. }
  69. return link
  70. },
  71. "mustBeProxyfied": func(mediaType string) bool {
  72. return slices.Contains(config.Opts.MediaProxyResourceTypes(), mediaType)
  73. },
  74. "domain": urllib.Domain,
  75. "replace": func(str, old, new string) string {
  76. return strings.Replace(str, old, new, 1)
  77. },
  78. "isodate": func(ts time.Time) string {
  79. return ts.Format("2006-01-02 15:04:05")
  80. },
  81. "theme_color": model.ThemeColor,
  82. "icon": func(iconName string) template.HTML {
  83. return template.HTML(fmt.Sprintf(
  84. `<svg class="icon" aria-hidden="true"><use 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. "deRef": func(i *int) int { return *i },
  93. "duration": duration,
  94. "urlEncode": url.PathEscape,
  95. "subtract": func(a, b int) int {
  96. return a - b
  97. },
  98. // These functions are overridden at runtime after parsing.
  99. "elapsed": func(timezone string, t time.Time) string {
  100. return ""
  101. },
  102. "t": func(key any, args ...any) string {
  103. return ""
  104. },
  105. "plural": func(key string, n int, args ...any) string {
  106. return ""
  107. },
  108. }
  109. }
  110. func csp(user *model.User, nonce string) string {
  111. policies := map[string]string{
  112. "default-src": "'none'",
  113. "frame-src": "*",
  114. "img-src": "* data:",
  115. "manifest-src": "'self'",
  116. "media-src": "*",
  117. "require-trusted-types-for": "'script'",
  118. "script-src": "'nonce-" + nonce + "' 'strict-dynamic'",
  119. "style-src": "'nonce-" + nonce + "'",
  120. "trusted-types": "html url",
  121. "connect-src": "'self'",
  122. }
  123. if user != nil {
  124. if user.ExternalFontHosts != "" {
  125. policies["font-src"] = user.ExternalFontHosts
  126. if user.Stylesheet != "" {
  127. policies["style-src"] += " " + user.ExternalFontHosts
  128. }
  129. }
  130. }
  131. var policy strings.Builder
  132. for key, value := range policies {
  133. policy.WriteString(key)
  134. policy.WriteString(" ")
  135. policy.WriteString(value)
  136. policy.WriteString("; ")
  137. }
  138. return `<meta http-equiv="Content-Security-Policy" content="` + policy.String() + `">`
  139. }
  140. func dict(values ...any) (map[string]any, error) {
  141. if len(values)%2 != 0 {
  142. return nil, fmt.Errorf("dict expects an even number of arguments")
  143. }
  144. dict := make(map[string]any, len(values)/2)
  145. for i := 0; i < len(values); i += 2 {
  146. key, ok := values[i].(string)
  147. if !ok {
  148. return nil, fmt.Errorf("dict keys must be strings")
  149. }
  150. dict[key] = values[i+1]
  151. }
  152. return dict, nil
  153. }
  154. func truncate(str string, max int) string {
  155. if runes := []rune(str); len(runes) > max {
  156. return string(runes[:max]) + "…"
  157. }
  158. return str
  159. }
  160. func isEmail(str string) bool {
  161. _, err := mail.ParseAddress(str)
  162. return err == nil
  163. }
  164. // Returns the duration in human readable format (hours and minutes).
  165. func duration(t time.Time) string {
  166. return durationImpl(t, time.Now())
  167. }
  168. // Accepts now argument for easy testing
  169. func durationImpl(t time.Time, now time.Time) string {
  170. if t.IsZero() {
  171. return ""
  172. }
  173. if diff := t.Sub(now); diff >= 0 {
  174. // Round to nearest second to get e.g. "14m56s" rather than "14m56.245483933s"
  175. return diff.Round(time.Second).String()
  176. }
  177. return ""
  178. }
  179. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  180. if t.IsZero() {
  181. return printer.Print("time_elapsed.not_yet")
  182. }
  183. now := timezone.Now(tz)
  184. t = timezone.Convert(tz, t)
  185. if now.Before(t) {
  186. return printer.Print("time_elapsed.not_yet")
  187. }
  188. diff := now.Sub(t)
  189. // Duration in seconds
  190. s := diff.Seconds()
  191. // Duration in days
  192. d := int(s / 86400)
  193. switch {
  194. case s < 60:
  195. return printer.Print("time_elapsed.now")
  196. case s < 3600:
  197. minutes := int(diff.Minutes())
  198. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  199. case s < 86400:
  200. hours := int(diff.Hours())
  201. return printer.Plural("time_elapsed.hours", hours, hours)
  202. case d == 1:
  203. return printer.Print("time_elapsed.yesterday")
  204. case d < 21:
  205. return printer.Plural("time_elapsed.days", d, d)
  206. case d < 31:
  207. weeks := int(math.Round(float64(d) / 7))
  208. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  209. case d < 365:
  210. months := int(math.Round(float64(d) / 30))
  211. return printer.Plural("time_elapsed.months", months, months)
  212. default:
  213. years := int(math.Round(float64(d) / 365))
  214. return printer.Plural("time_elapsed.years", years, years)
  215. }
  216. }
  217. func formatFileSize(b int64) string {
  218. const unit = 1024
  219. if b < unit {
  220. return fmt.Sprintf("%d B", b)
  221. }
  222. base := math.Log(float64(b)) / math.Log(unit)
  223. number := math.Pow(unit, base-math.Floor(base))
  224. return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
  225. }