handler.go 17 KB

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