processor.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. entryIsNew := !store.EntryURLExists(feed.ID, entry.URL)
  40. if feed.Crawler && entryIsNew {
  41. logger.Debug("[Processor] Crawling entry %q from feed %q", entry.URL, feed.FeedURL)
  42. startTime := time.Now()
  43. content, scraperErr := scraper.Fetch(
  44. entry.URL,
  45. feed.ScraperRules,
  46. feed.UserAgent,
  47. feed.Cookie,
  48. feed.AllowSelfSignedCertificates,
  49. )
  50. if config.Opts.HasMetricsCollector() {
  51. status := "success"
  52. if scraperErr != nil {
  53. status = "error"
  54. }
  55. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  56. }
  57. if scraperErr != nil {
  58. logger.Error(`[Processor] Unable to crawl this entry: %q => %v`, entry.URL, scraperErr)
  59. } else if content != "" {
  60. // We replace the entry content only if the scraper doesn't return any error.
  61. entry.Content = content
  62. }
  63. }
  64. entry.Content = rewrite.Rewriter(entry.URL, entry.Content, feed.RewriteRules)
  65. // The sanitizer should always run at the end of the process to make sure unsafe HTML is filtered.
  66. entry.Content = sanitizer.Sanitize(entry.URL, entry.Content)
  67. updateEntryReadingTime(store, feed, entry, entryIsNew)
  68. filteredEntries = append(filteredEntries, entry)
  69. }
  70. feed.Entries = filteredEntries
  71. }
  72. func isBlockedEntry(feed *model.Feed, entry *model.Entry) bool {
  73. if feed.BlocklistRules != "" {
  74. match, _ := regexp.MatchString(feed.BlocklistRules, entry.Title)
  75. if match {
  76. logger.Debug("[Processor] Blocking entry %q from feed %q based on rule %q", entry.Title, feed.FeedURL, feed.BlocklistRules)
  77. return true
  78. }
  79. }
  80. return false
  81. }
  82. func isAllowedEntry(feed *model.Feed, entry *model.Entry) bool {
  83. if feed.KeeplistRules != "" {
  84. match, _ := regexp.MatchString(feed.KeeplistRules, entry.Title)
  85. if match {
  86. logger.Debug("[Processor] Allow entry %q from feed %q based on rule %q", entry.Title, feed.FeedURL, feed.KeeplistRules)
  87. return true
  88. }
  89. return false
  90. }
  91. return true
  92. }
  93. // ProcessEntryWebPage downloads the entry web page and apply rewrite rules.
  94. func ProcessEntryWebPage(feed *model.Feed, entry *model.Entry) error {
  95. startTime := time.Now()
  96. content, scraperErr := scraper.Fetch(
  97. entry.URL,
  98. entry.Feed.ScraperRules,
  99. entry.Feed.UserAgent,
  100. entry.Feed.Cookie,
  101. feed.AllowSelfSignedCertificates,
  102. )
  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 updateEntryReadingTime(store *storage.Storage, feed *model.Feed, entry *model.Entry, entryIsNew bool) {
  122. if shouldFetchYouTubeWatchTime(entry) {
  123. if entryIsNew {
  124. watchTime, err := fetchYouTubeWatchTime(entry.URL)
  125. if err != nil {
  126. logger.Error("[Processor] Unable to fetch YouTube watch time: %q => %v", entry.URL, err)
  127. }
  128. entry.ReadingTime = watchTime
  129. } else {
  130. entry.ReadingTime = store.GetReadTime(entry, feed)
  131. }
  132. }
  133. // Handle YT error case and non-YT entries.
  134. if entry.ReadingTime == 0 {
  135. entry.ReadingTime = calculateReadingTime(entry.Content)
  136. }
  137. }
  138. func shouldFetchYouTubeWatchTime(entry *model.Entry) bool {
  139. if !config.Opts.FetchYouTubeWatchTime() {
  140. return false
  141. }
  142. matches := youtubeRegex.FindStringSubmatch(entry.URL)
  143. urlMatchesYouTubePattern := len(matches) == 2
  144. return urlMatchesYouTubePattern
  145. }
  146. func fetchYouTubeWatchTime(url string) (int, error) {
  147. clt := client.NewClientWithConfig(url, config.Opts)
  148. response, browserErr := browser.Exec(clt)
  149. if browserErr != nil {
  150. return 0, browserErr
  151. }
  152. doc, docErr := goquery.NewDocumentFromReader(response.Body)
  153. if docErr != nil {
  154. return 0, docErr
  155. }
  156. durs, exists := doc.Find(`meta[itemprop="duration"]`).First().Attr("content")
  157. if !exists {
  158. return 0, errors.New("duration has not found")
  159. }
  160. dur, err := parseISO8601(durs)
  161. if err != nil {
  162. return 0, fmt.Errorf("unable to parse duration %s: %v", durs, err)
  163. }
  164. return int(dur.Minutes()), nil
  165. }
  166. // parseISO8601 parses an ISO 8601 duration string.
  167. func parseISO8601(from string) (time.Duration, error) {
  168. var match []string
  169. var d time.Duration
  170. if iso8601Regex.MatchString(from) {
  171. match = iso8601Regex.FindStringSubmatch(from)
  172. } else {
  173. return 0, errors.New("could not parse duration string")
  174. }
  175. for i, name := range iso8601Regex.SubexpNames() {
  176. part := match[i]
  177. if i == 0 || name == "" || part == "" {
  178. continue
  179. }
  180. val, err := strconv.ParseInt(part, 10, 64)
  181. if err != nil {
  182. return 0, err
  183. }
  184. switch name {
  185. case "hour":
  186. d = d + (time.Duration(val) * time.Hour)
  187. case "minute":
  188. d = d + (time.Duration(val) * time.Minute)
  189. case "second":
  190. d = d + (time.Duration(val) * time.Second)
  191. default:
  192. return 0, fmt.Errorf("unknown field %s", name)
  193. }
  194. }
  195. return d, nil
  196. }
  197. func calculateReadingTime(content string) int {
  198. sanitizedContent := sanitizer.StripTags(content)
  199. languageInfo := getlang.FromString(sanitizedContent)
  200. var timeToReadInt int
  201. if languageInfo.LanguageCode() == "ko" || languageInfo.LanguageCode() == "zh" || languageInfo.LanguageCode() == "jp" {
  202. timeToReadInt = int(math.Ceil(float64(utf8.RuneCountInString(sanitizedContent)) / 500))
  203. } else {
  204. nbOfWords := len(strings.Fields(sanitizedContent))
  205. timeToReadInt = int(math.Ceil(float64(nbOfWords) / 265))
  206. }
  207. return timeToReadInt
  208. }