processor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package processor
  4. import (
  5. "log/slog"
  6. "regexp"
  7. "slices"
  8. "strings"
  9. "time"
  10. "miniflux.app/v2/internal/config"
  11. "miniflux.app/v2/internal/metric"
  12. "miniflux.app/v2/internal/model"
  13. "miniflux.app/v2/internal/reader/fetcher"
  14. "miniflux.app/v2/internal/reader/readingtime"
  15. "miniflux.app/v2/internal/reader/rewrite"
  16. "miniflux.app/v2/internal/reader/sanitizer"
  17. "miniflux.app/v2/internal/reader/scraper"
  18. "miniflux.app/v2/internal/reader/urlcleaner"
  19. "miniflux.app/v2/internal/storage"
  20. "github.com/tdewolff/minify/v2"
  21. "github.com/tdewolff/minify/v2/html"
  22. )
  23. var customReplaceRuleRegex = regexp.MustCompile(`rewrite\("(.*)"\|"(.*)"\)`)
  24. // ProcessFeedEntries downloads original web page for entries and apply filters.
  25. func ProcessFeedEntries(store *storage.Storage, feed *model.Feed, user *model.User, forceRefresh bool) {
  26. var filteredEntries model.Entries
  27. // Process older entries first
  28. for i := len(feed.Entries) - 1; i >= 0; i-- {
  29. entry := feed.Entries[i]
  30. slog.Debug("Processing entry",
  31. slog.Int64("user_id", user.ID),
  32. slog.String("entry_url", entry.URL),
  33. slog.String("entry_hash", entry.Hash),
  34. slog.String("entry_title", entry.Title),
  35. slog.Int64("feed_id", feed.ID),
  36. slog.String("feed_url", feed.FeedURL),
  37. )
  38. if isBlockedEntry(feed, entry, user) || !isAllowedEntry(feed, entry, user) || !isRecentEntry(entry) {
  39. continue
  40. }
  41. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(entry.URL); err == nil {
  42. entry.URL = cleanedURL
  43. }
  44. pageBaseURL := ""
  45. rewrittenURL := rewriteEntryURL(feed, entry)
  46. entryIsNew := store.IsNewEntry(feed.ID, entry.Hash)
  47. if feed.Crawler && (entryIsNew || forceRefresh) {
  48. slog.Debug("Scraping entry",
  49. slog.Int64("user_id", user.ID),
  50. slog.String("entry_url", entry.URL),
  51. slog.String("entry_hash", entry.Hash),
  52. slog.String("entry_title", entry.Title),
  53. slog.Int64("feed_id", feed.ID),
  54. slog.String("feed_url", feed.FeedURL),
  55. slog.Bool("entry_is_new", entryIsNew),
  56. slog.Bool("force_refresh", forceRefresh),
  57. slog.String("rewritten_url", rewrittenURL),
  58. )
  59. startTime := time.Now()
  60. requestBuilder := fetcher.NewRequestBuilder()
  61. requestBuilder.WithUserAgent(feed.UserAgent, config.Opts.HTTPClientUserAgent())
  62. requestBuilder.WithCookie(feed.Cookie)
  63. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  64. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  65. requestBuilder.UseProxy(feed.FetchViaProxy)
  66. requestBuilder.IgnoreTLSErrors(feed.AllowSelfSignedCertificates)
  67. requestBuilder.DisableHTTP2(feed.DisableHTTP2)
  68. scrapedPageBaseURL, extractedContent, scraperErr := scraper.ScrapeWebsite(
  69. requestBuilder,
  70. rewrittenURL,
  71. feed.ScraperRules,
  72. )
  73. if scrapedPageBaseURL != "" {
  74. pageBaseURL = scrapedPageBaseURL
  75. }
  76. if config.Opts.HasMetricsCollector() {
  77. status := "success"
  78. if scraperErr != nil {
  79. status = "error"
  80. }
  81. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  82. }
  83. if scraperErr != nil {
  84. slog.Warn("Unable to scrape entry",
  85. slog.Int64("user_id", user.ID),
  86. slog.String("entry_url", entry.URL),
  87. slog.Int64("feed_id", feed.ID),
  88. slog.String("feed_url", feed.FeedURL),
  89. slog.Any("error", scraperErr),
  90. )
  91. } else if extractedContent != "" {
  92. // We replace the entry content only if the scraper doesn't return any error.
  93. entry.Content = minifyEntryContent(extractedContent)
  94. }
  95. }
  96. rewrite.Rewriter(rewrittenURL, entry, feed.RewriteRules)
  97. if pageBaseURL == "" {
  98. pageBaseURL = rewrittenURL
  99. }
  100. // The sanitizer should always run at the end of the process to make sure unsafe HTML is filtered out.
  101. entry.Content = sanitizer.Sanitize(pageBaseURL, entry.Content)
  102. updateEntryReadingTime(store, feed, entry, entryIsNew, user)
  103. filteredEntries = append(filteredEntries, entry)
  104. }
  105. feed.Entries = filteredEntries
  106. }
  107. func isBlockedEntry(feed *model.Feed, entry *model.Entry, user *model.User) bool {
  108. if user.BlockFilterEntryRules != "" {
  109. rules := strings.Split(user.BlockFilterEntryRules, "\n")
  110. for _, rule := range rules {
  111. parts := strings.SplitN(rule, "=", 2)
  112. var match bool
  113. switch parts[0] {
  114. case "EntryTitle":
  115. match, _ = regexp.MatchString(parts[1], entry.Title)
  116. case "EntryURL":
  117. match, _ = regexp.MatchString(parts[1], entry.URL)
  118. case "EntryCommentsURL":
  119. match, _ = regexp.MatchString(parts[1], entry.CommentsURL)
  120. case "EntryContent":
  121. match, _ = regexp.MatchString(parts[1], entry.Content)
  122. case "EntryAuthor":
  123. match, _ = regexp.MatchString(parts[1], entry.Author)
  124. case "EntryTag":
  125. containsTag := slices.ContainsFunc(entry.Tags, func(tag string) bool {
  126. match, _ = regexp.MatchString(parts[1], tag)
  127. return match
  128. })
  129. if containsTag {
  130. match = true
  131. }
  132. }
  133. if match {
  134. slog.Debug("Blocking entry based on rule",
  135. slog.String("entry_url", entry.URL),
  136. slog.Int64("feed_id", feed.ID),
  137. slog.String("feed_url", feed.FeedURL),
  138. slog.String("rule", rule),
  139. )
  140. return true
  141. }
  142. }
  143. }
  144. if feed.BlocklistRules == "" {
  145. return false
  146. }
  147. compiledBlocklist, err := regexp.Compile(feed.BlocklistRules)
  148. if err != nil {
  149. slog.Debug("Failed on regexp compilation",
  150. slog.String("pattern", feed.BlocklistRules),
  151. slog.Any("error", err),
  152. )
  153. return false
  154. }
  155. containsBlockedTag := slices.ContainsFunc(entry.Tags, func(tag string) bool {
  156. return compiledBlocklist.MatchString(tag)
  157. })
  158. if compiledBlocklist.MatchString(entry.URL) || compiledBlocklist.MatchString(entry.Title) || compiledBlocklist.MatchString(entry.Author) || containsBlockedTag {
  159. slog.Debug("Blocking entry based on rule",
  160. slog.String("entry_url", entry.URL),
  161. slog.Int64("feed_id", feed.ID),
  162. slog.String("feed_url", feed.FeedURL),
  163. slog.String("rule", feed.BlocklistRules),
  164. )
  165. return true
  166. }
  167. return false
  168. }
  169. func isAllowedEntry(feed *model.Feed, entry *model.Entry, user *model.User) bool {
  170. if user.KeepFilterEntryRules != "" {
  171. rules := strings.Split(user.KeepFilterEntryRules, "\n")
  172. for _, rule := range rules {
  173. parts := strings.SplitN(rule, "=", 2)
  174. var match bool
  175. switch parts[0] {
  176. case "EntryTitle":
  177. match, _ = regexp.MatchString(parts[1], entry.Title)
  178. case "EntryURL":
  179. match, _ = regexp.MatchString(parts[1], entry.URL)
  180. case "EntryCommentsURL":
  181. match, _ = regexp.MatchString(parts[1], entry.CommentsURL)
  182. case "EntryContent":
  183. match, _ = regexp.MatchString(parts[1], entry.Content)
  184. case "EntryAuthor":
  185. match, _ = regexp.MatchString(parts[1], entry.Author)
  186. case "EntryTag":
  187. containsTag := slices.ContainsFunc(entry.Tags, func(tag string) bool {
  188. match, _ = regexp.MatchString(parts[1], tag)
  189. return match
  190. })
  191. if containsTag {
  192. match = true
  193. }
  194. }
  195. if match {
  196. slog.Debug("Allowing entry based on rule",
  197. slog.String("entry_url", entry.URL),
  198. slog.Int64("feed_id", feed.ID),
  199. slog.String("feed_url", feed.FeedURL),
  200. slog.String("rule", rule),
  201. )
  202. return true
  203. }
  204. }
  205. return false
  206. }
  207. if feed.KeeplistRules == "" {
  208. return true
  209. }
  210. compiledKeeplist, err := regexp.Compile(feed.KeeplistRules)
  211. if err != nil {
  212. slog.Debug("Failed on regexp compilation",
  213. slog.String("pattern", feed.KeeplistRules),
  214. slog.Any("error", err),
  215. )
  216. return false
  217. }
  218. containsAllowedTag := slices.ContainsFunc(entry.Tags, func(tag string) bool {
  219. return compiledKeeplist.MatchString(tag)
  220. })
  221. if compiledKeeplist.MatchString(entry.URL) || compiledKeeplist.MatchString(entry.Title) || compiledKeeplist.MatchString(entry.Author) || containsAllowedTag {
  222. slog.Debug("Allow entry based on rule",
  223. slog.String("entry_url", entry.URL),
  224. slog.Int64("feed_id", feed.ID),
  225. slog.String("feed_url", feed.FeedURL),
  226. slog.String("rule", feed.KeeplistRules),
  227. )
  228. return true
  229. }
  230. return false
  231. }
  232. // ProcessEntryWebPage downloads the entry web page and apply rewrite rules.
  233. func ProcessEntryWebPage(feed *model.Feed, entry *model.Entry, user *model.User) error {
  234. startTime := time.Now()
  235. rewrittenEntryURL := rewriteEntryURL(feed, entry)
  236. requestBuilder := fetcher.NewRequestBuilder()
  237. requestBuilder.WithUserAgent(feed.UserAgent, config.Opts.HTTPClientUserAgent())
  238. requestBuilder.WithCookie(feed.Cookie)
  239. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  240. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  241. requestBuilder.UseProxy(feed.FetchViaProxy)
  242. requestBuilder.IgnoreTLSErrors(feed.AllowSelfSignedCertificates)
  243. requestBuilder.DisableHTTP2(feed.DisableHTTP2)
  244. pageBaseURL, extractedContent, scraperErr := scraper.ScrapeWebsite(
  245. requestBuilder,
  246. rewrittenEntryURL,
  247. feed.ScraperRules,
  248. )
  249. if config.Opts.HasMetricsCollector() {
  250. status := "success"
  251. if scraperErr != nil {
  252. status = "error"
  253. }
  254. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  255. }
  256. if scraperErr != nil {
  257. return scraperErr
  258. }
  259. if extractedContent != "" {
  260. entry.Content = minifyEntryContent(extractedContent)
  261. if user.ShowReadingTime {
  262. entry.ReadingTime = readingtime.EstimateReadingTime(entry.Content, user.DefaultReadingSpeed, user.CJKReadingSpeed)
  263. }
  264. }
  265. rewrite.Rewriter(rewrittenEntryURL, entry, entry.Feed.RewriteRules)
  266. entry.Content = sanitizer.Sanitize(pageBaseURL, entry.Content)
  267. return nil
  268. }
  269. func rewriteEntryURL(feed *model.Feed, entry *model.Entry) string {
  270. var rewrittenURL = entry.URL
  271. if feed.UrlRewriteRules != "" {
  272. parts := customReplaceRuleRegex.FindStringSubmatch(feed.UrlRewriteRules)
  273. if len(parts) >= 3 {
  274. re, err := regexp.Compile(parts[1])
  275. if err != nil {
  276. slog.Error("Failed on regexp compilation",
  277. slog.String("url_rewrite_rules", feed.UrlRewriteRules),
  278. slog.Any("error", err),
  279. )
  280. return rewrittenURL
  281. }
  282. rewrittenURL = re.ReplaceAllString(entry.URL, parts[2])
  283. slog.Debug("Rewriting entry URL",
  284. slog.String("original_entry_url", entry.URL),
  285. slog.String("rewritten_entry_url", rewrittenURL),
  286. slog.Int64("feed_id", feed.ID),
  287. slog.String("feed_url", feed.FeedURL),
  288. )
  289. } else {
  290. slog.Debug("Cannot find search and replace terms for replace rule",
  291. slog.String("original_entry_url", entry.URL),
  292. slog.String("rewritten_entry_url", rewrittenURL),
  293. slog.Int64("feed_id", feed.ID),
  294. slog.String("feed_url", feed.FeedURL),
  295. slog.String("url_rewrite_rules", feed.UrlRewriteRules),
  296. )
  297. }
  298. }
  299. return rewrittenURL
  300. }
  301. func updateEntryReadingTime(store *storage.Storage, feed *model.Feed, entry *model.Entry, entryIsNew bool, user *model.User) {
  302. if !user.ShowReadingTime {
  303. slog.Debug("Skip reading time estimation for this user", slog.Int64("user_id", user.ID))
  304. return
  305. }
  306. if shouldFetchYouTubeWatchTime(entry) {
  307. if entryIsNew {
  308. watchTime, err := fetchYouTubeWatchTime(entry.URL)
  309. if err != nil {
  310. slog.Warn("Unable to fetch YouTube watch time",
  311. slog.Int64("user_id", user.ID),
  312. slog.Int64("entry_id", entry.ID),
  313. slog.String("entry_url", entry.URL),
  314. slog.Int64("feed_id", feed.ID),
  315. slog.String("feed_url", feed.FeedURL),
  316. slog.Any("error", err),
  317. )
  318. }
  319. entry.ReadingTime = watchTime
  320. } else {
  321. entry.ReadingTime = store.GetReadTime(feed.ID, entry.Hash)
  322. }
  323. }
  324. if shouldFetchNebulaWatchTime(entry) {
  325. if entryIsNew {
  326. watchTime, err := fetchNebulaWatchTime(entry.URL)
  327. if err != nil {
  328. slog.Warn("Unable to fetch Nebula watch time",
  329. slog.Int64("user_id", user.ID),
  330. slog.Int64("entry_id", entry.ID),
  331. slog.String("entry_url", entry.URL),
  332. slog.Int64("feed_id", feed.ID),
  333. slog.String("feed_url", feed.FeedURL),
  334. slog.Any("error", err),
  335. )
  336. }
  337. entry.ReadingTime = watchTime
  338. } else {
  339. entry.ReadingTime = store.GetReadTime(feed.ID, entry.Hash)
  340. }
  341. }
  342. if shouldFetchOdyseeWatchTime(entry) {
  343. if entryIsNew {
  344. watchTime, err := fetchOdyseeWatchTime(entry.URL)
  345. if err != nil {
  346. slog.Warn("Unable to fetch Odysee watch time",
  347. slog.Int64("user_id", user.ID),
  348. slog.Int64("entry_id", entry.ID),
  349. slog.String("entry_url", entry.URL),
  350. slog.Int64("feed_id", feed.ID),
  351. slog.String("feed_url", feed.FeedURL),
  352. slog.Any("error", err),
  353. )
  354. }
  355. entry.ReadingTime = watchTime
  356. } else {
  357. entry.ReadingTime = store.GetReadTime(feed.ID, entry.Hash)
  358. }
  359. }
  360. if shouldFetchBilibiliWatchTime(entry) {
  361. if entryIsNew {
  362. watchTime, err := fetchBilibiliWatchTime(entry.URL)
  363. if err != nil {
  364. slog.Warn("Unable to fetch Bilibili watch time",
  365. slog.Int64("user_id", user.ID),
  366. slog.Int64("entry_id", entry.ID),
  367. slog.String("entry_url", entry.URL),
  368. slog.Int64("feed_id", feed.ID),
  369. slog.String("feed_url", feed.FeedURL),
  370. slog.Any("error", err),
  371. )
  372. }
  373. entry.ReadingTime = watchTime
  374. } else {
  375. entry.ReadingTime = store.GetReadTime(feed.ID, entry.Hash)
  376. }
  377. }
  378. // Handle YT error case and non-YT entries.
  379. if entry.ReadingTime == 0 {
  380. entry.ReadingTime = readingtime.EstimateReadingTime(entry.Content, user.DefaultReadingSpeed, user.CJKReadingSpeed)
  381. }
  382. }
  383. func isRecentEntry(entry *model.Entry) bool {
  384. if config.Opts.FilterEntryMaxAgeDays() == 0 || entry.Date.After(time.Now().AddDate(0, 0, -config.Opts.FilterEntryMaxAgeDays())) {
  385. return true
  386. }
  387. return false
  388. }
  389. func minifyEntryContent(entryContent string) string {
  390. m := minify.New()
  391. // Options required to avoid breaking the HTML content.
  392. m.Add("text/html", &html.Minifier{
  393. KeepEndTags: true,
  394. KeepQuotes: true,
  395. })
  396. if minifiedHTML, err := m.String("text/html", entryContent); err == nil {
  397. entryContent = minifiedHTML
  398. }
  399. return entryContent
  400. }