handler.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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/reader/fetcher"
  13. "miniflux.app/v2/internal/reader/icon"
  14. "miniflux.app/v2/internal/reader/parser"
  15. "miniflux.app/v2/internal/reader/processor"
  16. "miniflux.app/v2/internal/storage"
  17. )
  18. var (
  19. ErrCategoryNotFound = errors.New("fetcher: category not found")
  20. ErrFeedNotFound = errors.New("fetcher: feed not found")
  21. ErrDuplicatedFeed = errors.New("fetcher: duplicated feed")
  22. )
  23. func CreateFeedFromSubscriptionDiscovery(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequestFromSubscriptionDiscovery) (*model.Feed, *locale.LocalizedErrorWrapper) {
  24. slog.Debug("Begin feed creation process from subscription discovery",
  25. slog.Int64("user_id", userID),
  26. slog.String("feed_url", feedCreationRequest.FeedURL),
  27. )
  28. user, storeErr := store.UserByID(userID)
  29. if storeErr != nil {
  30. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  31. }
  32. if !store.CategoryIDExists(userID, feedCreationRequest.CategoryID) {
  33. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  34. }
  35. if store.FeedURLExists(userID, feedCreationRequest.FeedURL) {
  36. return nil, locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  37. }
  38. subscription, parseErr := parser.ParseFeed(feedCreationRequest.FeedURL, feedCreationRequest.Content)
  39. if parseErr != nil {
  40. return nil, locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  41. }
  42. subscription.UserID = userID
  43. subscription.UserAgent = feedCreationRequest.UserAgent
  44. subscription.Cookie = feedCreationRequest.Cookie
  45. subscription.Username = feedCreationRequest.Username
  46. subscription.Password = feedCreationRequest.Password
  47. subscription.Crawler = feedCreationRequest.Crawler
  48. subscription.Disabled = feedCreationRequest.Disabled
  49. subscription.IgnoreHTTPCache = feedCreationRequest.IgnoreHTTPCache
  50. subscription.AllowSelfSignedCertificates = feedCreationRequest.AllowSelfSignedCertificates
  51. subscription.FetchViaProxy = feedCreationRequest.FetchViaProxy
  52. subscription.ScraperRules = feedCreationRequest.ScraperRules
  53. subscription.RewriteRules = feedCreationRequest.RewriteRules
  54. subscription.BlocklistRules = feedCreationRequest.BlocklistRules
  55. subscription.KeeplistRules = feedCreationRequest.KeeplistRules
  56. subscription.UrlRewriteRules = feedCreationRequest.UrlRewriteRules
  57. subscription.EtagHeader = feedCreationRequest.ETag
  58. subscription.LastModifiedHeader = feedCreationRequest.LastModified
  59. subscription.FeedURL = feedCreationRequest.FeedURL
  60. subscription.DisableHTTP2 = feedCreationRequest.DisableHTTP2
  61. subscription.WithCategoryID(feedCreationRequest.CategoryID)
  62. subscription.CheckedNow()
  63. processor.ProcessFeedEntries(store, subscription, user, true)
  64. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  65. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  66. }
  67. slog.Debug("Created feed",
  68. slog.Int64("user_id", userID),
  69. slog.Int64("feed_id", subscription.ID),
  70. slog.String("feed_url", subscription.FeedURL),
  71. )
  72. requestBuilder := fetcher.NewRequestBuilder()
  73. requestBuilder.WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password)
  74. requestBuilder.WithUserAgent(feedCreationRequest.UserAgent, config.Opts.HTTPClientUserAgent())
  75. requestBuilder.WithCookie(feedCreationRequest.Cookie)
  76. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  77. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  78. requestBuilder.UseProxy(feedCreationRequest.FetchViaProxy)
  79. requestBuilder.IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates)
  80. requestBuilder.DisableHTTP2(feedCreationRequest.DisableHTTP2)
  81. icon.NewIconChecker(store, subscription).UpdateOrCreateFeedIcon()
  82. return subscription, nil
  83. }
  84. // CreateFeed fetch, parse and store a new feed.
  85. func CreateFeed(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequest) (*model.Feed, *locale.LocalizedErrorWrapper) {
  86. slog.Debug("Begin feed creation process",
  87. slog.Int64("user_id", userID),
  88. slog.String("feed_url", feedCreationRequest.FeedURL),
  89. )
  90. user, storeErr := store.UserByID(userID)
  91. if storeErr != nil {
  92. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  93. }
  94. if !store.CategoryIDExists(userID, feedCreationRequest.CategoryID) {
  95. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  96. }
  97. requestBuilder := fetcher.NewRequestBuilder()
  98. requestBuilder.WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password)
  99. requestBuilder.WithUserAgent(feedCreationRequest.UserAgent, config.Opts.HTTPClientUserAgent())
  100. requestBuilder.WithCookie(feedCreationRequest.Cookie)
  101. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  102. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  103. requestBuilder.UseProxy(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.WithCategoryID(feedCreationRequest.CategoryID)
  145. subscription.CheckedNow()
  146. processor.ProcessFeedEntries(store, subscription, user, true)
  147. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  148. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  149. }
  150. slog.Debug("Created feed",
  151. slog.Int64("user_id", userID),
  152. slog.Int64("feed_id", subscription.ID),
  153. slog.String("feed_url", subscription.FeedURL),
  154. )
  155. icon.NewIconChecker(store, subscription).UpdateOrCreateFeedIcon()
  156. return subscription, nil
  157. }
  158. // RefreshFeed refreshes a feed.
  159. func RefreshFeed(store *storage.Storage, userID, feedID int64, forceRefresh bool) *locale.LocalizedErrorWrapper {
  160. slog.Debug("Begin feed refresh process",
  161. slog.Int64("user_id", userID),
  162. slog.Int64("feed_id", feedID),
  163. slog.Bool("force_refresh", forceRefresh),
  164. )
  165. user, storeErr := store.UserByID(userID)
  166. if storeErr != nil {
  167. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  168. }
  169. originalFeed, storeErr := store.FeedByID(userID, feedID)
  170. if storeErr != nil {
  171. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  172. }
  173. if originalFeed == nil {
  174. return locale.NewLocalizedErrorWrapper(ErrFeedNotFound, "error.feed_not_found")
  175. }
  176. weeklyEntryCount := 0
  177. refreshDelayInMinutes := 0
  178. if config.Opts.PollingScheduler() == model.SchedulerEntryFrequency {
  179. var weeklyCountErr error
  180. weeklyEntryCount, weeklyCountErr = store.WeeklyFeedEntryCount(userID, feedID)
  181. if weeklyCountErr != nil {
  182. return locale.NewLocalizedErrorWrapper(weeklyCountErr, "error.database_error", weeklyCountErr)
  183. }
  184. }
  185. originalFeed.CheckedNow()
  186. originalFeed.ScheduleNextCheck(weeklyEntryCount, refreshDelayInMinutes)
  187. requestBuilder := fetcher.NewRequestBuilder()
  188. requestBuilder.WithUsernameAndPassword(originalFeed.Username, originalFeed.Password)
  189. requestBuilder.WithUserAgent(originalFeed.UserAgent, config.Opts.HTTPClientUserAgent())
  190. requestBuilder.WithCookie(originalFeed.Cookie)
  191. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  192. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  193. requestBuilder.UseProxy(originalFeed.FetchViaProxy)
  194. requestBuilder.IgnoreTLSErrors(originalFeed.AllowSelfSignedCertificates)
  195. requestBuilder.DisableHTTP2(originalFeed.DisableHTTP2)
  196. ignoreHTTPCache := originalFeed.IgnoreHTTPCache || forceRefresh
  197. if !ignoreHTTPCache {
  198. requestBuilder.WithETag(originalFeed.EtagHeader)
  199. requestBuilder.WithLastModified(originalFeed.LastModifiedHeader)
  200. }
  201. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(originalFeed.FeedURL))
  202. defer responseHandler.Close()
  203. if responseHandler.IsRateLimited() {
  204. retryDelayInSeconds := responseHandler.ParseRetryDelay()
  205. refreshDelayInMinutes = retryDelayInSeconds / 60
  206. originalFeed.ScheduleNextCheck(weeklyEntryCount, refreshDelayInMinutes)
  207. slog.Warn("Feed is rate limited",
  208. slog.String("feed_url", originalFeed.FeedURL),
  209. slog.Int("retry_delay_in_seconds", retryDelayInSeconds),
  210. slog.Int("refresh_delay_in_minutes", refreshDelayInMinutes),
  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", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  216. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  217. store.UpdateFeedError(originalFeed)
  218. return localizedError
  219. }
  220. if store.AnotherFeedURLExists(userID, originalFeed.ID, responseHandler.EffectiveURL()) {
  221. localizedError := locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  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. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  245. store.UpdateFeedError(originalFeed)
  246. return localizedError
  247. }
  248. // If the feed has a TTL defined, we use it to make sure we don't check it too often.
  249. refreshDelayInMinutes = updatedFeed.TTL
  250. // Set the next check at with updated arguments.
  251. originalFeed.ScheduleNextCheck(weeklyEntryCount, refreshDelayInMinutes)
  252. slog.Debug("Updated next check date",
  253. slog.Int64("user_id", userID),
  254. slog.Int64("feed_id", feedID),
  255. slog.Int("refresh_delay_in_minutes", refreshDelayInMinutes),
  256. slog.Time("new_next_check_at", originalFeed.NextCheckAt),
  257. )
  258. originalFeed.Entries = updatedFeed.Entries
  259. processor.ProcessFeedEntries(store, originalFeed, user, forceRefresh)
  260. // We don't update existing entries when the crawler is enabled (we crawl only inexisting entries). Unless it is forced to refresh
  261. updateExistingEntries := forceRefresh || !originalFeed.Crawler
  262. newEntries, storeErr := store.RefreshFeedEntries(originalFeed.UserID, originalFeed.ID, originalFeed.Entries, updateExistingEntries)
  263. if storeErr != nil {
  264. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  265. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  266. store.UpdateFeedError(originalFeed)
  267. return localizedError
  268. }
  269. userIntegrations, intErr := store.Integration(userID)
  270. if intErr != nil {
  271. slog.Error("Fetching integrations failed; the refresh process will go on, but no integrations will run this time",
  272. slog.Int64("user_id", userID),
  273. slog.Int64("feed_id", feedID),
  274. slog.Any("error", intErr),
  275. )
  276. } else if userIntegrations != nil && len(newEntries) > 0 {
  277. go integration.PushEntries(originalFeed, newEntries, userIntegrations)
  278. }
  279. originalFeed.EtagHeader = responseHandler.ETag()
  280. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  281. originalFeed.IconURL = updatedFeed.IconURL
  282. iconChecker := icon.NewIconChecker(store, originalFeed)
  283. if forceRefresh {
  284. iconChecker.UpdateOrCreateFeedIcon()
  285. } else {
  286. iconChecker.CreateFeedIconIfMissing()
  287. }
  288. } else {
  289. slog.Debug("Feed not modified",
  290. slog.Int64("user_id", userID),
  291. slog.Int64("feed_id", feedID),
  292. )
  293. // Last-Modified may be updated even if ETag is not. In this case, per
  294. // RFC9111 sections 3.2 and 4.3.4, the stored response must be updated.
  295. if responseHandler.LastModified() != "" {
  296. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  297. }
  298. }
  299. originalFeed.ResetErrorCounter()
  300. if storeErr := store.UpdateFeed(originalFeed); storeErr != nil {
  301. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  302. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  303. store.UpdateFeedError(originalFeed)
  304. return localizedError
  305. }
  306. return nil
  307. }