processor.go 6.7 KB

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