functions.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. "hasOAuth2Provider": func(provider string) bool {
  37. return config.Opts.OAuth2Provider() == provider
  38. },
  39. "hasAuthProxy": func() bool {
  40. return config.Opts.AuthProxyHeader() != ""
  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 mediaproxy.RewriteDocumentWithRelativeProxyURL(f.router, data)
  56. },
  57. "proxyURL": func(link string) string {
  58. mediaProxyMode := config.Opts.MediaProxyMode()
  59. if mediaProxyMode == "all" || (mediaProxyMode != "none" && !urllib.IsHTTPS(link)) {
  60. return mediaproxy.ProxifyRelativeURL(f.router, link)
  61. }
  62. return link
  63. },
  64. "mustBeProxyfied": func(mediaType string) bool {
  65. return slices.Contains(config.Opts.MediaProxyResourceTypes(), mediaType)
  66. },
  67. "domain": urllib.Domain,
  68. "hasPrefix": strings.HasPrefix,
  69. "contains": strings.Contains,
  70. "replace": func(str, old, new string) string {
  71. return strings.Replace(str, old, new, 1)
  72. },
  73. "isodate": func(ts time.Time) string {
  74. return ts.Format("2006-01-02 15:04:05")
  75. },
  76. "theme_color": model.ThemeColor,
  77. "icon": func(iconName string) template.HTML {
  78. return template.HTML(fmt.Sprintf(
  79. `<svg class="icon" aria-hidden="true"><use xlink:href="%s#icon-%s"/></svg>`,
  80. route.Path(f.router, "appIcon", "filename", "sprite.svg"),
  81. iconName,
  82. ))
  83. },
  84. "nonce": func() string {
  85. return crypto.GenerateRandomStringHex(16)
  86. },
  87. "deRef": func(i *int) int { return *i },
  88. "duration": duration,
  89. "urlEncode": url.PathEscape,
  90. // These functions are overrode at runtime after the parsing.
  91. "elapsed": func(timezone string, t time.Time) string {
  92. return ""
  93. },
  94. "t": func(key interface{}, args ...interface{}) string {
  95. return ""
  96. },
  97. "plural": func(key string, n int, args ...interface{}) string {
  98. return ""
  99. },
  100. }
  101. }
  102. func dict(values ...interface{}) (map[string]interface{}, error) {
  103. if len(values)%2 != 0 {
  104. return nil, fmt.Errorf("dict expects an even number of arguments")
  105. }
  106. dict := make(map[string]interface{}, len(values)/2)
  107. for i := 0; i < len(values); i += 2 {
  108. key, ok := values[i].(string)
  109. if !ok {
  110. return nil, fmt.Errorf("dict keys must be strings")
  111. }
  112. dict[key] = values[i+1]
  113. }
  114. return dict, nil
  115. }
  116. func hasKey(dict map[string]string, key string) bool {
  117. if value, found := dict[key]; found {
  118. return value != ""
  119. }
  120. return false
  121. }
  122. func truncate(str string, max int) string {
  123. runes := 0
  124. for i := range str {
  125. runes++
  126. if runes > max {
  127. return str[:i] + "…"
  128. }
  129. }
  130. return str
  131. }
  132. func isEmail(str string) bool {
  133. _, err := mail.ParseAddress(str)
  134. return err == nil
  135. }
  136. // Returns the duration in human readable format (hours and minutes).
  137. func duration(t time.Time) string {
  138. return durationImpl(t, time.Now())
  139. }
  140. // Accepts now argument for easy testing
  141. func durationImpl(t time.Time, now time.Time) string {
  142. if t.IsZero() {
  143. return ""
  144. }
  145. if diff := t.Sub(now); diff >= 0 {
  146. // Round to nearest second to get e.g. "14m56s" rather than "14m56.245483933s"
  147. return diff.Round(time.Second).String()
  148. }
  149. return ""
  150. }
  151. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  152. if t.IsZero() {
  153. return printer.Print("time_elapsed.not_yet")
  154. }
  155. now := timezone.Now(tz)
  156. t = timezone.Convert(tz, t)
  157. if now.Before(t) {
  158. return printer.Print("time_elapsed.not_yet")
  159. }
  160. diff := now.Sub(t)
  161. // Duration in seconds
  162. s := diff.Seconds()
  163. // Duration in days
  164. d := int(s / 86400)
  165. switch {
  166. case s < 60:
  167. return printer.Print("time_elapsed.now")
  168. case s < 3600:
  169. minutes := int(diff.Minutes())
  170. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  171. case s < 86400:
  172. hours := int(diff.Hours())
  173. return printer.Plural("time_elapsed.hours", hours, hours)
  174. case d == 1:
  175. return printer.Print("time_elapsed.yesterday")
  176. case d < 21:
  177. return printer.Plural("time_elapsed.days", d, d)
  178. case d < 31:
  179. weeks := int(math.Round(float64(d) / 7))
  180. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  181. case d < 365:
  182. months := int(math.Round(float64(d) / 30))
  183. return printer.Plural("time_elapsed.months", months, months)
  184. default:
  185. years := int(math.Round(float64(d) / 365))
  186. return printer.Plural("time_elapsed.years", years, years)
  187. }
  188. }
  189. func formatFileSize(b int64) string {
  190. const unit = 1024
  191. if b < unit {
  192. return fmt.Sprintf("%d B", b)
  193. }
  194. base := math.Log(float64(b)) / math.Log(unit)
  195. number := math.Pow(unit, base-math.Floor(base))
  196. return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
  197. }