processor.go 7.1 KB

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