handler.go 17 KB

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