functions.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. "formatFileSize": formatFileSize,
  29. "dict": dict,
  30. "hasKey": hasKey,
  31. "truncate": truncate,
  32. "isEmail": isEmail,
  33. "baseURL": func() string {
  34. return config.Opts.BaseURL()
  35. },
  36. "rootURL": func() string {
  37. return config.Opts.RootURL()
  38. },
  39. "hasOAuth2Provider": func(provider string) bool {
  40. return config.Opts.OAuth2Provider() == provider
  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. "noescape": func(str string) template.HTML {
  49. return template.HTML(str)
  50. },
  51. "proxyFilter": func(data string) string {
  52. return imageProxyFilter(f.router, data)
  53. },
  54. "proxyURL": func(link string) string {
  55. proxyImages := config.Opts.ProxyImages()
  56. if proxyImages == "all" || (proxyImages != "none" && !url.IsHTTPS(link)) {
  57. return proxify(f.router, link)
  58. }
  59. return link
  60. },
  61. "domain": func(websiteURL string) string {
  62. return url.Domain(websiteURL)
  63. },
  64. "hasPrefix": func(str, prefix string) bool {
  65. return strings.HasPrefix(str, prefix)
  66. },
  67. "contains": func(str, substr string) bool {
  68. return strings.Contains(str, substr)
  69. },
  70. "isodate": func(ts time.Time) string {
  71. return ts.Format("2006-01-02 15:04:05")
  72. },
  73. "theme_color": func(theme string) string {
  74. return model.ThemeColor(theme)
  75. },
  76. // These functions are overrided at runtime after the parsing.
  77. "elapsed": func(timezone string, t time.Time) string {
  78. return ""
  79. },
  80. "t": func(key interface{}, args ...interface{}) string {
  81. return ""
  82. },
  83. "plural": func(key string, n int, args ...interface{}) string {
  84. return ""
  85. },
  86. "timeToRead": func(content string) int {
  87. return 0
  88. },
  89. }
  90. }
  91. func dict(values ...interface{}) (map[string]interface{}, error) {
  92. if len(values)%2 != 0 {
  93. return nil, fmt.Errorf("dict expects an even number of arguments")
  94. }
  95. dict := make(map[string]interface{}, len(values)/2)
  96. for i := 0; i < len(values); i += 2 {
  97. key, ok := values[i].(string)
  98. if !ok {
  99. return nil, fmt.Errorf("dict keys must be strings")
  100. }
  101. dict[key] = values[i+1]
  102. }
  103. return dict, nil
  104. }
  105. func hasKey(dict map[string]string, key string) bool {
  106. if value, found := dict[key]; found {
  107. return value != ""
  108. }
  109. return false
  110. }
  111. func truncate(str string, max int) string {
  112. runes := 0
  113. for i := range str {
  114. runes++
  115. if runes > max {
  116. return str[:i] + "…"
  117. }
  118. }
  119. return str
  120. }
  121. func isEmail(str string) bool {
  122. _, err := mail.ParseAddress(str)
  123. if err != nil {
  124. return false
  125. }
  126. return true
  127. }
  128. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  129. if t.IsZero() {
  130. return printer.Printf("time_elapsed.not_yet")
  131. }
  132. now := timezone.Now(tz)
  133. t = timezone.Convert(tz, t)
  134. if now.Before(t) {
  135. return printer.Printf("time_elapsed.not_yet")
  136. }
  137. diff := now.Sub(t)
  138. // Duration in seconds
  139. s := diff.Seconds()
  140. // Duration in days
  141. d := int(s / 86400)
  142. switch {
  143. case s < 60:
  144. return printer.Printf("time_elapsed.now")
  145. case s < 3600:
  146. minutes := int(diff.Minutes())
  147. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  148. case s < 86400:
  149. hours := int(diff.Hours())
  150. return printer.Plural("time_elapsed.hours", hours, hours)
  151. case d == 1:
  152. return printer.Printf("time_elapsed.yesterday")
  153. case d < 21:
  154. return printer.Plural("time_elapsed.days", d, d)
  155. case d < 31:
  156. weeks := int(math.Round(float64(d) / 7))
  157. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  158. case d < 365:
  159. months := int(math.Round(float64(d) / 30))
  160. return printer.Plural("time_elapsed.months", months, months)
  161. default:
  162. years := int(math.Round(float64(d) / 365))
  163. return printer.Plural("time_elapsed.years", years, years)
  164. }
  165. }
  166. func imageProxyFilter(router *mux.Router, data string) string {
  167. proxyImages := config.Opts.ProxyImages()
  168. if proxyImages == "none" {
  169. return data
  170. }
  171. doc, err := goquery.NewDocumentFromReader(strings.NewReader(data))
  172. if err != nil {
  173. return data
  174. }
  175. doc.Find("img").Each(func(i int, img *goquery.Selection) {
  176. if srcAttr, ok := img.Attr("src"); ok {
  177. if proxyImages == "all" || !url.IsHTTPS(srcAttr) {
  178. img.SetAttr("src", proxify(router, srcAttr))
  179. }
  180. }
  181. })
  182. output, _ := doc.Find("body").First().Html()
  183. return output
  184. }
  185. func proxify(router *mux.Router, link string) string {
  186. // We use base64 url encoding to avoid slash in the URL.
  187. return route.Path(router, "proxy", "encodedURL", base64.URLEncoding.EncodeToString([]byte(link)))
  188. }
  189. func formatFileSize(b int64) string {
  190. const unit = 1024
  191. if b < unit {
  192. return fmt.Sprintf("%d B", b)
  193. }
  194. div, exp := int64(unit), 0
  195. for n := b / unit; n >= unit; n /= unit {
  196. div *= unit
  197. exp++
  198. }
  199. return fmt.Sprintf("%.1f %ciB",
  200. float64(b)/float64(div), "KMGTPE"[exp])
  201. }
  202. func timeToRead(content string) int {
  203. nbOfWords := len(strings.Fields(content))
  204. return int(math.Ceil(float64(nbOfWords) / 265))
  205. }