processor.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. "strconv"
  10. "time"
  11. "miniflux.app/v2/internal/config"
  12. "miniflux.app/v2/internal/http/client"
  13. "miniflux.app/v2/internal/metric"
  14. "miniflux.app/v2/internal/model"
  15. "miniflux.app/v2/internal/reader/browser"
  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. )
  23. var (
  24. youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)`)
  25. odyseeRegex = regexp.MustCompile(`^https://odysee\.com`)
  26. 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)?)?$`)
  27. customReplaceRuleRegex = regexp.MustCompile(`rewrite\("(.*)"\|"(.*)"\)`)
  28. )
  29. // ProcessFeedEntries downloads original web page for entries and apply filters.
  30. func ProcessFeedEntries(store *storage.Storage, feed *model.Feed, user *model.User, forceRefresh bool) {
  31. var filteredEntries model.Entries
  32. // Process older entries first
  33. for i := len(feed.Entries) - 1; i >= 0; i-- {
  34. entry := feed.Entries[i]
  35. slog.Debug("Processing entry",
  36. slog.Int64("user_id", user.ID),
  37. slog.Int64("entry_id", entry.ID),
  38. slog.String("entry_url", entry.URL),
  39. slog.Int64("feed_id", feed.ID),
  40. slog.String("feed_url", feed.FeedURL),
  41. )
  42. if isBlockedEntry(feed, entry) || !isAllowedEntry(feed, entry) {
  43. continue
  44. }
  45. url := getUrlFromEntry(feed, entry)
  46. entryIsNew := !store.EntryURLExists(feed.ID, entry.URL)
  47. if feed.Crawler && (entryIsNew || forceRefresh) {
  48. slog.Debug("Scraping entry",
  49. slog.Int64("user_id", user.ID),
  50. slog.Int64("entry_id", entry.ID),
  51. slog.String("entry_url", entry.URL),
  52. slog.Int64("feed_id", feed.ID),
  53. slog.String("feed_url", feed.FeedURL),
  54. )
  55. startTime := time.Now()
  56. content, scraperErr := scraper.Fetch(
  57. url,
  58. feed.ScraperRules,
  59. feed.UserAgent,
  60. feed.Cookie,
  61. feed.AllowSelfSignedCertificates,
  62. feed.FetchViaProxy,
  63. )
  64. if config.Opts.HasMetricsCollector() {
  65. status := "success"
  66. if scraperErr != nil {
  67. status = "error"
  68. }
  69. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  70. }
  71. if scraperErr != nil {
  72. slog.Warn("Unable to scrape entry",
  73. slog.Int64("user_id", user.ID),
  74. slog.Int64("entry_id", entry.ID),
  75. slog.String("entry_url", entry.URL),
  76. slog.Int64("feed_id", feed.ID),
  77. slog.String("feed_url", feed.FeedURL),
  78. slog.Any("error", scraperErr),
  79. )
  80. } else if content != "" {
  81. // We replace the entry content only if the scraper doesn't return any error.
  82. entry.Content = content
  83. }
  84. }
  85. rewrite.Rewriter(url, entry, feed.RewriteRules)
  86. // The sanitizer should always run at the end of the process to make sure unsafe HTML is filtered.
  87. entry.Content = sanitizer.Sanitize(url, entry.Content)
  88. updateEntryReadingTime(store, feed, entry, entryIsNew, user)
  89. filteredEntries = append(filteredEntries, entry)
  90. }
  91. feed.Entries = filteredEntries
  92. }
  93. func isBlockedEntry(feed *model.Feed, entry *model.Entry) bool {
  94. if feed.BlocklistRules != "" {
  95. match, _ := regexp.MatchString(feed.BlocklistRules, entry.Title)
  96. if match {
  97. slog.Debug("Blocking entry based on rule",
  98. slog.Int64("entry_id", entry.ID),
  99. slog.String("entry_url", entry.URL),
  100. slog.Int64("feed_id", feed.ID),
  101. slog.String("feed_url", feed.FeedURL),
  102. slog.String("rule", feed.BlocklistRules),
  103. )
  104. return true
  105. }
  106. }
  107. return false
  108. }
  109. func isAllowedEntry(feed *model.Feed, entry *model.Entry) bool {
  110. if feed.KeeplistRules != "" {
  111. match, _ := regexp.MatchString(feed.KeeplistRules, entry.Title)
  112. if match {
  113. slog.Debug("Allow entry based on rule",
  114. slog.Int64("entry_id", entry.ID),
  115. slog.String("entry_url", entry.URL),
  116. slog.Int64("feed_id", feed.ID),
  117. slog.String("feed_url", feed.FeedURL),
  118. slog.String("rule", feed.KeeplistRules),
  119. )
  120. return true
  121. }
  122. return false
  123. }
  124. return true
  125. }
  126. // ProcessEntryWebPage downloads the entry web page and apply rewrite rules.
  127. func ProcessEntryWebPage(feed *model.Feed, entry *model.Entry, user *model.User) error {
  128. startTime := time.Now()
  129. url := getUrlFromEntry(feed, entry)
  130. content, scraperErr := scraper.Fetch(
  131. url,
  132. entry.Feed.ScraperRules,
  133. entry.Feed.UserAgent,
  134. entry.Feed.Cookie,
  135. feed.AllowSelfSignedCertificates,
  136. feed.FetchViaProxy,
  137. )
  138. if config.Opts.HasMetricsCollector() {
  139. status := "success"
  140. if scraperErr != nil {
  141. status = "error"
  142. }
  143. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  144. }
  145. if scraperErr != nil {
  146. return scraperErr
  147. }
  148. if content != "" {
  149. entry.Content = content
  150. entry.ReadingTime = readingtime.EstimateReadingTime(entry.Content, user.DefaultReadingSpeed, user.CJKReadingSpeed)
  151. }
  152. rewrite.Rewriter(url, entry, entry.Feed.RewriteRules)
  153. entry.Content = sanitizer.Sanitize(url, entry.Content)
  154. return nil
  155. }
  156. func getUrlFromEntry(feed *model.Feed, entry *model.Entry) string {
  157. var url = entry.URL
  158. if feed.UrlRewriteRules != "" {
  159. parts := customReplaceRuleRegex.FindStringSubmatch(feed.UrlRewriteRules)
  160. if len(parts) >= 3 {
  161. re := regexp.MustCompile(parts[1])
  162. url = re.ReplaceAllString(entry.URL, parts[2])
  163. slog.Debug("Rewriting entry URL",
  164. slog.Int64("entry_id", entry.ID),
  165. slog.String("original_entry_url", entry.URL),
  166. slog.String("rewritten_entry_url", url),
  167. slog.Int64("feed_id", feed.ID),
  168. slog.String("feed_url", feed.FeedURL),
  169. )
  170. } else {
  171. slog.Debug("Cannot find search and replace terms for replace rule",
  172. slog.Int64("entry_id", entry.ID),
  173. slog.String("original_entry_url", entry.URL),
  174. slog.String("rewritten_entry_url", url),
  175. slog.Int64("feed_id", feed.ID),
  176. slog.String("feed_url", feed.FeedURL),
  177. slog.String("url_rewrite_rules", feed.UrlRewriteRules),
  178. )
  179. }
  180. }
  181. return url
  182. }
  183. func updateEntryReadingTime(store *storage.Storage, feed *model.Feed, entry *model.Entry, entryIsNew bool, user *model.User) {
  184. if shouldFetchYouTubeWatchTime(entry) {
  185. if entryIsNew {
  186. watchTime, err := fetchYouTubeWatchTime(entry.URL)
  187. if err != nil {
  188. slog.Warn("Unable to fetch YouTube watch time",
  189. slog.Int64("user_id", user.ID),
  190. slog.Int64("entry_id", entry.ID),
  191. slog.String("entry_url", entry.URL),
  192. slog.Int64("feed_id", feed.ID),
  193. slog.String("feed_url", feed.FeedURL),
  194. slog.Any("error", err),
  195. )
  196. }
  197. entry.ReadingTime = watchTime
  198. } else {
  199. entry.ReadingTime = store.GetReadTime(entry, feed)
  200. }
  201. }
  202. if shouldFetchOdyseeWatchTime(entry) {
  203. if entryIsNew {
  204. watchTime, err := fetchOdyseeWatchTime(entry.URL)
  205. if err != nil {
  206. slog.Warn("Unable to fetch Odysee watch time",
  207. slog.Int64("user_id", user.ID),
  208. slog.Int64("entry_id", entry.ID),
  209. slog.String("entry_url", entry.URL),
  210. slog.Int64("feed_id", feed.ID),
  211. slog.String("feed_url", feed.FeedURL),
  212. slog.Any("error", err),
  213. )
  214. }
  215. entry.ReadingTime = watchTime
  216. } else {
  217. entry.ReadingTime = store.GetReadTime(entry, feed)
  218. }
  219. }
  220. // Handle YT error case and non-YT entries.
  221. if entry.ReadingTime == 0 {
  222. entry.ReadingTime = readingtime.EstimateReadingTime(entry.Content, user.DefaultReadingSpeed, user.CJKReadingSpeed)
  223. }
  224. }
  225. func shouldFetchYouTubeWatchTime(entry *model.Entry) bool {
  226. if !config.Opts.FetchYouTubeWatchTime() {
  227. return false
  228. }
  229. matches := youtubeRegex.FindStringSubmatch(entry.URL)
  230. urlMatchesYouTubePattern := len(matches) == 2
  231. return urlMatchesYouTubePattern
  232. }
  233. func shouldFetchOdyseeWatchTime(entry *model.Entry) bool {
  234. if !config.Opts.FetchOdyseeWatchTime() {
  235. return false
  236. }
  237. matches := odyseeRegex.FindStringSubmatch(entry.URL)
  238. return matches != nil
  239. }
  240. func fetchYouTubeWatchTime(url string) (int, error) {
  241. clt := client.NewClientWithConfig(url, config.Opts)
  242. response, browserErr := browser.Exec(clt)
  243. if browserErr != nil {
  244. return 0, browserErr
  245. }
  246. doc, docErr := goquery.NewDocumentFromReader(response.Body)
  247. if docErr != nil {
  248. return 0, docErr
  249. }
  250. durs, exists := doc.Find(`meta[itemprop="duration"]`).First().Attr("content")
  251. if !exists {
  252. return 0, errors.New("duration has not found")
  253. }
  254. dur, err := parseISO8601(durs)
  255. if err != nil {
  256. return 0, fmt.Errorf("unable to parse duration %s: %v", durs, err)
  257. }
  258. return int(dur.Minutes()), nil
  259. }
  260. func fetchOdyseeWatchTime(url string) (int, error) {
  261. clt := client.NewClientWithConfig(url, config.Opts)
  262. response, browserErr := browser.Exec(clt)
  263. if browserErr != nil {
  264. return 0, browserErr
  265. }
  266. doc, docErr := goquery.NewDocumentFromReader(response.Body)
  267. if docErr != nil {
  268. return 0, docErr
  269. }
  270. durs, exists := doc.Find(`meta[property="og:video:duration"]`).First().Attr("content")
  271. // durs contains video watch time in seconds
  272. if !exists {
  273. return 0, errors.New("duration has not found")
  274. }
  275. dur, err := strconv.ParseInt(durs, 10, 64)
  276. if err != nil {
  277. return 0, fmt.Errorf("unable to parse duration %s: %v", durs, err)
  278. }
  279. return int(dur / 60), nil
  280. }
  281. // parseISO8601 parses an ISO 8601 duration string.
  282. func parseISO8601(from string) (time.Duration, error) {
  283. var match []string
  284. var d time.Duration
  285. if iso8601Regex.MatchString(from) {
  286. match = iso8601Regex.FindStringSubmatch(from)
  287. } else {
  288. return 0, errors.New("could not parse duration string")
  289. }
  290. for i, name := range iso8601Regex.SubexpNames() {
  291. part := match[i]
  292. if i == 0 || name == "" || part == "" {
  293. continue
  294. }
  295. val, err := strconv.ParseInt(part, 10, 64)
  296. if err != nil {
  297. return 0, err
  298. }
  299. switch name {
  300. case "hour":
  301. d = d + (time.Duration(val) * time.Hour)
  302. case "minute":
  303. d = d + (time.Duration(val) * time.Minute)
  304. case "second":
  305. d = d + (time.Duration(val) * time.Second)
  306. default:
  307. return 0, fmt.Errorf("unknown field %s", name)
  308. }
  309. }
  310. return d, nil
  311. }