functions.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. "formatFileSize": formatFileSize,
  30. "dict": dict,
  31. "hasKey": hasKey,
  32. "truncate": truncate,
  33. "isEmail": isEmail,
  34. "baseURL": config.Opts.BaseURL,
  35. "rootURL": config.Opts.RootURL,
  36. "disableLocalAuth": config.Opts.DisableLocalAuth,
  37. "oidcProviderName": config.Opts.OIDCProviderName,
  38. "hasOAuth2Provider": func(provider string) bool {
  39. return config.Opts.OAuth2Provider() == provider
  40. },
  41. "hasAuthProxy": func() bool {
  42. return config.Opts.AuthProxyHeader() != ""
  43. },
  44. "route": func(name string, args ...interface{}) string {
  45. return route.Path(f.router, name, args...)
  46. },
  47. "safeURL": func(url string) template.URL {
  48. return template.URL(url)
  49. },
  50. "safeCSS": func(str string) template.CSS {
  51. return template.CSS(str)
  52. },
  53. "noescape": func(str string) template.HTML {
  54. return template.HTML(str)
  55. },
  56. "proxyFilter": func(data string) string {
  57. return mediaproxy.RewriteDocumentWithRelativeProxyURL(f.router, data)
  58. },
  59. "proxyURL": func(link string) string {
  60. mediaProxyMode := config.Opts.MediaProxyMode()
  61. if mediaProxyMode == "all" || (mediaProxyMode != "none" && !urllib.IsHTTPS(link)) {
  62. return mediaproxy.ProxifyRelativeURL(f.router, link)
  63. }
  64. return link
  65. },
  66. "mustBeProxyfied": func(mediaType string) bool {
  67. return slices.Contains(config.Opts.MediaProxyResourceTypes(), mediaType)
  68. },
  69. "domain": urllib.Domain,
  70. "hasPrefix": strings.HasPrefix,
  71. "contains": strings.Contains,
  72. "replace": func(str, old, new string) string {
  73. return strings.Replace(str, old, new, 1)
  74. },
  75. "isodate": func(ts time.Time) string {
  76. return ts.Format("2006-01-02 15:04:05")
  77. },
  78. "theme_color": model.ThemeColor,
  79. "icon": func(iconName string) template.HTML {
  80. return template.HTML(fmt.Sprintf(
  81. `<svg class="icon" aria-hidden="true"><use xlink:href="%s#icon-%s"/></svg>`,
  82. route.Path(f.router, "appIcon", "filename", "sprite.svg"),
  83. iconName,
  84. ))
  85. },
  86. "nonce": func() string {
  87. return crypto.GenerateRandomStringHex(16)
  88. },
  89. "deRef": func(i *int) int { return *i },
  90. "duration": duration,
  91. "urlEncode": url.PathEscape,
  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. // Returns the duration in human readable format (hours and minutes).
  139. func duration(t time.Time) string {
  140. return durationImpl(t, time.Now())
  141. }
  142. // Accepts now argument for easy testing
  143. func durationImpl(t time.Time, now time.Time) string {
  144. if t.IsZero() {
  145. return ""
  146. }
  147. if diff := t.Sub(now); diff >= 0 {
  148. // Round to nearest second to get e.g. "14m56s" rather than "14m56.245483933s"
  149. return diff.Round(time.Second).String()
  150. }
  151. return ""
  152. }
  153. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  154. if t.IsZero() {
  155. return printer.Print("time_elapsed.not_yet")
  156. }
  157. now := timezone.Now(tz)
  158. t = timezone.Convert(tz, t)
  159. if now.Before(t) {
  160. return printer.Print("time_elapsed.not_yet")
  161. }
  162. diff := now.Sub(t)
  163. // Duration in seconds
  164. s := diff.Seconds()
  165. // Duration in days
  166. d := int(s / 86400)
  167. switch {
  168. case s < 60:
  169. return printer.Print("time_elapsed.now")
  170. case s < 3600:
  171. minutes := int(diff.Minutes())
  172. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  173. case s < 86400:
  174. hours := int(diff.Hours())
  175. return printer.Plural("time_elapsed.hours", hours, hours)
  176. case d == 1:
  177. return printer.Print("time_elapsed.yesterday")
  178. case d < 21:
  179. return printer.Plural("time_elapsed.days", d, d)
  180. case d < 31:
  181. weeks := int(math.Round(float64(d) / 7))
  182. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  183. case d < 365:
  184. months := int(math.Round(float64(d) / 30))
  185. return printer.Plural("time_elapsed.months", months, months)
  186. default:
  187. years := int(math.Round(float64(d) / 365))
  188. return printer.Plural("time_elapsed.years", years, years)
  189. }
  190. }
  191. func formatFileSize(b int64) string {
  192. const unit = 1024
  193. if b < unit {
  194. return fmt.Sprintf("%d B", b)
  195. }
  196. base := math.Log(float64(b)) / math.Log(unit)
  197. number := math.Pow(unit, base-math.Floor(base))
  198. return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
  199. }