handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. "miniflux.app/v2/internal/urllib"
  20. )
  21. var (
  22. ErrCategoryNotFound = errors.New("fetcher: category not found")
  23. ErrFeedNotFound = errors.New("fetcher: feed not found")
  24. ErrDuplicatedFeed = errors.New("fetcher: duplicated feed")
  25. )
  26. func getTranslatedLocalizedError(store *storage.Storage, userID int64, originalFeed *model.Feed, localizedError *locale.LocalizedErrorWrapper) *locale.LocalizedErrorWrapper {
  27. user, storeErr := store.UserByID(userID)
  28. if storeErr != nil {
  29. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  30. }
  31. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  32. store.UpdateFeedError(originalFeed)
  33. return localizedError
  34. }
  35. func CreateFeedFromSubscriptionDiscovery(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequestFromSubscriptionDiscovery) (*model.Feed, *locale.LocalizedErrorWrapper) {
  36. slog.Debug("Begin feed creation process from subscription discovery",
  37. slog.Int64("user_id", userID),
  38. slog.String("feed_url", urllib.RedactedURL(feedCreationRequest.FeedURL)),
  39. slog.String("proxy_url", feedCreationRequest.ProxyURL),
  40. )
  41. categoryExists, storeErr := store.CategoryIDExists(userID, feedCreationRequest.CategoryID)
  42. if storeErr != nil {
  43. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  44. }
  45. if !categoryExists {
  46. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  47. }
  48. if store.FeedURLExists(userID, feedCreationRequest.FeedURL) {
  49. return nil, locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  50. }
  51. subscription, parseErr := parser.ParseFeed(feedCreationRequest.FeedURL, feedCreationRequest.Content)
  52. if parseErr != nil {
  53. return nil, locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  54. }
  55. subscription.UserID = userID
  56. subscription.UserAgent = feedCreationRequest.UserAgent
  57. subscription.Cookie = feedCreationRequest.Cookie
  58. subscription.Username = feedCreationRequest.Username
  59. subscription.Password = feedCreationRequest.Password
  60. subscription.Crawler = feedCreationRequest.Crawler
  61. subscription.IgnoreEntryUpdates = feedCreationRequest.IgnoreEntryUpdates
  62. subscription.Disabled = feedCreationRequest.Disabled
  63. subscription.IgnoreHTTPCache = feedCreationRequest.IgnoreHTTPCache
  64. subscription.AllowSelfSignedCertificates = feedCreationRequest.AllowSelfSignedCertificates
  65. subscription.FetchViaProxy = feedCreationRequest.FetchViaProxy
  66. subscription.ScraperRules = feedCreationRequest.ScraperRules
  67. subscription.RewriteRules = feedCreationRequest.RewriteRules
  68. subscription.BlocklistRules = feedCreationRequest.BlocklistRules
  69. subscription.KeeplistRules = feedCreationRequest.KeeplistRules
  70. subscription.UrlRewriteRules = feedCreationRequest.UrlRewriteRules
  71. subscription.BlockFilterEntryRules = feedCreationRequest.BlockFilterEntryRules
  72. subscription.KeepFilterEntryRules = feedCreationRequest.KeepFilterEntryRules
  73. subscription.EtagHeader = feedCreationRequest.ETag
  74. subscription.LastModifiedHeader = feedCreationRequest.LastModified
  75. subscription.FeedURL = feedCreationRequest.FeedURL
  76. subscription.DisableHTTP2 = feedCreationRequest.DisableHTTP2
  77. subscription.WithCategoryID(feedCreationRequest.CategoryID)
  78. subscription.ProxyURL = feedCreationRequest.ProxyURL
  79. subscription.CheckedNow()
  80. processor.ProcessFeedEntries(store, subscription, userID, true)
  81. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  82. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  83. }
  84. slog.Debug("Created feed",
  85. slog.Int64("user_id", userID),
  86. slog.Int64("feed_id", subscription.ID),
  87. slog.String("feed_url", urllib.RedactedURL(subscription.FeedURL)),
  88. )
  89. icon.NewIconChecker(store, subscription).UpdateOrCreateFeedIcon()
  90. return subscription, nil
  91. }
  92. // CreateFeed fetch, parse and store a new feed.
  93. func CreateFeed(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequest) (*model.Feed, *locale.LocalizedErrorWrapper) {
  94. slog.Debug("Begin feed creation process",
  95. slog.Int64("user_id", userID),
  96. slog.String("feed_url", urllib.RedactedURL(feedCreationRequest.FeedURL)),
  97. slog.String("proxy_url", feedCreationRequest.ProxyURL),
  98. )
  99. categoryExists, storeErr := store.CategoryIDExists(userID, feedCreationRequest.CategoryID)
  100. if storeErr != nil {
  101. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  102. }
  103. if !categoryExists {
  104. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  105. }
  106. requestBuilder := fetcher.NewRequestBuilder().
  107. WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password).
  108. WithUserAgent(feedCreationRequest.UserAgent, config.Opts.HTTPClientUserAgent()).
  109. WithCookie(feedCreationRequest.Cookie, feedCreationRequest.FeedURL).
  110. WithTimeout(config.Opts.HTTPClientTimeout()).
  111. WithProxyRotator(proxyrotator.ProxyRotatorInstance).
  112. WithCustomFeedProxyURL(feedCreationRequest.ProxyURL).
  113. WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL()).
  114. UseCustomApplicationProxyURL(feedCreationRequest.FetchViaProxy).
  115. IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates).
  116. DisableHTTP2(feedCreationRequest.DisableHTTP2)
  117. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(feedCreationRequest.FeedURL))
  118. defer responseHandler.Close()
  119. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  120. slog.Warn("Unable to fetch feed", slog.String("feed_url", urllib.RedactedURL(feedCreationRequest.FeedURL)), slog.Any("error", localizedError.Error()))
  121. return nil, localizedError
  122. }
  123. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  124. if localizedError != nil {
  125. slog.Warn("Unable to fetch feed", slog.String("feed_url", urllib.RedactedURL(feedCreationRequest.FeedURL)), slog.Any("error", localizedError.Error()))
  126. return nil, localizedError
  127. }
  128. if store.FeedURLExists(userID, responseHandler.EffectiveURL()) {
  129. return nil, locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  130. }
  131. subscription, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), bytes.NewReader(responseBody))
  132. if parseErr != nil {
  133. return nil, locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  134. }
  135. subscription.UserID = userID
  136. subscription.UserAgent = feedCreationRequest.UserAgent
  137. subscription.Cookie = feedCreationRequest.Cookie
  138. subscription.Username = feedCreationRequest.Username
  139. subscription.Password = feedCreationRequest.Password
  140. subscription.Crawler = feedCreationRequest.Crawler
  141. subscription.IgnoreEntryUpdates = feedCreationRequest.IgnoreEntryUpdates
  142. subscription.Disabled = feedCreationRequest.Disabled
  143. subscription.IgnoreHTTPCache = feedCreationRequest.IgnoreHTTPCache
  144. subscription.AllowSelfSignedCertificates = feedCreationRequest.AllowSelfSignedCertificates
  145. subscription.DisableHTTP2 = feedCreationRequest.DisableHTTP2
  146. subscription.FetchViaProxy = feedCreationRequest.FetchViaProxy
  147. subscription.ScraperRules = feedCreationRequest.ScraperRules
  148. subscription.RewriteRules = feedCreationRequest.RewriteRules
  149. subscription.UrlRewriteRules = feedCreationRequest.UrlRewriteRules
  150. subscription.BlocklistRules = feedCreationRequest.BlocklistRules
  151. subscription.KeeplistRules = feedCreationRequest.KeeplistRules
  152. subscription.BlockFilterEntryRules = feedCreationRequest.BlockFilterEntryRules
  153. subscription.KeepFilterEntryRules = feedCreationRequest.KeepFilterEntryRules
  154. subscription.HideGlobally = feedCreationRequest.HideGlobally
  155. subscription.NoMediaPlayer = feedCreationRequest.NoMediaPlayer
  156. subscription.EtagHeader = responseHandler.ETag()
  157. subscription.LastModifiedHeader = responseHandler.LastModified()
  158. subscription.FeedURL = responseHandler.EffectiveURL()
  159. subscription.ProxyURL = feedCreationRequest.ProxyURL
  160. subscription.WithCategoryID(feedCreationRequest.CategoryID)
  161. subscription.CheckedNow()
  162. processor.ProcessFeedEntries(store, subscription, userID, true)
  163. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  164. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  165. }
  166. slog.Debug("Created feed",
  167. slog.Int64("user_id", userID),
  168. slog.Int64("feed_id", subscription.ID),
  169. slog.String("feed_url", urllib.RedactedURL(subscription.FeedURL)),
  170. )
  171. icon.NewIconChecker(store, subscription).UpdateOrCreateFeedIcon()
  172. return subscription, nil
  173. }
  174. // RefreshFeed refreshes a feed.
  175. func RefreshFeed(store *storage.Storage, userID, feedID int64, forceRefresh bool) *locale.LocalizedErrorWrapper {
  176. slog.Debug("Begin feed refresh process",
  177. slog.Int64("user_id", userID),
  178. slog.Int64("feed_id", feedID),
  179. slog.Bool("force_refresh", forceRefresh),
  180. )
  181. originalFeed, storeErr := store.FeedByID(userID, feedID)
  182. if storeErr != nil {
  183. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  184. }
  185. if originalFeed == nil {
  186. return locale.NewLocalizedErrorWrapper(ErrFeedNotFound, "error.feed_not_found")
  187. }
  188. weeklyEntryCount := 0
  189. if config.Opts.PollingScheduler() == model.SchedulerEntryFrequency {
  190. var weeklyCountErr error
  191. weeklyEntryCount, weeklyCountErr = store.WeeklyFeedEntryCount(userID, feedID)
  192. if weeklyCountErr != nil {
  193. return locale.NewLocalizedErrorWrapper(weeklyCountErr, "error.database_error", weeklyCountErr)
  194. }
  195. }
  196. originalFeed.CheckedNow()
  197. originalFeed.ScheduleNextCheck(weeklyEntryCount, time.Duration(0))
  198. requestBuilder := fetcher.NewRequestBuilder().
  199. WithUsernameAndPassword(originalFeed.Username, originalFeed.Password).
  200. WithUserAgent(originalFeed.UserAgent, config.Opts.HTTPClientUserAgent()).
  201. WithCookie(originalFeed.Cookie, originalFeed.FeedURL).
  202. WithTimeout(config.Opts.HTTPClientTimeout()).
  203. WithProxyRotator(proxyrotator.ProxyRotatorInstance).
  204. WithCustomFeedProxyURL(originalFeed.ProxyURL).
  205. WithCustomApplicationProxyURL(config.Opts.HTTPClientProxyURL()).
  206. UseCustomApplicationProxyURL(originalFeed.FetchViaProxy).
  207. IgnoreTLSErrors(originalFeed.AllowSelfSignedCertificates).
  208. DisableHTTP2(originalFeed.DisableHTTP2)
  209. ignoreHTTPCache := originalFeed.IgnoreHTTPCache || forceRefresh
  210. if !ignoreHTTPCache {
  211. requestBuilder = requestBuilder.
  212. WithETag(originalFeed.EtagHeader).
  213. 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", urllib.RedactedURL(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", urllib.RedactedURL(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", urllib.RedactedURL(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", urllib.RedactedURL(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.Language = updatedFeed.Language
  303. originalFeed.IconURL = updatedFeed.IconURL
  304. iconChecker := icon.NewIconChecker(store, originalFeed)
  305. if forceRefresh {
  306. iconChecker.UpdateOrCreateFeedIcon()
  307. } else {
  308. iconChecker.CreateFeedIconIfMissing()
  309. }
  310. } else {
  311. slog.Debug("Feed not modified",
  312. slog.Int64("user_id", userID),
  313. slog.Int64("feed_id", feedID),
  314. )
  315. // Last-Modified may be updated even if ETag is not. In this case, per
  316. // RFC9111 sections 3.2 and 4.3.4, the stored response must be updated.
  317. if responseHandler.LastModified() != "" {
  318. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  319. }
  320. }
  321. originalFeed.ResetErrorCounter()
  322. if storeErr := store.UpdateFeed(originalFeed); storeErr != nil {
  323. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  324. return getTranslatedLocalizedError(store, userID, originalFeed, localizedError)
  325. }
  326. return nil
  327. }