processor.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package processor // import "miniflux.app/v2/internal/reader/processor"
  4. import (
  5. "log/slog"
  6. "net/url"
  7. "slices"
  8. "time"
  9. "miniflux.app/v2/internal/config"
  10. "miniflux.app/v2/internal/metric"
  11. "miniflux.app/v2/internal/model"
  12. "miniflux.app/v2/internal/proxyrotator"
  13. "miniflux.app/v2/internal/reader/fetcher"
  14. "miniflux.app/v2/internal/reader/filter"
  15. "miniflux.app/v2/internal/reader/readingtime"
  16. "miniflux.app/v2/internal/reader/rewrite"
  17. "miniflux.app/v2/internal/reader/sanitizer"
  18. "miniflux.app/v2/internal/reader/scraper"
  19. "miniflux.app/v2/internal/reader/urlcleaner"
  20. "miniflux.app/v2/internal/storage"
  21. "miniflux.app/v2/internal/urllib"
  22. )
  23. // ProcessFeedEntries downloads original web page for entries and apply filters.
  24. func ProcessFeedEntries(store *storage.Storage, feed *model.Feed, userID int64, forceRefresh bool) {
  25. var filteredEntries model.Entries
  26. user, storeErr := store.UserByID(userID)
  27. if storeErr != nil {
  28. slog.Error("Database error", slog.Any("error", storeErr))
  29. return
  30. }
  31. // The errors are handled in RemoveTrackingParameters.
  32. parsedFeedURL, _ := url.Parse(feed.FeedURL)
  33. parsedSiteURL, _ := url.Parse(feed.SiteURL)
  34. blockRules := filter.ParseRules(user.BlockFilterEntryRules, feed.BlockFilterEntryRules)
  35. allowRules := filter.ParseRules(user.KeepFilterEntryRules, feed.KeepFilterEntryRules)
  36. slog.Debug("Filter rules",
  37. slog.String("user_block_filter_rules", user.BlockFilterEntryRules),
  38. slog.String("feed_block_filter_rules", feed.BlockFilterEntryRules),
  39. slog.String("user_keep_filter_rules", user.KeepFilterEntryRules),
  40. slog.String("feed_keep_filter_rules", feed.KeepFilterEntryRules),
  41. slog.Any("block_rules", blockRules),
  42. slog.Any("allow_rules", allowRules),
  43. slog.Int64("user_id", user.ID),
  44. slog.Int64("feed_id", feed.ID),
  45. )
  46. requestBuilder := fetcher.NewRequestBuilder().
  47. WithUserAgent(feed.UserAgent, config.Opts.HTTPClientUserAgent()).
  48. WithCookie(feed.Cookie, feed.FeedURL).
  49. WithTimeout(config.Opts.HTTPClientTimeout()).
  50. WithProxyRotator(proxyrotator.ProxyRotatorInstance).
  51. WithCustomFeedProxyURL(feed.ProxyURL).
  52. WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL()).
  53. UseCustomApplicationProxyURL(feed.FetchViaProxy).
  54. IgnoreTLSErrors(feed.AllowSelfSignedCertificates).
  55. DisableHTTP2(feed.DisableHTTP2)
  56. // Processing older entries first ensures that their creation timestamp is lower than newer entries.
  57. for _, entry := range slices.Backward(feed.Entries) {
  58. slog.Debug("Processing entry",
  59. slog.Int64("user_id", user.ID),
  60. slog.String("entry_url", entry.URL),
  61. slog.String("entry_hash", entry.Hash),
  62. slog.String("entry_title", entry.Title),
  63. slog.Int64("feed_id", feed.ID),
  64. slog.String("feed_url", urllib.RedactedURL(feed.FeedURL)),
  65. )
  66. if filter.IsBlockedEntry(blockRules, allowRules, feed, entry) {
  67. slog.Debug("Entry is blocked by filter rules",
  68. slog.Int64("user_id", user.ID),
  69. slog.String("entry_url", entry.URL),
  70. slog.String("entry_hash", entry.Hash),
  71. slog.String("entry_title", entry.Title),
  72. slog.Int64("feed_id", feed.ID),
  73. slog.String("feed_url", urllib.RedactedURL(feed.FeedURL)),
  74. slog.String("filter_stage", "before_scrape"),
  75. )
  76. continue
  77. }
  78. parsedInputUrl, _ := url.Parse(entry.URL)
  79. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(parsedFeedURL, parsedSiteURL, parsedInputUrl); err == nil {
  80. entry.URL = cleanedURL
  81. }
  82. webpageBaseURL := ""
  83. entry.URL = rewrite.RewriteEntryURL(feed, entry)
  84. entryIsNew := store.IsNewEntry(feed.ID, entry.Hash)
  85. contentExtractedSuccessfully := false
  86. if feed.Crawler && (entryIsNew || forceRefresh) {
  87. slog.Debug("Scraping entry",
  88. slog.Int64("user_id", user.ID),
  89. slog.String("entry_url", entry.URL),
  90. slog.String("entry_hash", entry.Hash),
  91. slog.String("entry_title", entry.Title),
  92. slog.Int64("feed_id", feed.ID),
  93. slog.String("feed_url", urllib.RedactedURL(feed.FeedURL)),
  94. slog.Bool("entry_is_new", entryIsNew),
  95. slog.Bool("force_refresh", forceRefresh),
  96. )
  97. startTime := time.Now()
  98. scrapedPageBaseURL, extractedContent, scraperErr := scraper.ScrapeWebsite(
  99. requestBuilder,
  100. entry.URL,
  101. feed.ScraperRules,
  102. )
  103. if scrapedPageBaseURL != "" {
  104. webpageBaseURL = scrapedPageBaseURL
  105. }
  106. if config.Opts.HasMetricsCollector() {
  107. status := metric.StatusSuccess
  108. if scraperErr != nil {
  109. status = metric.StatusError
  110. }
  111. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  112. }
  113. if scraperErr != nil {
  114. slog.Warn("Unable to scrape entry",
  115. slog.Int64("user_id", user.ID),
  116. slog.String("entry_url", entry.URL),
  117. slog.Int64("feed_id", feed.ID),
  118. slog.String("feed_url", urllib.RedactedURL(feed.FeedURL)),
  119. slog.Any("error", scraperErr),
  120. )
  121. } else if extractedContent != "" {
  122. // We replace the entry content only if the scraper doesn't return any error.
  123. entry.Content = minifyContent(extractedContent)
  124. contentExtractedSuccessfully = true
  125. }
  126. }
  127. rewrite.ApplyContentRewriteRules(entry, feed.RewriteRules)
  128. // Re-run filters only when extracted content replaced entry.Content.
  129. if contentExtractedSuccessfully && filter.IsBlockedEntry(blockRules, allowRules, feed, entry) {
  130. slog.Debug("Entry is blocked by filter rules",
  131. slog.Int64("user_id", user.ID),
  132. slog.String("entry_url", entry.URL),
  133. slog.String("entry_hash", entry.Hash),
  134. slog.String("entry_title", entry.Title),
  135. slog.Int64("feed_id", feed.ID),
  136. slog.String("feed_url", urllib.RedactedURL(feed.FeedURL)),
  137. slog.String("filter_stage", "after_scrape"),
  138. )
  139. continue
  140. }
  141. if webpageBaseURL == "" {
  142. webpageBaseURL = entry.URL
  143. }
  144. // The sanitizer should always run at the end of the process to make sure unsafe HTML is filtered out.
  145. entry.Content = sanitizer.SanitizeHTML(webpageBaseURL, entry.Content, &sanitizer.SanitizerOptions{OpenLinksInNewTab: user.OpenExternalLinksInNewTab})
  146. updateEntryReadingTime(store, feed, entry, entryIsNew, user)
  147. filteredEntries = append(filteredEntries, entry)
  148. }
  149. if user.ShowReadingTime && shouldFetchYouTubeWatchTimeInBulk() {
  150. fetchYouTubeWatchTimeInBulk(filteredEntries)
  151. }
  152. feed.Entries = filteredEntries
  153. }
  154. // ProcessEntryWebPage downloads the entry web page and apply rewrite rules.
  155. func ProcessEntryWebPage(feed *model.Feed, entry *model.Entry, user *model.User) error {
  156. startTime := time.Now()
  157. entry.URL = rewrite.RewriteEntryURL(feed, entry)
  158. requestBuilder := fetcher.NewRequestBuilder().
  159. WithUserAgent(feed.UserAgent, config.Opts.HTTPClientUserAgent()).
  160. WithCookie(feed.Cookie, feed.FeedURL).
  161. WithTimeout(config.Opts.HTTPClientTimeout()).
  162. WithProxyRotator(proxyrotator.ProxyRotatorInstance).
  163. WithCustomFeedProxyURL(feed.ProxyURL).
  164. WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL()).
  165. UseCustomApplicationProxyURL(feed.FetchViaProxy).
  166. IgnoreTLSErrors(feed.AllowSelfSignedCertificates).
  167. DisableHTTP2(feed.DisableHTTP2)
  168. webpageBaseURL, extractedContent, scraperErr := scraper.ScrapeWebsite(
  169. requestBuilder,
  170. entry.URL,
  171. feed.ScraperRules,
  172. )
  173. if config.Opts.HasMetricsCollector() {
  174. status := metric.StatusSuccess
  175. if scraperErr != nil {
  176. status = metric.StatusError
  177. }
  178. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  179. }
  180. if scraperErr != nil {
  181. return scraperErr
  182. }
  183. if extractedContent != "" {
  184. entry.Content = minifyContent(extractedContent)
  185. if user.ShowReadingTime {
  186. entry.ReadingTime = readingtime.EstimateReadingTime(entry.Content, user.DefaultReadingSpeed, user.CJKReadingSpeed)
  187. }
  188. }
  189. rewrite.ApplyContentRewriteRules(entry, entry.Feed.RewriteRules)
  190. entry.Content = sanitizer.SanitizeHTML(webpageBaseURL, entry.Content, &sanitizer.SanitizerOptions{OpenLinksInNewTab: user.OpenExternalLinksInNewTab})
  191. return nil
  192. }