handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package handler // import "miniflux.app/v2/internal/reader/handler"
  4. import (
  5. "bytes"
  6. "errors"
  7. "log/slog"
  8. "time"
  9. "miniflux.app/v2/internal/config"
  10. "miniflux.app/v2/internal/integration"
  11. "miniflux.app/v2/internal/locale"
  12. "miniflux.app/v2/internal/model"
  13. "miniflux.app/v2/internal/proxyrotator"
  14. "miniflux.app/v2/internal/reader/fetcher"
  15. "miniflux.app/v2/internal/reader/icon"
  16. "miniflux.app/v2/internal/reader/parser"
  17. "miniflux.app/v2/internal/reader/processor"
  18. "miniflux.app/v2/internal/storage"
  19. )
  20. var (
  21. ErrCategoryNotFound = errors.New("fetcher: category not found")
  22. ErrFeedNotFound = errors.New("fetcher: feed not found")
  23. ErrDuplicatedFeed = errors.New("fetcher: duplicated feed")
  24. )
  25. func getTranslatedLocalizedError(store *storage.Storage, userID int64, originalFeed *model.Feed, localizedError *locale.LocalizedErrorWrapper) *locale.LocalizedErrorWrapper {
  26. user, storeErr := store.UserByID(userID)
  27. if storeErr != nil {
  28. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  29. }
  30. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  31. store.UpdateFeedError(originalFeed)
  32. return localizedError
  33. }
  34. func CreateFeedFromSubscriptionDiscovery(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequestFromSubscriptionDiscovery) (*model.Feed, *locale.LocalizedErrorWrapper) {
  35. slog.Debug("Begin feed creation process from subscription discovery",
  36. slog.Int64("user_id", userID),
  37. slog.String("feed_url", feedCreationRequest.FeedURL),
  38. slog.String("proxy_url", feedCreationRequest.ProxyURL),
  39. )
  40. if !store.CategoryIDExists(userID, feedCreationRequest.CategoryID) {
  41. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  42. }
  43. if store.FeedURLExists(userID, feedCreationRequest.FeedURL) {
  44. return nil, locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  45. }
  46. subscription, parseErr := parser.ParseFeed(feedCreationRequest.FeedURL, feedCreationRequest.Content)
  47. if parseErr != nil {
  48. return nil, locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  49. }
  50. subscription.UserID = userID
  51. subscription.UserAgent = feedCreationRequest.UserAgent
  52. subscription.Cookie = feedCreationRequest.Cookie
  53. subscription.Username = feedCreationRequest.Username
  54. subscription.Password = feedCreationRequest.Password
  55. subscription.Crawler = feedCreationRequest.Crawler
  56. subscription.IgnoreEntryUpdates = feedCreationRequest.IgnoreEntryUpdates
  57. subscription.Disabled = feedCreationRequest.Disabled
  58. subscription.IgnoreHTTPCache = feedCreationRequest.IgnoreHTTPCache
  59. subscription.AllowSelfSignedCertificates = feedCreationRequest.AllowSelfSignedCertificates
  60. subscription.FetchViaProxy = feedCreationRequest.FetchViaProxy
  61. subscription.ScraperRules = feedCreationRequest.ScraperRules
  62. subscription.RewriteRules = feedCreationRequest.RewriteRules
  63. subscription.BlocklistRules = feedCreationRequest.BlocklistRules
  64. subscription.KeeplistRules = feedCreationRequest.KeeplistRules
  65. subscription.UrlRewriteRules = feedCreationRequest.UrlRewriteRules
  66. subscription.BlockFilterEntryRules = feedCreationRequest.BlockFilterEntryRules
  67. subscription.KeepFilterEntryRules = feedCreationRequest.KeepFilterEntryRules
  68. subscription.EtagHeader = feedCreationRequest.ETag
  69. subscription.LastModifiedHeader = feedCreationRequest.LastModified
  70. subscription.FeedURL = feedCreationRequest.FeedURL
  71. subscription.DisableHTTP2 = feedCreationRequest.DisableHTTP2
  72. subscription.WithCategoryID(feedCreationRequest.CategoryID)
  73. subscription.ProxyURL = feedCreationRequest.ProxyURL
  74. subscription.CheckedNow()
  75. processor.ProcessFeedEntries(store, subscription, userID, true)
  76. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  77. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  78. }
  79. slog.Debug("Created feed",
  80. slog.Int64("user_id", userID),
  81. slog.Int64("feed_id", subscription.ID),
  82. slog.String("feed_url", subscription.FeedURL),
  83. )
  84. requestBuilder := fetcher.NewRequestBuilder()
  85. requestBuilder.WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password)
  86. requestBuilder.WithUserAgent(feedCreationRequest.UserAgent, config.Opts.HTTPClientUserAgent())
  87. requestBuilder.WithCookie(feedCreationRequest.Cookie)
  88. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  89. requestBuilder.WithProxyRotator(proxyrotator.ProxyRotatorInstance)
  90. requestBuilder.WithCustomFeedProxyURL(feedCreationRequest.ProxyURL)
  91. requestBuilder.WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL())
  92. requestBuilder.UseCustomApplicationProxyURL(feedCreationRequest.FetchViaProxy)
  93. requestBuilder.IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates)
  94. requestBuilder.DisableHTTP2(feedCreationRequest.DisableHTTP2)
  95. icon.NewIconChecker(store, subscription).UpdateOrCreateFeedIcon()
  96. return subscription, nil
  97. }
  98. // CreateFeed fetch, parse and store a new feed.
  99. func CreateFeed(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequest) (*model.Feed, *locale.LocalizedErrorWrapper) {
  100. slog.Debug("Begin feed creation process",
  101. slog.Int64("user_id", userID),
  102. slog.String("feed_url", feedCreationRequest.FeedURL),
  103. slog.String("proxy_url", feedCreationRequest.ProxyURL),
  104. )
  105. if !store.CategoryIDExists(userID, feedCreationRequest.CategoryID) {
  106. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  107. }
  108. requestBuilder := fetcher.NewRequestBuilder()
  109. requestBuilder.WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password)
  110. requestBuilder.WithUserAgent(feedCreationRequest.UserAgent, config.Opts.HTTPClientUserAgent())
  111. requestBuilder.WithCookie(feedCreationRequest.Cookie)
  112. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  113. requestBuilder.WithProxyRotator(proxyrotator.ProxyRotatorInstance)
  114. requestBuilder.WithCustomFeedProxyURL(feedCreationRequest.ProxyURL)
  115. requestBuilder.WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL())
  116. requestBuilder.UseCustomApplicationProxyURL(feedCreationRequest.FetchViaProxy)
  117. requestBuilder.IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates)
  118. requestBuilder.DisableHTTP2(feedCreationRequest.DisableHTTP2)
  119. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(feedCreationRequest.FeedURL))
  120. defer responseHandler.Close()
  121. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  122. slog.Warn("Unable to fetch feed", slog.String("feed_url", feedCreationRequest.FeedURL), slog.Any("error", localizedError.Error()))
  123. return nil, localizedError
  124. }
  125. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  126. if localizedError != nil {
  127. slog.Warn("Unable to fetch feed", slog.String("feed_url", feedCreationRequest.FeedURL), slog.Any("error", localizedError.Error()))
  128. return nil, localizedError
  129. }
  130. if store.FeedURLExists(userID, responseHandler.EffectiveURL()) {
  131. return nil, locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  132. }
  133. subscription, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), bytes.NewReader(responseBody))
  134. if parseErr != nil {
  135. return nil, locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  136. }
  137. subscription.UserID = userID
  138. subscription.UserAgent = feedCreationRequest.UserAgent
  139. subscription.Cookie = feedCreationRequest.Cookie
  140. subscription.Username = feedCreationRequest.Username
  141. subscription.Password = feedCreationRequest.Password
  142. subscription.Crawler = feedCreationRequest.Crawler
  143. subscription.IgnoreEntryUpdates = feedCreationRequest.IgnoreEntryUpdates
  144. subscription.Disabled = feedCreationRequest.Disabled
  145. subscription.IgnoreHTTPCache = feedCreationRequest.IgnoreHTTPCache
  146. subscription.AllowSelfSignedCertificates = feedCreationRequest.AllowSelfSignedCertificates
  147. subscription.DisableHTTP2 = feedCreationRequest.DisableHTTP2
  148. subscription.FetchViaProxy = feedCreationRequest.FetchViaProxy
  149. subscription.ScraperRules = feedCreationRequest.ScraperRules
  150. subscription.RewriteRules = feedCreationRequest.RewriteRules
  151. subscription.UrlRewriteRules = feedCreationRequest.UrlRewriteRules
  152. subscription.BlocklistRules = feedCreationRequest.BlocklistRules
  153. subscription.KeeplistRules = feedCreationRequest.KeeplistRules
  154. subscription.BlockFilterEntryRules = feedCreationRequest.BlockFilterEntryRules
  155. subscription.KeepFilterEntryRules = feedCreationRequest.KeepFilterEntryRules
  156. subscription.HideGlobally = feedCreationRequest.HideGlobally
  157. subscription.EtagHeader = responseHandler.ETag()
  158. subscription.LastModifiedHeader = responseHandler.LastModified()
  159. subscription.FeedURL = responseHandler.EffectiveURL()
  160. subscription.ProxyURL = feedCreationRequest.ProxyURL
  161. subscription.WithCategoryID(feedCreationRequest.CategoryID)
  162. subscription.CheckedNow()
  163. processor.ProcessFeedEntries(store, subscription, userID, true)
  164. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  165. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  166. }
  167. slog.Debug("Created feed",
  168. slog.Int64("user_id", userID),
  169. slog.Int64("feed_id", subscription.ID),
  170. slog.String("feed_url", subscription.FeedURL),
  171. )
  172. icon.NewIconChecker(store, subscription).UpdateOrCreateFeedIcon()
  173. return subscription, nil
  174. }
  175. // RefreshFeed refreshes a feed.
  176. func RefreshFeed(store *storage.Storage, userID, feedID int64, forceRefresh bool) *locale.LocalizedErrorWrapper {
  177. slog.Debug("Begin feed refresh process",
  178. slog.Int64("user_id", userID),
  179. slog.Int64("feed_id", feedID),
  180. slog.Bool("force_refresh", forceRefresh),
  181. )
  182. originalFeed, storeErr := store.FeedByID(userID, feedID)
  183. if storeErr != nil {
  184. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  185. }
  186. if originalFeed == nil {
  187. return locale.NewLocalizedErrorWrapper(ErrFeedNotFound, "error.feed_not_found")
  188. }
  189. weeklyEntryCount := 0
  190. if config.Opts.PollingScheduler() == model.SchedulerEntryFrequency {
  191. var weeklyCountErr error
  192. weeklyEntryCount, weeklyCountErr = store.WeeklyFeedEntryCount(userID, feedID)
  193. if weeklyCountErr != nil {
  194. return locale.NewLocalizedErrorWrapper(weeklyCountErr, "error.database_error", weeklyCountErr)
  195. }
  196. }
  197. originalFeed.CheckedNow()
  198. originalFeed.ScheduleNextCheck(weeklyEntryCount, time.Duration(0))
  199. requestBuilder := fetcher.NewRequestBuilder()
  200. requestBuilder.WithUsernameAndPassword(originalFeed.Username, originalFeed.Password)
  201. requestBuilder.WithUserAgent(originalFeed.UserAgent, config.Opts.HTTPClientUserAgent())
  202. requestBuilder.WithCookie(originalFeed.Cookie)
  203. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  204. requestBuilder.WithProxyRotator(proxyrotator.ProxyRotatorInstance)
  205. requestBuilder.WithCustomFeedProxyURL(originalFeed.ProxyURL)
  206. requestBuilder.WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL())
  207. requestBuilder.UseCustomApplicationProxyURL(originalFeed.FetchViaProxy)
  208. requestBuilder.IgnoreTLSErrors(originalFeed.AllowSelfSignedCertificates)
  209. requestBuilder.DisableHTTP2(originalFeed.DisableHTTP2)
  210. ignoreHTTPCache := originalFeed.IgnoreHTTPCache || forceRefresh
  211. if !ignoreHTTPCache {
  212. requestBuilder.WithETag(originalFeed.EtagHeader)
  213. requestBuilder.WithLastModified(originalFeed.LastModifiedHeader)
  214. }
  215. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(originalFeed.FeedURL))
  216. defer responseHandler.Close()
  217. if responseHandler.IsRateLimited() {
  218. retryDelay := responseHandler.ParseRetryDelay()
  219. calculatedNextCheckInterval := originalFeed.ScheduleNextCheck(weeklyEntryCount, retryDelay)
  220. slog.Warn("Feed is rate limited",
  221. slog.String("feed_url", originalFeed.FeedURL),
  222. slog.Int("retry_delay_in_seconds", int(retryDelay.Seconds())),
  223. slog.Int("calculated_next_check_interval_in_minutes", int(calculatedNextCheckInterval.Minutes())),
  224. slog.Time("new_next_check_at", originalFeed.NextCheckAt),
  225. )
  226. }
  227. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  228. slog.Warn("Unable to fetch feed",
  229. slog.Int64("user_id", userID),
  230. slog.Int64("feed_id", feedID),
  231. slog.String("feed_url", originalFeed.FeedURL),
  232. slog.Any("error", localizedError.Error()),
  233. )
  234. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  235. }
  236. if store.AnotherFeedURLExists(userID, originalFeed.ID, responseHandler.EffectiveURL()) {
  237. localizedError := locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  238. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  239. }
  240. if ignoreHTTPCache || responseHandler.IsModified(originalFeed.EtagHeader, originalFeed.LastModifiedHeader) {
  241. slog.Debug("Feed modified",
  242. slog.Int64("user_id", userID),
  243. slog.Int64("feed_id", feedID),
  244. slog.String("etag_header", originalFeed.EtagHeader),
  245. slog.String("last_modified_header", originalFeed.LastModifiedHeader),
  246. )
  247. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  248. if localizedError != nil {
  249. slog.Warn("Unable to fetch feed", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  250. return localizedError
  251. }
  252. updatedFeed, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), bytes.NewReader(responseBody))
  253. if parseErr != nil {
  254. localizedError := locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  255. if errors.Is(parseErr, parser.ErrFeedFormatNotDetected) {
  256. localizedError = locale.NewLocalizedErrorWrapper(parseErr, "error.feed_format_not_detected", parseErr)
  257. }
  258. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  259. }
  260. // Use the RSS TTL value, or the Cache-Control or Expires HTTP headers if available.
  261. // Otherwise, we use the default value from the configuration (min interval parameter).
  262. feedTTLValue := updatedFeed.TTL
  263. cacheControlMaxAgeValue := responseHandler.CacheControlMaxAge()
  264. expiresValue := responseHandler.Expires()
  265. refreshDelay := max(feedTTLValue, cacheControlMaxAgeValue, expiresValue)
  266. // Set the next check at with updated arguments.
  267. calculatedNextCheckInterval := originalFeed.ScheduleNextCheck(weeklyEntryCount, refreshDelay)
  268. slog.Debug("Updated next check date",
  269. slog.Int64("user_id", userID),
  270. slog.Int64("feed_id", feedID),
  271. slog.String("feed_url", originalFeed.FeedURL),
  272. slog.Int("feed_ttl_minutes", int(feedTTLValue.Minutes())),
  273. slog.Int("cache_control_max_age_in_minutes", int(cacheControlMaxAgeValue.Minutes())),
  274. slog.Int("expires_in_minutes", int(expiresValue.Minutes())),
  275. slog.Int("refresh_delay_in_minutes", int(refreshDelay.Minutes())),
  276. slog.Int("calculated_next_check_interval_in_minutes", int(calculatedNextCheckInterval.Minutes())),
  277. slog.Time("new_next_check_at", originalFeed.NextCheckAt),
  278. )
  279. originalFeed.Entries = updatedFeed.Entries
  280. processor.ProcessFeedEntries(store, originalFeed, userID, forceRefresh)
  281. // We don't update existing entries when the crawler is enabled (we crawl only inexisting entries).
  282. // We also skip updating existing entries if the feed has ignore_entry_updates enabled.
  283. // Unless it is forced to refresh.
  284. updateExistingEntries := forceRefresh || (!originalFeed.Crawler && !originalFeed.IgnoreEntryUpdates)
  285. newEntries, storeErr := store.RefreshFeedEntries(originalFeed.UserID, originalFeed.ID, originalFeed.Entries, updateExistingEntries)
  286. if storeErr != nil {
  287. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  288. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  289. }
  290. userIntegrations, intErr := store.Integration(userID)
  291. if intErr != nil {
  292. slog.Error("Fetching integrations failed; the refresh process will go on, but no integrations will run this time",
  293. slog.Int64("user_id", userID),
  294. slog.Int64("feed_id", feedID),
  295. slog.Any("error", intErr),
  296. )
  297. } else if userIntegrations != nil && len(newEntries) > 0 {
  298. go integration.PushEntries(originalFeed, newEntries, userIntegrations)
  299. }
  300. originalFeed.EtagHeader = responseHandler.ETag()
  301. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  302. originalFeed.IconURL = updatedFeed.IconURL
  303. iconChecker := icon.NewIconChecker(store, originalFeed)
  304. if forceRefresh {
  305. iconChecker.UpdateOrCreateFeedIcon()
  306. } else {
  307. iconChecker.CreateFeedIconIfMissing()
  308. }
  309. } else {
  310. slog.Debug("Feed not modified",
  311. slog.Int64("user_id", userID),
  312. slog.Int64("feed_id", feedID),
  313. )
  314. // Last-Modified may be updated even if ETag is not. In this case, per
  315. // RFC9111 sections 3.2 and 4.3.4, the stored response must be updated.
  316. if responseHandler.LastModified() != "" {
  317. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  318. }
  319. }
  320. originalFeed.ResetErrorCounter()
  321. if storeErr := store.UpdateFeed(originalFeed); storeErr != nil {
  322. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  323. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  324. }
  325. return nil
  326. }