functions.go 5.7 KB

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