handler.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. checkFeedIcon(
  82. store,
  83. requestBuilder,
  84. subscription.ID,
  85. subscription.SiteURL,
  86. subscription.IconURL,
  87. )
  88. return subscription, nil
  89. }
  90. // CreateFeed fetch, parse and store a new feed.
  91. func CreateFeed(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequest) (*model.Feed, *locale.LocalizedErrorWrapper) {
  92. slog.Debug("Begin feed creation process",
  93. slog.Int64("user_id", userID),
  94. slog.String("feed_url", feedCreationRequest.FeedURL),
  95. )
  96. user, storeErr := store.UserByID(userID)
  97. if storeErr != nil {
  98. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  99. }
  100. if !store.CategoryIDExists(userID, feedCreationRequest.CategoryID) {
  101. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  102. }
  103. requestBuilder := fetcher.NewRequestBuilder()
  104. requestBuilder.WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password)
  105. requestBuilder.WithUserAgent(feedCreationRequest.UserAgent, config.Opts.HTTPClientUserAgent())
  106. requestBuilder.WithCookie(feedCreationRequest.Cookie)
  107. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  108. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  109. requestBuilder.UseProxy(feedCreationRequest.FetchViaProxy)
  110. requestBuilder.IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates)
  111. requestBuilder.DisableHTTP2(feedCreationRequest.DisableHTTP2)
  112. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(feedCreationRequest.FeedURL))
  113. defer responseHandler.Close()
  114. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  115. slog.Warn("Unable to fetch feed", slog.String("feed_url", feedCreationRequest.FeedURL), slog.Any("error", localizedError.Error()))
  116. return nil, localizedError
  117. }
  118. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  119. if localizedError != nil {
  120. slog.Warn("Unable to fetch feed", slog.String("feed_url", feedCreationRequest.FeedURL), slog.Any("error", localizedError.Error()))
  121. return nil, localizedError
  122. }
  123. if store.FeedURLExists(userID, responseHandler.EffectiveURL()) {
  124. return nil, locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  125. }
  126. subscription, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), bytes.NewReader(responseBody))
  127. if parseErr != nil {
  128. return nil, locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  129. }
  130. subscription.UserID = userID
  131. subscription.UserAgent = feedCreationRequest.UserAgent
  132. subscription.Cookie = feedCreationRequest.Cookie
  133. subscription.Username = feedCreationRequest.Username
  134. subscription.Password = feedCreationRequest.Password
  135. subscription.Crawler = feedCreationRequest.Crawler
  136. subscription.Disabled = feedCreationRequest.Disabled
  137. subscription.IgnoreHTTPCache = feedCreationRequest.IgnoreHTTPCache
  138. subscription.AllowSelfSignedCertificates = feedCreationRequest.AllowSelfSignedCertificates
  139. subscription.DisableHTTP2 = feedCreationRequest.DisableHTTP2
  140. subscription.FetchViaProxy = feedCreationRequest.FetchViaProxy
  141. subscription.ScraperRules = feedCreationRequest.ScraperRules
  142. subscription.RewriteRules = feedCreationRequest.RewriteRules
  143. subscription.BlocklistRules = feedCreationRequest.BlocklistRules
  144. subscription.KeeplistRules = feedCreationRequest.KeeplistRules
  145. subscription.UrlRewriteRules = feedCreationRequest.UrlRewriteRules
  146. subscription.EtagHeader = responseHandler.ETag()
  147. subscription.LastModifiedHeader = responseHandler.LastModified()
  148. subscription.FeedURL = responseHandler.EffectiveURL()
  149. subscription.WithCategoryID(feedCreationRequest.CategoryID)
  150. subscription.CheckedNow()
  151. processor.ProcessFeedEntries(store, subscription, user, true)
  152. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  153. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  154. }
  155. slog.Debug("Created feed",
  156. slog.Int64("user_id", userID),
  157. slog.Int64("feed_id", subscription.ID),
  158. slog.String("feed_url", subscription.FeedURL),
  159. )
  160. checkFeedIcon(
  161. store,
  162. requestBuilder,
  163. subscription.ID,
  164. subscription.SiteURL,
  165. subscription.IconURL,
  166. )
  167. return subscription, nil
  168. }
  169. // RefreshFeed refreshes a feed.
  170. func RefreshFeed(store *storage.Storage, userID, feedID int64, forceRefresh bool) *locale.LocalizedErrorWrapper {
  171. slog.Debug("Begin feed refresh process",
  172. slog.Int64("user_id", userID),
  173. slog.Int64("feed_id", feedID),
  174. slog.Bool("force_refresh", forceRefresh),
  175. )
  176. user, storeErr := store.UserByID(userID)
  177. if storeErr != nil {
  178. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  179. }
  180. originalFeed, storeErr := store.FeedByID(userID, feedID)
  181. if storeErr != nil {
  182. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  183. }
  184. if originalFeed == nil {
  185. return locale.NewLocalizedErrorWrapper(ErrFeedNotFound, "error.feed_not_found")
  186. }
  187. weeklyEntryCount := 0
  188. newTTL := 0
  189. if config.Opts.PollingScheduler() == model.SchedulerEntryFrequency {
  190. var weeklyCountErr error
  191. weeklyEntryCount, weeklyCountErr = store.WeeklyFeedEntryCount(userID, feedID)
  192. if weeklyCountErr != nil {
  193. return locale.NewLocalizedErrorWrapper(weeklyCountErr, "error.database_error", weeklyCountErr)
  194. }
  195. }
  196. originalFeed.CheckedNow()
  197. originalFeed.ScheduleNextCheck(weeklyEntryCount, newTTL)
  198. requestBuilder := fetcher.NewRequestBuilder()
  199. requestBuilder.WithUsernameAndPassword(originalFeed.Username, originalFeed.Password)
  200. requestBuilder.WithUserAgent(originalFeed.UserAgent, config.Opts.HTTPClientUserAgent())
  201. requestBuilder.WithCookie(originalFeed.Cookie)
  202. requestBuilder.WithETag(originalFeed.EtagHeader)
  203. requestBuilder.WithLastModified(originalFeed.LastModifiedHeader)
  204. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  205. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  206. requestBuilder.UseProxy(originalFeed.FetchViaProxy)
  207. requestBuilder.IgnoreTLSErrors(originalFeed.AllowSelfSignedCertificates)
  208. requestBuilder.DisableHTTP2(originalFeed.DisableHTTP2)
  209. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(originalFeed.FeedURL))
  210. defer responseHandler.Close()
  211. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  212. slog.Warn("Unable to fetch feed", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  213. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  214. store.UpdateFeedError(originalFeed)
  215. return localizedError
  216. }
  217. if store.AnotherFeedURLExists(userID, originalFeed.ID, responseHandler.EffectiveURL()) {
  218. localizedError := locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  219. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  220. store.UpdateFeedError(originalFeed)
  221. return localizedError
  222. }
  223. if originalFeed.IgnoreHTTPCache || responseHandler.IsModified(originalFeed.EtagHeader, originalFeed.LastModifiedHeader) {
  224. slog.Debug("Feed modified",
  225. slog.Int64("user_id", userID),
  226. slog.Int64("feed_id", feedID),
  227. )
  228. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  229. if localizedError != nil {
  230. slog.Warn("Unable to fetch feed", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  231. return localizedError
  232. }
  233. updatedFeed, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), bytes.NewReader(responseBody))
  234. if parseErr != nil {
  235. localizedError := locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  236. if errors.Is(parseErr, parser.ErrFeedFormatNotDetected) {
  237. localizedError = locale.NewLocalizedErrorWrapper(parseErr, "error.feed_format_not_detected", parseErr)
  238. }
  239. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  240. store.UpdateFeedError(originalFeed)
  241. return localizedError
  242. }
  243. // If the feed has a TTL defined, we use it to make sure we don't check it too often.
  244. newTTL = updatedFeed.TTL
  245. // Set the next check at with updated arguments.
  246. originalFeed.ScheduleNextCheck(weeklyEntryCount, newTTL)
  247. slog.Debug("Updated next check date",
  248. slog.Int64("user_id", userID),
  249. slog.Int64("feed_id", feedID),
  250. slog.Int("ttl", newTTL),
  251. slog.Time("new_next_check_at", originalFeed.NextCheckAt),
  252. )
  253. originalFeed.Entries = updatedFeed.Entries
  254. processor.ProcessFeedEntries(store, originalFeed, user, forceRefresh)
  255. // We don't update existing entries when the crawler is enabled (we crawl only inexisting entries). Unless it is forced to refresh
  256. updateExistingEntries := forceRefresh || !originalFeed.Crawler
  257. newEntries, storeErr := store.RefreshFeedEntries(originalFeed.UserID, originalFeed.ID, originalFeed.Entries, updateExistingEntries)
  258. if storeErr != nil {
  259. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  260. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  261. store.UpdateFeedError(originalFeed)
  262. return localizedError
  263. }
  264. userIntegrations, intErr := store.Integration(userID)
  265. if intErr != nil {
  266. slog.Error("Fetching integrations failed; the refresh process will go on, but no integrations will run this time",
  267. slog.Int64("user_id", userID),
  268. slog.Int64("feed_id", feedID),
  269. slog.Any("error", intErr),
  270. )
  271. } else if userIntegrations != nil && len(newEntries) > 0 {
  272. go integration.PushEntries(originalFeed, newEntries, userIntegrations)
  273. }
  274. // We update caching headers only if the feed has been modified,
  275. // because some websites don't return the same headers when replying with a 304.
  276. originalFeed.EtagHeader = responseHandler.ETag()
  277. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  278. checkFeedIcon(
  279. store,
  280. requestBuilder,
  281. originalFeed.ID,
  282. originalFeed.SiteURL,
  283. updatedFeed.IconURL,
  284. )
  285. } else {
  286. slog.Debug("Feed not modified",
  287. slog.Int64("user_id", userID),
  288. slog.Int64("feed_id", feedID),
  289. )
  290. }
  291. originalFeed.ResetErrorCounter()
  292. if storeErr := store.UpdateFeed(originalFeed); storeErr != nil {
  293. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  294. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  295. store.UpdateFeedError(originalFeed)
  296. return localizedError
  297. }
  298. return nil
  299. }
  300. func checkFeedIcon(store *storage.Storage, requestBuilder *fetcher.RequestBuilder, feedID int64, websiteURL, feedIconURL string) {
  301. if !store.HasIcon(feedID) {
  302. iconFinder := icon.NewIconFinder(requestBuilder, websiteURL, feedIconURL)
  303. if icon, err := iconFinder.FindIcon(); err != nil {
  304. slog.Debug("Unable to find feed icon",
  305. slog.Int64("feed_id", feedID),
  306. slog.String("website_url", websiteURL),
  307. slog.String("feed_icon_url", feedIconURL),
  308. slog.Any("error", err),
  309. )
  310. } else if icon == nil {
  311. slog.Debug("No icon found",
  312. slog.Int64("feed_id", feedID),
  313. slog.String("website_url", websiteURL),
  314. slog.String("feed_icon_url", feedIconURL),
  315. )
  316. } else {
  317. if err := store.CreateFeedIcon(feedID, icon); err != nil {
  318. slog.Error("Unable to store feed icon",
  319. slog.Int64("feed_id", feedID),
  320. slog.String("website_url", websiteURL),
  321. slog.String("feed_icon_url", feedIconURL),
  322. slog.Any("error", err),
  323. )
  324. }
  325. }
  326. }
  327. }