processor.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. "math"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "unicode/utf8"
  13. "miniflux.app/integration"
  14. "miniflux.app/config"
  15. "miniflux.app/http/client"
  16. "miniflux.app/logger"
  17. "miniflux.app/metric"
  18. "miniflux.app/model"
  19. "miniflux.app/reader/browser"
  20. "miniflux.app/reader/rewrite"
  21. "miniflux.app/reader/sanitizer"
  22. "miniflux.app/reader/scraper"
  23. "miniflux.app/storage"
  24. "github.com/PuerkitoBio/goquery"
  25. "github.com/rylans/getlang"
  26. )
  27. var (
  28. youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)`)
  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) {
  34. var filteredEntries model.Entries
  35. // array used for bulk push
  36. entriesToPush := model.Entries{}
  37. // Process older entries first
  38. for i := len(feed.Entries) - 1; i >= 0; i-- {
  39. entry := feed.Entries[i]
  40. logger.Debug("[Processor] Processing entry %q from feed %q", entry.URL, feed.FeedURL)
  41. if isBlockedEntry(feed, entry) || !isAllowedEntry(feed, entry) {
  42. continue
  43. }
  44. url := getUrlFromEntry(feed, entry)
  45. entryIsNew := !store.EntryURLExists(feed.ID, entry.URL)
  46. if feed.Crawler && entryIsNew {
  47. logger.Debug("[Processor] Crawling entry %q from feed %q", url, feed.FeedURL)
  48. startTime := time.Now()
  49. content, scraperErr := scraper.Fetch(
  50. url,
  51. feed.ScraperRules,
  52. feed.UserAgent,
  53. feed.Cookie,
  54. feed.AllowSelfSignedCertificates,
  55. feed.FetchViaProxy,
  56. )
  57. if config.Opts.HasMetricsCollector() {
  58. status := "success"
  59. if scraperErr != nil {
  60. status = "error"
  61. }
  62. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  63. }
  64. if scraperErr != nil {
  65. logger.Error(`[Processor] Unable to crawl this entry: %q => %v`, entry.URL, scraperErr)
  66. } else if content != "" {
  67. // We replace the entry content only if the scraper doesn't return any error.
  68. entry.Content = content
  69. }
  70. }
  71. rewrite.Rewriter(url, entry, feed.RewriteRules)
  72. // The sanitizer should always run at the end of the process to make sure unsafe HTML is filtered.
  73. entry.Content = sanitizer.Sanitize(url, entry.Content)
  74. if entryIsNew {
  75. intg, err := store.Integration(feed.UserID)
  76. if err != nil {
  77. logger.Error("[Processor] Get integrations for user %d failed: %v; the refresh process will go on, but no integrations will run this time.", feed.UserID, err)
  78. } else if intg != nil {
  79. localEntry := entry
  80. go func() {
  81. integration.PushEntry(localEntry, intg)
  82. }()
  83. entriesToPush = append(entriesToPush, localEntry)
  84. }
  85. }
  86. updateEntryReadingTime(store, feed, entry, entryIsNew, user)
  87. filteredEntries = append(filteredEntries, entry)
  88. }
  89. intg, err := store.Integration(feed.UserID)
  90. if err != nil {
  91. logger.Error("[Processor] Get integrations for user %d failed: %v; the refresh process will go on, but no integrations will run this time.", feed.UserID, err)
  92. } else if intg != nil && len(entriesToPush) > 0 {
  93. go func() {
  94. integration.PushEntries(entriesToPush, intg)
  95. }()
  96. }
  97. feed.Entries = filteredEntries
  98. }
  99. func isBlockedEntry(feed *model.Feed, entry *model.Entry) bool {
  100. if feed.BlocklistRules != "" {
  101. match, _ := regexp.MatchString(feed.BlocklistRules, entry.Title)
  102. if match {
  103. logger.Debug("[Processor] Blocking entry %q from feed %q based on rule %q", entry.Title, feed.FeedURL, feed.BlocklistRules)
  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. logger.Debug("[Processor] Allow entry %q from feed %q based on rule %q", entry.Title, feed.FeedURL, feed.KeeplistRules)
  114. return true
  115. }
  116. return false
  117. }
  118. return true
  119. }
  120. // ProcessEntryWebPage downloads the entry web page and apply rewrite rules.
  121. func ProcessEntryWebPage(feed *model.Feed, entry *model.Entry, user *model.User) error {
  122. startTime := time.Now()
  123. url := getUrlFromEntry(feed, entry)
  124. content, scraperErr := scraper.Fetch(
  125. url,
  126. entry.Feed.ScraperRules,
  127. entry.Feed.UserAgent,
  128. entry.Feed.Cookie,
  129. feed.AllowSelfSignedCertificates,
  130. feed.FetchViaProxy,
  131. )
  132. if config.Opts.HasMetricsCollector() {
  133. status := "success"
  134. if scraperErr != nil {
  135. status = "error"
  136. }
  137. metric.ScraperRequestDuration.WithLabelValues(status).Observe(time.Since(startTime).Seconds())
  138. }
  139. if scraperErr != nil {
  140. return scraperErr
  141. }
  142. if content != "" {
  143. entry.Content = content
  144. entry.ReadingTime = calculateReadingTime(content, user)
  145. }
  146. rewrite.Rewriter(url, entry, entry.Feed.RewriteRules)
  147. entry.Content = sanitizer.Sanitize(url, entry.Content)
  148. return nil
  149. }
  150. func getUrlFromEntry(feed *model.Feed, entry *model.Entry) string {
  151. var url = entry.URL
  152. if feed.UrlRewriteRules != "" {
  153. parts := customReplaceRuleRegex.FindStringSubmatch(feed.UrlRewriteRules)
  154. if len(parts) >= 3 {
  155. re := regexp.MustCompile(parts[1])
  156. url = re.ReplaceAllString(entry.URL, parts[2])
  157. logger.Debug(`[Processor] Rewriting entry URL %s to %s`, entry.URL, url)
  158. } else {
  159. logger.Debug("[Processor] Cannot find search and replace terms for replace rule %s", feed.UrlRewriteRules)
  160. }
  161. }
  162. return url
  163. }
  164. func updateEntryReadingTime(store *storage.Storage, feed *model.Feed, entry *model.Entry, entryIsNew bool, user *model.User) {
  165. if shouldFetchYouTubeWatchTime(entry) {
  166. if entryIsNew {
  167. watchTime, err := fetchYouTubeWatchTime(entry.URL)
  168. if err != nil {
  169. logger.Error("[Processor] Unable to fetch YouTube watch time: %q => %v", entry.URL, err)
  170. }
  171. entry.ReadingTime = watchTime
  172. } else {
  173. entry.ReadingTime = store.GetReadTime(entry, feed)
  174. }
  175. }
  176. // Handle YT error case and non-YT entries.
  177. if entry.ReadingTime == 0 {
  178. entry.ReadingTime = calculateReadingTime(entry.Content, user)
  179. }
  180. }
  181. func shouldFetchYouTubeWatchTime(entry *model.Entry) bool {
  182. if !config.Opts.FetchYouTubeWatchTime() {
  183. return false
  184. }
  185. matches := youtubeRegex.FindStringSubmatch(entry.URL)
  186. urlMatchesYouTubePattern := len(matches) == 2
  187. return urlMatchesYouTubePattern
  188. }
  189. func fetchYouTubeWatchTime(url string) (int, error) {
  190. clt := client.NewClientWithConfig(url, config.Opts)
  191. response, browserErr := browser.Exec(clt)
  192. if browserErr != nil {
  193. return 0, browserErr
  194. }
  195. doc, docErr := goquery.NewDocumentFromReader(response.Body)
  196. if docErr != nil {
  197. return 0, docErr
  198. }
  199. durs, exists := doc.Find(`meta[itemprop="duration"]`).First().Attr("content")
  200. if !exists {
  201. return 0, errors.New("duration has not found")
  202. }
  203. dur, err := parseISO8601(durs)
  204. if err != nil {
  205. return 0, fmt.Errorf("unable to parse duration %s: %v", durs, err)
  206. }
  207. return int(dur.Minutes()), nil
  208. }
  209. // parseISO8601 parses an ISO 8601 duration string.
  210. func parseISO8601(from string) (time.Duration, error) {
  211. var match []string
  212. var d time.Duration
  213. if iso8601Regex.MatchString(from) {
  214. match = iso8601Regex.FindStringSubmatch(from)
  215. } else {
  216. return 0, errors.New("could not parse duration string")
  217. }
  218. for i, name := range iso8601Regex.SubexpNames() {
  219. part := match[i]
  220. if i == 0 || name == "" || part == "" {
  221. continue
  222. }
  223. val, err := strconv.ParseInt(part, 10, 64)
  224. if err != nil {
  225. return 0, err
  226. }
  227. switch name {
  228. case "hour":
  229. d = d + (time.Duration(val) * time.Hour)
  230. case "minute":
  231. d = d + (time.Duration(val) * time.Minute)
  232. case "second":
  233. d = d + (time.Duration(val) * time.Second)
  234. default:
  235. return 0, fmt.Errorf("unknown field %s", name)
  236. }
  237. }
  238. return d, nil
  239. }
  240. func calculateReadingTime(content string, user *model.User) int {
  241. sanitizedContent := sanitizer.StripTags(content)
  242. languageInfo := getlang.FromString(sanitizedContent)
  243. var timeToReadInt int
  244. if languageInfo.LanguageCode() == "ko" || languageInfo.LanguageCode() == "zh" || languageInfo.LanguageCode() == "jp" {
  245. timeToReadInt = int(math.Ceil(float64(utf8.RuneCountInString(sanitizedContent)) / float64(user.CJKReadingSpeed)))
  246. } else {
  247. nbOfWords := len(strings.Fields(sanitizedContent))
  248. timeToReadInt = int(math.Ceil(float64(nbOfWords) / float64(user.DefaultReadingSpeed)))
  249. }
  250. return timeToReadInt
  251. }