processor.go 8.9 KB

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