processor.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 processor
  5. import (
  6. "errors"
  7. "fmt"
  8. "math"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "unicode/utf8"
  14. "miniflux.app/config"
  15. "miniflux.app/http/client"
  16. "miniflux.app/logger"
  17. "miniflux.app/metric"
  18. "miniflux.app/model"
  19. "miniflux.app/reader/browser"
  20. "miniflux.app/reader/rewrite"
  21. "miniflux.app/reader/sanitizer"
  22. "miniflux.app/reader/scraper"
  23. "miniflux.app/storage"
  24. "github.com/PuerkitoBio/goquery"
  25. "github.com/rylans/getlang"
  26. )
  27. var (
  28. youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)`)
  29. iso8601Regex = regexp.MustCompile(`^P((?P<year>\d+)Y)?((?P<month>\d+)M)?((?P<week>\d+)W)?((?P<day>\d+)D)?(T((?P<hour>\d+)H)?((?P<minute>\d+)M)?((?P<second>\d+)S)?)?$`)
  30. )
  31. // ProcessFeedEntries downloads original web page for entries and apply filters.
  32. func ProcessFeedEntries(store *storage.Storage, feed *model.Feed) {
  33. var filteredEntries model.Entries
  34. for _, entry := range feed.Entries {
  35. logger.Debug("[Processor] Processing entry %q from feed %q", entry.URL, feed.FeedURL)
  36. if isBlockedEntry(feed, entry) || !isAllowedEntry(feed, entry) {
  37. continue
  38. }
  39. if feed.Crawler {
  40. if !store.EntryURLExists(feed.ID, entry.URL) {
  41. logger.Debug("[Processor] Crawling entry %q from feed %q", entry.URL, feed.FeedURL)
  42. startTime := time.Now()
  43. content, scraperErr := scraper.Fetch(entry.URL, feed.ScraperRules, feed.UserAgent)
  44. if config.Opts.HasMetricsCollector() {
  45. status := "success"
  46. if scraperErr != nil {
  47. status = "error"
  48. }
  49. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  50. }
  51. if scraperErr != nil {
  52. logger.Error(`[Processor] Unable to crawl this entry: %q => %v`, entry.URL, scraperErr)
  53. } else if content != "" {
  54. // We replace the entry content only if the scraper doesn't return any error.
  55. entry.Content = content
  56. }
  57. }
  58. }
  59. entry.Content = rewrite.Rewriter(entry.URL, entry.Content, feed.RewriteRules)
  60. // The sanitizer should always run at the end of the process to make sure unsafe HTML is filtered.
  61. entry.Content = sanitizer.Sanitize(entry.URL, entry.Content)
  62. if config.Opts.FetchYouTubeWatchTime() {
  63. if matches := youtubeRegex.FindStringSubmatch(entry.URL); len(matches) == 2 {
  64. watchTime, err := fetchYouTubeWatchTime(entry.URL)
  65. if err != nil {
  66. logger.Error("[Processor] Unable to fetch YouTube watch time: %q => %v", entry.URL, err)
  67. }
  68. entry.ReadingTime = watchTime
  69. }
  70. }
  71. if entry.ReadingTime == 0 {
  72. entry.ReadingTime = calculateReadingTime(entry.Content)
  73. }
  74. filteredEntries = append(filteredEntries, entry)
  75. }
  76. feed.Entries = filteredEntries
  77. }
  78. func isBlockedEntry(feed *model.Feed, entry *model.Entry) bool {
  79. if feed.BlocklistRules != "" {
  80. match, _ := regexp.MatchString(feed.BlocklistRules, entry.Title)
  81. if match {
  82. logger.Debug("[Processor] Blocking entry %q from feed %q based on rule %q", entry.Title, feed.FeedURL, feed.BlocklistRules)
  83. return true
  84. }
  85. }
  86. return false
  87. }
  88. func isAllowedEntry(feed *model.Feed, entry *model.Entry) bool {
  89. if feed.KeeplistRules != "" {
  90. match, _ := regexp.MatchString(feed.KeeplistRules, entry.Title)
  91. if match {
  92. logger.Debug("[Processor] Allow entry %q from feed %q based on rule %q", entry.Title, feed.FeedURL, feed.KeeplistRules)
  93. return true
  94. }
  95. return false
  96. }
  97. return true
  98. }
  99. // ProcessEntryWebPage downloads the entry web page and apply rewrite rules.
  100. func ProcessEntryWebPage(entry *model.Entry) error {
  101. startTime := time.Now()
  102. content, scraperErr := scraper.Fetch(entry.URL, entry.Feed.ScraperRules, entry.Feed.UserAgent)
  103. if config.Opts.HasMetricsCollector() {
  104. status := "success"
  105. if scraperErr != nil {
  106. status = "error"
  107. }
  108. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  109. }
  110. if scraperErr != nil {
  111. return scraperErr
  112. }
  113. content = rewrite.Rewriter(entry.URL, content, entry.Feed.RewriteRules)
  114. content = sanitizer.Sanitize(entry.URL, content)
  115. if content != "" {
  116. entry.Content = content
  117. entry.ReadingTime = calculateReadingTime(content)
  118. }
  119. return nil
  120. }
  121. func fetchYouTubeWatchTime(url string) (int, error) {
  122. clt := client.NewClientWithConfig(url, config.Opts)
  123. response, browserErr := browser.Exec(clt)
  124. if browserErr != nil {
  125. return 0, browserErr
  126. }
  127. doc, docErr := goquery.NewDocumentFromReader(response.Body)
  128. if docErr != nil {
  129. return 0, docErr
  130. }
  131. durs, exists := doc.Find(`meta[itemprop="duration"]`).First().Attr("content")
  132. if !exists {
  133. return 0, errors.New("duration has not found")
  134. }
  135. dur, err := parseISO8601(durs)
  136. if err != nil {
  137. return 0, fmt.Errorf("unable to parse duration %s: %v", durs, err)
  138. }
  139. return int(dur.Minutes()), nil
  140. }
  141. // parseISO8601 parses an ISO 8601 duration string.
  142. func parseISO8601(from string) (time.Duration, error) {
  143. var match []string
  144. var d time.Duration
  145. if iso8601Regex.MatchString(from) {
  146. match = iso8601Regex.FindStringSubmatch(from)
  147. } else {
  148. return 0, errors.New("could not parse duration string")
  149. }
  150. for i, name := range iso8601Regex.SubexpNames() {
  151. part := match[i]
  152. if i == 0 || name == "" || part == "" {
  153. continue
  154. }
  155. val, err := strconv.ParseInt(part, 10, 64)
  156. if err != nil {
  157. return 0, err
  158. }
  159. switch name {
  160. case "hour":
  161. d = d + (time.Duration(val) * time.Hour)
  162. case "minute":
  163. d = d + (time.Duration(val) * time.Minute)
  164. case "second":
  165. d = d + (time.Duration(val) * time.Second)
  166. default:
  167. return 0, fmt.Errorf("unknown field %s", name)
  168. }
  169. }
  170. return d, nil
  171. }
  172. func calculateReadingTime(content string) int {
  173. sanitizedContent := sanitizer.StripTags(content)
  174. languageInfo := getlang.FromString(sanitizedContent)
  175. var timeToReadInt int
  176. if languageInfo.LanguageCode() == "ko" || languageInfo.LanguageCode() == "zh" || languageInfo.LanguageCode() == "jp" {
  177. timeToReadInt = int(math.Ceil(float64(utf8.RuneCountInString(sanitizedContent)) / 500))
  178. } else {
  179. nbOfWords := len(strings.Fields(sanitizedContent))
  180. timeToReadInt = int(math.Ceil(float64(nbOfWords) / 265))
  181. }
  182. return timeToReadInt
  183. }