functions.go 6.0 KB

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