processor.go 10 KB

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