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