4
0

handler.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. icon.NewIconChecker(store, subscription).UpdateOrCreateFeedIcon()
  85. return subscription, nil
  86. }
  87. // CreateFeed fetch, parse and store a new feed.
  88. func CreateFeed(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequest) (*model.Feed, *locale.LocalizedErrorWrapper) {
  89. slog.Debug("Begin feed creation process",
  90. slog.Int64("user_id", userID),
  91. slog.String("feed_url", feedCreationRequest.FeedURL),
  92. slog.String("proxy_url", feedCreationRequest.ProxyURL),
  93. )
  94. if !store.CategoryIDExists(userID, feedCreationRequest.CategoryID) {
  95. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  96. }
  97. requestBuilder := fetcher.NewRequestBuilder().
  98. WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password).
  99. WithUserAgent(feedCreationRequest.UserAgent, config.Opts.HTTPClientUserAgent()).
  100. WithCookie(feedCreationRequest.Cookie).
  101. WithTimeout(config.Opts.HTTPClientTimeout()).
  102. WithProxyRotator(proxyrotator.ProxyRotatorInstance).
  103. WithCustomFeedProxyURL(feedCreationRequest.ProxyURL).
  104. WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL()).
  105. UseCustomApplicationProxyURL(feedCreationRequest.FetchViaProxy).
  106. IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates).
  107. DisableHTTP2(feedCreationRequest.DisableHTTP2)
  108. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(feedCreationRequest.FeedURL))
  109. defer responseHandler.Close()
  110. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  111. slog.Warn("Unable to fetch feed", slog.String("feed_url", feedCreationRequest.FeedURL), slog.Any("error", localizedError.Error()))
  112. return nil, localizedError
  113. }
  114. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  115. if localizedError != nil {
  116. slog.Warn("Unable to fetch feed", slog.String("feed_url", feedCreationRequest.FeedURL), slog.Any("error", localizedError.Error()))
  117. return nil, localizedError
  118. }
  119. if store.FeedURLExists(userID, responseHandler.EffectiveURL()) {
  120. return nil, locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  121. }
  122. subscription, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), bytes.NewReader(responseBody))
  123. if parseErr != nil {
  124. return nil, locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  125. }
  126. subscription.UserID = userID
  127. subscription.UserAgent = feedCreationRequest.UserAgent
  128. subscription.Cookie = feedCreationRequest.Cookie
  129. subscription.Username = feedCreationRequest.Username
  130. subscription.Password = feedCreationRequest.Password
  131. subscription.Crawler = feedCreationRequest.Crawler
  132. subscription.IgnoreEntryUpdates = feedCreationRequest.IgnoreEntryUpdates
  133. subscription.Disabled = feedCreationRequest.Disabled
  134. subscription.IgnoreHTTPCache = feedCreationRequest.IgnoreHTTPCache
  135. subscription.AllowSelfSignedCertificates = feedCreationRequest.AllowSelfSignedCertificates
  136. subscription.DisableHTTP2 = feedCreationRequest.DisableHTTP2
  137. subscription.FetchViaProxy = feedCreationRequest.FetchViaProxy
  138. subscription.ScraperRules = feedCreationRequest.ScraperRules
  139. subscription.RewriteRules = feedCreationRequest.RewriteRules
  140. subscription.UrlRewriteRules = feedCreationRequest.UrlRewriteRules
  141. subscription.BlocklistRules = feedCreationRequest.BlocklistRules
  142. subscription.KeeplistRules = feedCreationRequest.KeeplistRules
  143. subscription.BlockFilterEntryRules = feedCreationRequest.BlockFilterEntryRules
  144. subscription.KeepFilterEntryRules = feedCreationRequest.KeepFilterEntryRules
  145. subscription.HideGlobally = feedCreationRequest.HideGlobally
  146. subscription.NoMediaPlayer = feedCreationRequest.NoMediaPlayer
  147. subscription.EtagHeader = responseHandler.ETag()
  148. subscription.LastModifiedHeader = responseHandler.LastModified()
  149. subscription.FeedURL = responseHandler.EffectiveURL()
  150. subscription.ProxyURL = feedCreationRequest.ProxyURL
  151. subscription.WithCategoryID(feedCreationRequest.CategoryID)
  152. subscription.CheckedNow()
  153. processor.ProcessFeedEntries(store, subscription, userID, true)
  154. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  155. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  156. }
  157. slog.Debug("Created feed",
  158. slog.Int64("user_id", userID),
  159. slog.Int64("feed_id", subscription.ID),
  160. slog.String("feed_url", subscription.FeedURL),
  161. )
  162. icon.NewIconChecker(store, subscription).UpdateOrCreateFeedIcon()
  163. return subscription, nil
  164. }
  165. // RefreshFeed refreshes a feed.
  166. func RefreshFeed(store *storage.Storage, userID, feedID int64, forceRefresh bool) *locale.LocalizedErrorWrapper {
  167. slog.Debug("Begin feed refresh process",
  168. slog.Int64("user_id", userID),
  169. slog.Int64("feed_id", feedID),
  170. slog.Bool("force_refresh", forceRefresh),
  171. )
  172. originalFeed, storeErr := store.FeedByID(userID, feedID)
  173. if storeErr != nil {
  174. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  175. }
  176. if originalFeed == nil {
  177. return locale.NewLocalizedErrorWrapper(ErrFeedNotFound, "error.feed_not_found")
  178. }
  179. weeklyEntryCount := 0
  180. if config.Opts.PollingScheduler() == model.SchedulerEntryFrequency {
  181. var weeklyCountErr error
  182. weeklyEntryCount, weeklyCountErr = store.WeeklyFeedEntryCount(userID, feedID)
  183. if weeklyCountErr != nil {
  184. return locale.NewLocalizedErrorWrapper(weeklyCountErr, "error.database_error", weeklyCountErr)
  185. }
  186. }
  187. originalFeed.CheckedNow()
  188. originalFeed.ScheduleNextCheck(weeklyEntryCount, time.Duration(0))
  189. requestBuilder := fetcher.NewRequestBuilder().
  190. WithUsernameAndPassword(originalFeed.Username, originalFeed.Password).
  191. WithUserAgent(originalFeed.UserAgent, config.Opts.HTTPClientUserAgent()).
  192. WithCookie(originalFeed.Cookie).
  193. WithTimeout(config.Opts.HTTPClientTimeout()).
  194. WithProxyRotator(proxyrotator.ProxyRotatorInstance).
  195. WithCustomFeedProxyURL(originalFeed.ProxyURL).
  196. WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL()).
  197. UseCustomApplicationProxyURL(originalFeed.FetchViaProxy).
  198. IgnoreTLSErrors(originalFeed.AllowSelfSignedCertificates).
  199. DisableHTTP2(originalFeed.DisableHTTP2)
  200. ignoreHTTPCache := originalFeed.IgnoreHTTPCache || forceRefresh
  201. if !ignoreHTTPCache {
  202. requestBuilder = requestBuilder.
  203. WithETag(originalFeed.EtagHeader).
  204. WithLastModified(originalFeed.LastModifiedHeader)
  205. }
  206. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(originalFeed.FeedURL))
  207. defer responseHandler.Close()
  208. if responseHandler.IsRateLimited() {
  209. retryDelay := responseHandler.ParseRetryDelay()
  210. calculatedNextCheckInterval := originalFeed.ScheduleNextCheck(weeklyEntryCount, retryDelay)
  211. slog.Warn("Feed is rate limited",
  212. slog.String("feed_url", originalFeed.FeedURL),
  213. slog.Int("retry_delay_in_seconds", int(retryDelay.Seconds())),
  214. slog.Int("calculated_next_check_interval_in_minutes", int(calculatedNextCheckInterval.Minutes())),
  215. slog.Time("new_next_check_at", originalFeed.NextCheckAt),
  216. )
  217. }
  218. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  219. slog.Warn("Unable to fetch feed",
  220. slog.Int64("user_id", userID),
  221. slog.Int64("feed_id", feedID),
  222. slog.String("feed_url", originalFeed.FeedURL),
  223. slog.Any("error", localizedError.Error()),
  224. )
  225. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  226. }
  227. if store.AnotherFeedURLExists(userID, originalFeed.ID, responseHandler.EffectiveURL()) {
  228. localizedError := locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  229. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  230. }
  231. if ignoreHTTPCache || responseHandler.IsModified(originalFeed.EtagHeader, originalFeed.LastModifiedHeader) {
  232. slog.Debug("Feed modified",
  233. slog.Int64("user_id", userID),
  234. slog.Int64("feed_id", feedID),
  235. slog.String("etag_header", originalFeed.EtagHeader),
  236. slog.String("last_modified_header", originalFeed.LastModifiedHeader),
  237. )
  238. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  239. if localizedError != nil {
  240. slog.Warn("Unable to fetch feed", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  241. return localizedError
  242. }
  243. updatedFeed, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), bytes.NewReader(responseBody))
  244. if parseErr != nil {
  245. localizedError := locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  246. if errors.Is(parseErr, parser.ErrFeedFormatNotDetected) {
  247. localizedError = locale.NewLocalizedErrorWrapper(parseErr, "error.feed_format_not_detected", parseErr)
  248. }
  249. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  250. }
  251. // Use the RSS TTL value, or the Cache-Control or Expires HTTP headers if available.
  252. // Otherwise, we use the default value from the configuration (min interval parameter).
  253. feedTTLValue := updatedFeed.TTL
  254. cacheControlMaxAgeValue := responseHandler.CacheControlMaxAge()
  255. expiresValue := responseHandler.Expires()
  256. refreshDelay := max(feedTTLValue, cacheControlMaxAgeValue, expiresValue)
  257. // Set the next check at with updated arguments.
  258. calculatedNextCheckInterval := originalFeed.ScheduleNextCheck(weeklyEntryCount, refreshDelay)
  259. slog.Debug("Updated next check date",
  260. slog.Int64("user_id", userID),
  261. slog.Int64("feed_id", feedID),
  262. slog.String("feed_url", originalFeed.FeedURL),
  263. slog.Int("feed_ttl_minutes", int(feedTTLValue.Minutes())),
  264. slog.Int("cache_control_max_age_in_minutes", int(cacheControlMaxAgeValue.Minutes())),
  265. slog.Int("expires_in_minutes", int(expiresValue.Minutes())),
  266. slog.Int("refresh_delay_in_minutes", int(refreshDelay.Minutes())),
  267. slog.Int("calculated_next_check_interval_in_minutes", int(calculatedNextCheckInterval.Minutes())),
  268. slog.Time("new_next_check_at", originalFeed.NextCheckAt),
  269. )
  270. originalFeed.Entries = updatedFeed.Entries
  271. processor.ProcessFeedEntries(store, originalFeed, userID, forceRefresh)
  272. // We don't update existing entries when the crawler is enabled (we crawl only inexisting entries).
  273. // We also skip updating existing entries if the feed has ignore_entry_updates enabled.
  274. // Unless it is forced to refresh.
  275. updateExistingEntries := forceRefresh || (!originalFeed.Crawler && !originalFeed.IgnoreEntryUpdates)
  276. newEntries, storeErr := store.RefreshFeedEntries(originalFeed.UserID, originalFeed.ID, originalFeed.Entries, updateExistingEntries)
  277. if storeErr != nil {
  278. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  279. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  280. }
  281. userIntegrations, intErr := store.Integration(userID)
  282. if intErr != nil {
  283. slog.Error("Fetching integrations failed; the refresh process will go on, but no integrations will run this time",
  284. slog.Int64("user_id", userID),
  285. slog.Int64("feed_id", feedID),
  286. slog.Any("error", intErr),
  287. )
  288. } else if userIntegrations != nil && len(newEntries) > 0 {
  289. go integration.PushEntries(originalFeed, newEntries, userIntegrations)
  290. }
  291. originalFeed.EtagHeader = responseHandler.ETag()
  292. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  293. originalFeed.Language = updatedFeed.Language
  294. originalFeed.IconURL = updatedFeed.IconURL
  295. iconChecker := icon.NewIconChecker(store, originalFeed)
  296. if forceRefresh {
  297. iconChecker.UpdateOrCreateFeedIcon()
  298. } else {
  299. iconChecker.CreateFeedIconIfMissing()
  300. }
  301. } else {
  302. slog.Debug("Feed not modified",
  303. slog.Int64("user_id", userID),
  304. slog.Int64("feed_id", feedID),
  305. )
  306. // Last-Modified may be updated even if ETag is not. In this case, per
  307. // RFC9111 sections 3.2 and 4.3.4, the stored response must be updated.
  308. if responseHandler.LastModified() != "" {
  309. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  310. }
  311. }
  312. originalFeed.ResetErrorCounter()
  313. if storeErr := store.UpdateFeed(originalFeed); storeErr != nil {
  314. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  315. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  316. }
  317. return nil
  318. }