handler.go 15 KB

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