4
0

handler.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. newTTL := 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, newTTL)
  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 localizedError := responseHandler.LocalizedError(); localizedError != nil {
  204. slog.Warn("Unable to fetch feed", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  205. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  206. store.UpdateFeedError(originalFeed)
  207. return localizedError
  208. }
  209. if store.AnotherFeedURLExists(userID, originalFeed.ID, responseHandler.EffectiveURL()) {
  210. localizedError := locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  211. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  212. store.UpdateFeedError(originalFeed)
  213. return localizedError
  214. }
  215. if ignoreHTTPCache || responseHandler.IsModified(originalFeed.EtagHeader, originalFeed.LastModifiedHeader) {
  216. slog.Debug("Feed modified",
  217. slog.Int64("user_id", userID),
  218. slog.Int64("feed_id", feedID),
  219. slog.String("etag_header", originalFeed.EtagHeader),
  220. slog.String("last_modified_header", originalFeed.LastModifiedHeader),
  221. )
  222. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  223. if localizedError != nil {
  224. slog.Warn("Unable to fetch feed", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  225. return localizedError
  226. }
  227. updatedFeed, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), bytes.NewReader(responseBody))
  228. if parseErr != nil {
  229. localizedError := locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  230. if errors.Is(parseErr, parser.ErrFeedFormatNotDetected) {
  231. localizedError = locale.NewLocalizedErrorWrapper(parseErr, "error.feed_format_not_detected", parseErr)
  232. }
  233. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  234. store.UpdateFeedError(originalFeed)
  235. return localizedError
  236. }
  237. // If the feed has a TTL defined, we use it to make sure we don't check it too often.
  238. newTTL = updatedFeed.TTL
  239. // Set the next check at with updated arguments.
  240. originalFeed.ScheduleNextCheck(weeklyEntryCount, newTTL)
  241. slog.Debug("Updated next check date",
  242. slog.Int64("user_id", userID),
  243. slog.Int64("feed_id", feedID),
  244. slog.Int("ttl", newTTL),
  245. slog.Time("new_next_check_at", originalFeed.NextCheckAt),
  246. )
  247. originalFeed.Entries = updatedFeed.Entries
  248. processor.ProcessFeedEntries(store, originalFeed, user, forceRefresh)
  249. // We don't update existing entries when the crawler is enabled (we crawl only inexisting entries). Unless it is forced to refresh
  250. updateExistingEntries := forceRefresh || !originalFeed.Crawler
  251. newEntries, storeErr := store.RefreshFeedEntries(originalFeed.UserID, originalFeed.ID, originalFeed.Entries, updateExistingEntries)
  252. if storeErr != nil {
  253. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  254. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  255. store.UpdateFeedError(originalFeed)
  256. return localizedError
  257. }
  258. userIntegrations, intErr := store.Integration(userID)
  259. if intErr != nil {
  260. slog.Error("Fetching integrations failed; the refresh process will go on, but no integrations will run this time",
  261. slog.Int64("user_id", userID),
  262. slog.Int64("feed_id", feedID),
  263. slog.Any("error", intErr),
  264. )
  265. } else if userIntegrations != nil && len(newEntries) > 0 {
  266. go integration.PushEntries(originalFeed, newEntries, userIntegrations)
  267. }
  268. originalFeed.EtagHeader = responseHandler.ETag()
  269. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  270. iconChecker := icon.NewIconChecker(store, originalFeed)
  271. if forceRefresh {
  272. iconChecker.UpdateOrCreateFeedIcon()
  273. } else {
  274. iconChecker.CreateFeedIconIfMissing()
  275. }
  276. } else {
  277. slog.Debug("Feed not modified",
  278. slog.Int64("user_id", userID),
  279. slog.Int64("feed_id", feedID),
  280. )
  281. // Last-Modified may be updated even if ETag is not. In this case, per
  282. // RFC9111 sections 3.2 and 4.3.4, the stored response must be updated.
  283. if responseHandler.LastModified() != "" {
  284. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  285. }
  286. }
  287. originalFeed.ResetErrorCounter()
  288. if storeErr := store.UpdateFeed(originalFeed); storeErr != nil {
  289. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  290. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  291. store.UpdateFeedError(originalFeed)
  292. return localizedError
  293. }
  294. return nil
  295. }