processor.go 8.3 KB

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