handler.go 16 KB

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