processor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package processor
  4. import (
  5. "errors"
  6. "fmt"
  7. "log/slog"
  8. "regexp"
  9. "slices"
  10. "strconv"
  11. "time"
  12. "miniflux.app/v2/internal/config"
  13. "miniflux.app/v2/internal/metric"
  14. "miniflux.app/v2/internal/model"
  15. "miniflux.app/v2/internal/reader/fetcher"
  16. "miniflux.app/v2/internal/reader/readingtime"
  17. "miniflux.app/v2/internal/reader/rewrite"
  18. "miniflux.app/v2/internal/reader/sanitizer"
  19. "miniflux.app/v2/internal/reader/scraper"
  20. "miniflux.app/v2/internal/storage"
  21. "github.com/PuerkitoBio/goquery"
  22. "github.com/tdewolff/minify/v2"
  23. "github.com/tdewolff/minify/v2/html"
  24. )
  25. var (
  26. youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)$`)
  27. odyseeRegex = regexp.MustCompile(`^https://odysee\.com`)
  28. 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)?)?$`)
  29. customReplaceRuleRegex = regexp.MustCompile(`rewrite\("(.*)"\|"(.*)"\)`)
  30. )
  31. // ProcessFeedEntries downloads original web page for entries and apply filters.
  32. func ProcessFeedEntries(store *storage.Storage, feed *model.Feed, user *model.User, forceRefresh bool) {
  33. var filteredEntries model.Entries
  34. // Process older entries first
  35. for i := len(feed.Entries) - 1; i >= 0; i-- {
  36. entry := feed.Entries[i]
  37. slog.Debug("Processing entry",
  38. slog.Int64("user_id", user.ID),
  39. slog.String("entry_url", entry.URL),
  40. slog.String("entry_hash", entry.Hash),
  41. slog.String("entry_title", entry.Title),
  42. slog.Int64("feed_id", feed.ID),
  43. slog.String("feed_url", feed.FeedURL),
  44. )
  45. if isBlockedEntry(feed, entry) || !isAllowedEntry(feed, entry) || !isRecentEntry(entry) {
  46. continue
  47. }
  48. websiteURL := getUrlFromEntry(feed, entry)
  49. entryIsNew := store.IsNewEntry(feed.ID, entry.Hash)
  50. if feed.Crawler && (entryIsNew || forceRefresh) {
  51. slog.Debug("Scraping entry",
  52. slog.Int64("user_id", user.ID),
  53. slog.String("entry_url", entry.URL),
  54. slog.String("entry_hash", entry.Hash),
  55. slog.String("entry_title", entry.Title),
  56. slog.Int64("feed_id", feed.ID),
  57. slog.String("feed_url", feed.FeedURL),
  58. slog.Bool("entry_is_new", entryIsNew),
  59. slog.Bool("force_refresh", forceRefresh),
  60. slog.String("website_url", websiteURL),
  61. )
  62. startTime := time.Now()
  63. requestBuilder := fetcher.NewRequestBuilder()
  64. requestBuilder.WithUserAgent(feed.UserAgent, config.Opts.HTTPClientUserAgent())
  65. requestBuilder.WithCookie(feed.Cookie)
  66. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  67. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  68. requestBuilder.UseProxy(feed.FetchViaProxy)
  69. requestBuilder.IgnoreTLSErrors(feed.AllowSelfSignedCertificates)
  70. requestBuilder.DisableHTTP2(feed.DisableHTTP2)
  71. content, scraperErr := scraper.ScrapeWebsite(
  72. requestBuilder,
  73. websiteURL,
  74. feed.ScraperRules,
  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 content != "" {
  92. // We replace the entry content only if the scraper doesn't return any error.
  93. entry.Content = minifyEntryContent(content)
  94. }
  95. }
  96. rewrite.Rewriter(websiteURL, entry, feed.RewriteRules)
  97. // The sanitizer should always run at the end of the process to make sure unsafe HTML is filtered.
  98. entry.Content = sanitizer.Sanitize(websiteURL, entry.Content)
  99. updateEntryReadingTime(store, feed, entry, entryIsNew, user)
  100. filteredEntries = append(filteredEntries, entry)
  101. }
  102. feed.Entries = filteredEntries
  103. }
  104. func isBlockedEntry(feed *model.Feed, entry *model.Entry) bool {
  105. if feed.BlocklistRules == "" {
  106. return false
  107. }
  108. compiledBlocklist, err := regexp.Compile(feed.BlocklistRules)
  109. if err != nil {
  110. slog.Debug("Failed on regexp compilation",
  111. slog.String("pattern", feed.BlocklistRules),
  112. slog.Any("error", err),
  113. )
  114. return false
  115. }
  116. containsBlockedTag := slices.ContainsFunc(entry.Tags, func(tag string) bool {
  117. return compiledBlocklist.MatchString(tag)
  118. })
  119. if compiledBlocklist.MatchString(entry.URL) || compiledBlocklist.MatchString(entry.Title) || compiledBlocklist.MatchString(entry.Author) || containsBlockedTag {
  120. slog.Debug("Blocking entry based on rule",
  121. slog.String("entry_url", entry.URL),
  122. slog.Int64("feed_id", feed.ID),
  123. slog.String("feed_url", feed.FeedURL),
  124. slog.String("rule", feed.BlocklistRules),
  125. )
  126. return true
  127. }
  128. return false
  129. }
  130. func isAllowedEntry(feed *model.Feed, entry *model.Entry) bool {
  131. if feed.KeeplistRules == "" {
  132. return true
  133. }
  134. compiledKeeplist, err := regexp.Compile(feed.KeeplistRules)
  135. if err != nil {
  136. slog.Debug("Failed on regexp compilation",
  137. slog.String("pattern", feed.KeeplistRules),
  138. slog.Any("error", err),
  139. )
  140. return false
  141. }
  142. containsAllowedTag := slices.ContainsFunc(entry.Tags, func(tag string) bool {
  143. return compiledKeeplist.MatchString(tag)
  144. })
  145. if compiledKeeplist.MatchString(entry.URL) || compiledKeeplist.MatchString(entry.Title) || compiledKeeplist.MatchString(entry.Author) || containsAllowedTag {
  146. slog.Debug("Allow entry based on rule",
  147. slog.String("entry_url", entry.URL),
  148. slog.Int64("feed_id", feed.ID),
  149. slog.String("feed_url", feed.FeedURL),
  150. slog.String("rule", feed.KeeplistRules),
  151. )
  152. return true
  153. }
  154. return false
  155. }
  156. // ProcessEntryWebPage downloads the entry web page and apply rewrite rules.
  157. func ProcessEntryWebPage(feed *model.Feed, entry *model.Entry, user *model.User) error {
  158. startTime := time.Now()
  159. websiteURL := getUrlFromEntry(feed, entry)
  160. requestBuilder := fetcher.NewRequestBuilder()
  161. requestBuilder.WithUserAgent(feed.UserAgent, config.Opts.HTTPClientUserAgent())
  162. requestBuilder.WithCookie(feed.Cookie)
  163. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  164. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  165. requestBuilder.UseProxy(feed.FetchViaProxy)
  166. requestBuilder.IgnoreTLSErrors(feed.AllowSelfSignedCertificates)
  167. requestBuilder.DisableHTTP2(feed.DisableHTTP2)
  168. content, scraperErr := scraper.ScrapeWebsite(
  169. requestBuilder,
  170. websiteURL,
  171. feed.ScraperRules,
  172. )
  173. if config.Opts.HasMetricsCollector() {
  174. status := "success"
  175. if scraperErr != nil {
  176. status = "error"
  177. }
  178. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  179. }
  180. if scraperErr != nil {
  181. return scraperErr
  182. }
  183. if content != "" {
  184. entry.Content = minifyEntryContent(content)
  185. if user.ShowReadingTime {
  186. entry.ReadingTime = readingtime.EstimateReadingTime(entry.Content, user.DefaultReadingSpeed, user.CJKReadingSpeed)
  187. }
  188. }
  189. rewrite.Rewriter(websiteURL, entry, entry.Feed.RewriteRules)
  190. entry.Content = sanitizer.Sanitize(websiteURL, entry.Content)
  191. return nil
  192. }
  193. func getUrlFromEntry(feed *model.Feed, entry *model.Entry) string {
  194. var url = entry.URL
  195. if feed.UrlRewriteRules != "" {
  196. parts := customReplaceRuleRegex.FindStringSubmatch(feed.UrlRewriteRules)
  197. if len(parts) >= 3 {
  198. re := regexp.MustCompile(parts[1])
  199. url = re.ReplaceAllString(entry.URL, parts[2])
  200. slog.Debug("Rewriting entry URL",
  201. slog.String("original_entry_url", entry.URL),
  202. slog.String("rewritten_entry_url", url),
  203. slog.Int64("feed_id", feed.ID),
  204. slog.String("feed_url", feed.FeedURL),
  205. )
  206. } else {
  207. slog.Debug("Cannot find search and replace terms for replace rule",
  208. slog.String("original_entry_url", entry.URL),
  209. slog.String("rewritten_entry_url", url),
  210. slog.Int64("feed_id", feed.ID),
  211. slog.String("feed_url", feed.FeedURL),
  212. slog.String("url_rewrite_rules", feed.UrlRewriteRules),
  213. )
  214. }
  215. }
  216. return url
  217. }
  218. func updateEntryReadingTime(store *storage.Storage, feed *model.Feed, entry *model.Entry, entryIsNew bool, user *model.User) {
  219. if !user.ShowReadingTime {
  220. slog.Debug("Skip reading time estimation for this user", slog.Int64("user_id", user.ID))
  221. return
  222. }
  223. if shouldFetchYouTubeWatchTime(entry) {
  224. if entryIsNew {
  225. watchTime, err := fetchYouTubeWatchTime(entry.URL)
  226. if err != nil {
  227. slog.Warn("Unable to fetch YouTube watch time",
  228. slog.Int64("user_id", user.ID),
  229. slog.Int64("entry_id", entry.ID),
  230. slog.String("entry_url", entry.URL),
  231. slog.Int64("feed_id", feed.ID),
  232. slog.String("feed_url", feed.FeedURL),
  233. slog.Any("error", err),
  234. )
  235. }
  236. entry.ReadingTime = watchTime
  237. } else {
  238. entry.ReadingTime = store.GetReadTime(feed.ID, entry.Hash)
  239. }
  240. }
  241. if shouldFetchOdyseeWatchTime(entry) {
  242. if entryIsNew {
  243. watchTime, err := fetchOdyseeWatchTime(entry.URL)
  244. if err != nil {
  245. slog.Warn("Unable to fetch Odysee watch time",
  246. slog.Int64("user_id", user.ID),
  247. slog.Int64("entry_id", entry.ID),
  248. slog.String("entry_url", entry.URL),
  249. slog.Int64("feed_id", feed.ID),
  250. slog.String("feed_url", feed.FeedURL),
  251. slog.Any("error", err),
  252. )
  253. }
  254. entry.ReadingTime = watchTime
  255. } else {
  256. entry.ReadingTime = store.GetReadTime(feed.ID, entry.Hash)
  257. }
  258. }
  259. // Handle YT error case and non-YT entries.
  260. if entry.ReadingTime == 0 {
  261. entry.ReadingTime = readingtime.EstimateReadingTime(entry.Content, user.DefaultReadingSpeed, user.CJKReadingSpeed)
  262. }
  263. }
  264. func shouldFetchYouTubeWatchTime(entry *model.Entry) bool {
  265. if !config.Opts.FetchYouTubeWatchTime() {
  266. return false
  267. }
  268. matches := youtubeRegex.FindStringSubmatch(entry.URL)
  269. urlMatchesYouTubePattern := len(matches) == 2
  270. return urlMatchesYouTubePattern
  271. }
  272. func shouldFetchOdyseeWatchTime(entry *model.Entry) bool {
  273. if !config.Opts.FetchOdyseeWatchTime() {
  274. return false
  275. }
  276. matches := odyseeRegex.FindStringSubmatch(entry.URL)
  277. return matches != nil
  278. }
  279. func fetchYouTubeWatchTime(websiteURL string) (int, error) {
  280. requestBuilder := fetcher.NewRequestBuilder()
  281. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  282. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  283. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(websiteURL))
  284. defer responseHandler.Close()
  285. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  286. slog.Warn("Unable to fetch YouTube page", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  287. return 0, localizedError.Error()
  288. }
  289. doc, docErr := goquery.NewDocumentFromReader(responseHandler.Body(config.Opts.HTTPClientMaxBodySize()))
  290. if docErr != nil {
  291. return 0, docErr
  292. }
  293. durs, exists := doc.Find(`meta[itemprop="duration"]`).First().Attr("content")
  294. if !exists {
  295. return 0, errors.New("duration has not found")
  296. }
  297. dur, err := parseISO8601(durs)
  298. if err != nil {
  299. return 0, fmt.Errorf("unable to parse duration %s: %v", durs, err)
  300. }
  301. return int(dur.Minutes()), nil
  302. }
  303. func fetchOdyseeWatchTime(websiteURL string) (int, error) {
  304. requestBuilder := fetcher.NewRequestBuilder()
  305. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  306. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  307. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(websiteURL))
  308. defer responseHandler.Close()
  309. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  310. slog.Warn("Unable to fetch Odysee watch time", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  311. return 0, localizedError.Error()
  312. }
  313. doc, docErr := goquery.NewDocumentFromReader(responseHandler.Body(config.Opts.HTTPClientMaxBodySize()))
  314. if docErr != nil {
  315. return 0, docErr
  316. }
  317. durs, exists := doc.Find(`meta[property="og:video:duration"]`).First().Attr("content")
  318. // durs contains video watch time in seconds
  319. if !exists {
  320. return 0, errors.New("duration has not found")
  321. }
  322. dur, err := strconv.ParseInt(durs, 10, 64)
  323. if err != nil {
  324. return 0, fmt.Errorf("unable to parse duration %s: %v", durs, err)
  325. }
  326. return int(dur / 60), nil
  327. }
  328. // parseISO8601 parses an ISO 8601 duration string.
  329. func parseISO8601(from string) (time.Duration, error) {
  330. var match []string
  331. var d time.Duration
  332. if iso8601Regex.MatchString(from) {
  333. match = iso8601Regex.FindStringSubmatch(from)
  334. } else {
  335. return 0, errors.New("could not parse duration string")
  336. }
  337. for i, name := range iso8601Regex.SubexpNames() {
  338. part := match[i]
  339. if i == 0 || name == "" || part == "" {
  340. continue
  341. }
  342. val, err := strconv.ParseInt(part, 10, 64)
  343. if err != nil {
  344. return 0, err
  345. }
  346. switch name {
  347. case "hour":
  348. d += (time.Duration(val) * time.Hour)
  349. case "minute":
  350. d += (time.Duration(val) * time.Minute)
  351. case "second":
  352. d += (time.Duration(val) * time.Second)
  353. default:
  354. return 0, fmt.Errorf("unknown field %s", name)
  355. }
  356. }
  357. return d, nil
  358. }
  359. func isRecentEntry(entry *model.Entry) bool {
  360. if config.Opts.FilterEntryMaxAgeDays() == 0 || entry.Date.After(time.Now().AddDate(0, 0, -config.Opts.FilterEntryMaxAgeDays())) {
  361. return true
  362. }
  363. return false
  364. }
  365. func minifyEntryContent(entryContent string) string {
  366. m := minify.New()
  367. // Options required to avoid breaking the HTML content.
  368. m.Add("text/html", &html.Minifier{
  369. KeepEndTags: true,
  370. KeepQuotes: true,
  371. })
  372. if minifiedHTML, err := m.String("text/html", entryContent); err == nil {
  373. entryContent = minifiedHTML
  374. }
  375. return entryContent
  376. }