functions.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package template // import "miniflux.app/template"
  5. import (
  6. "encoding/base64"
  7. "fmt"
  8. "html/template"
  9. "math"
  10. "net/mail"
  11. "strings"
  12. "time"
  13. "miniflux.app/config"
  14. "miniflux.app/http/route"
  15. "miniflux.app/locale"
  16. "miniflux.app/model"
  17. "miniflux.app/timezone"
  18. "miniflux.app/url"
  19. "github.com/PuerkitoBio/goquery"
  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. "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. "route": func(name string, args ...interface{}) string {
  42. return route.Path(f.router, name, args...)
  43. },
  44. "noescape": func(str string) template.HTML {
  45. return template.HTML(str)
  46. },
  47. "proxyFilter": func(data string) string {
  48. return imageProxyFilter(f.router, data)
  49. },
  50. "proxyURL": func(link string) string {
  51. proxyImages := config.Opts.ProxyImages()
  52. if proxyImages == "all" || (proxyImages != "none" && !url.IsHTTPS(link)) {
  53. return proxify(f.router, link)
  54. }
  55. return link
  56. },
  57. "domain": func(websiteURL string) string {
  58. return url.Domain(websiteURL)
  59. },
  60. "hasPrefix": func(str, prefix string) bool {
  61. return strings.HasPrefix(str, prefix)
  62. },
  63. "contains": func(str, substr string) bool {
  64. return strings.Contains(str, substr)
  65. },
  66. "isodate": func(ts time.Time) string {
  67. return ts.Format("2006-01-02 15:04:05")
  68. },
  69. "theme_color": func(theme string) string {
  70. return model.ThemeColor(theme)
  71. },
  72. // These functions are overrided at runtime after the parsing.
  73. "elapsed": func(timezone string, t time.Time) string {
  74. return ""
  75. },
  76. "t": func(key interface{}, args ...interface{}) string {
  77. return ""
  78. },
  79. "plural": func(key string, n int, args ...interface{}) string {
  80. return ""
  81. },
  82. }
  83. }
  84. func dict(values ...interface{}) (map[string]interface{}, error) {
  85. if len(values)%2 != 0 {
  86. return nil, fmt.Errorf("dict expects an even number of arguments")
  87. }
  88. dict := make(map[string]interface{}, len(values)/2)
  89. for i := 0; i < len(values); i += 2 {
  90. key, ok := values[i].(string)
  91. if !ok {
  92. return nil, fmt.Errorf("dict keys must be strings")
  93. }
  94. dict[key] = values[i+1]
  95. }
  96. return dict, nil
  97. }
  98. func hasKey(dict map[string]string, key string) bool {
  99. if value, found := dict[key]; found {
  100. return value != ""
  101. }
  102. return false
  103. }
  104. func truncate(str string, max int) string {
  105. runes := 0
  106. for i := range str {
  107. runes++
  108. if runes > max {
  109. return str[:i] + "…"
  110. }
  111. }
  112. return str
  113. }
  114. func isEmail(str string) bool {
  115. _, err := mail.ParseAddress(str)
  116. if err != nil {
  117. return false
  118. }
  119. return true
  120. }
  121. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  122. if t.IsZero() {
  123. return printer.Printf("time_elapsed.not_yet")
  124. }
  125. now := timezone.Now(tz)
  126. t = timezone.Convert(tz, t)
  127. if now.Before(t) {
  128. return printer.Printf("time_elapsed.not_yet")
  129. }
  130. diff := now.Sub(t)
  131. // Duration in seconds
  132. s := diff.Seconds()
  133. // Duration in days
  134. d := int(s / 86400)
  135. switch {
  136. case s < 60:
  137. return printer.Printf("time_elapsed.now")
  138. case s < 3600:
  139. minutes := int(diff.Minutes())
  140. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  141. case s < 86400:
  142. hours := int(diff.Hours())
  143. return printer.Plural("time_elapsed.hours", hours, hours)
  144. case d == 1:
  145. return printer.Printf("time_elapsed.yesterday")
  146. case d < 21:
  147. return printer.Plural("time_elapsed.days", d, d)
  148. case d < 31:
  149. weeks := int(math.Round(float64(d) / 7))
  150. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  151. case d < 365:
  152. months := int(math.Round(float64(d) / 30))
  153. return printer.Plural("time_elapsed.months", months, months)
  154. default:
  155. years := int(math.Round(float64(d) / 365))
  156. return printer.Plural("time_elapsed.years", years, years)
  157. }
  158. }
  159. func imageProxyFilter(router *mux.Router, data string) string {
  160. proxyImages := config.Opts.ProxyImages()
  161. if proxyImages == "none" {
  162. return data
  163. }
  164. doc, err := goquery.NewDocumentFromReader(strings.NewReader(data))
  165. if err != nil {
  166. return data
  167. }
  168. doc.Find("img").Each(func(i int, img *goquery.Selection) {
  169. if srcAttr, ok := img.Attr("src"); ok {
  170. if proxyImages == "all" || !url.IsHTTPS(srcAttr) {
  171. img.SetAttr("src", proxify(router, srcAttr))
  172. }
  173. }
  174. })
  175. output, _ := doc.Find("body").First().Html()
  176. return output
  177. }
  178. func proxify(router *mux.Router, link string) string {
  179. // We use base64 url encoding to avoid slash in the URL.
  180. return route.Path(router, "proxy", "encodedURL", base64.URLEncoding.EncodeToString([]byte(link)))
  181. }