handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. "errors"
  6. "log/slog"
  7. "time"
  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. // CreateFeed fetch, parse and store a new feed.
  24. func CreateFeed(store *storage.Storage, userID int64, feedCreationRequest *model.FeedCreationRequest) (*model.Feed, *locale.LocalizedErrorWrapper) {
  25. slog.Debug("Begin feed creation process",
  26. slog.Int64("user_id", userID),
  27. slog.String("feed_url", feedCreationRequest.FeedURL),
  28. )
  29. user, storeErr := store.UserByID(userID)
  30. if storeErr != nil {
  31. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  32. }
  33. if !store.CategoryIDExists(userID, feedCreationRequest.CategoryID) {
  34. return nil, locale.NewLocalizedErrorWrapper(ErrCategoryNotFound, "error.category_not_found")
  35. }
  36. requestBuilder := fetcher.NewRequestBuilder()
  37. requestBuilder.WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password)
  38. requestBuilder.WithUserAgent(feedCreationRequest.UserAgent)
  39. requestBuilder.WithCookie(feedCreationRequest.Cookie)
  40. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  41. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  42. requestBuilder.UseProxy(feedCreationRequest.FetchViaProxy)
  43. requestBuilder.IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates)
  44. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(feedCreationRequest.FeedURL))
  45. defer responseHandler.Close()
  46. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  47. slog.Warn("Unable to fetch feed", slog.String("feed_url", feedCreationRequest.FeedURL), slog.Any("error", localizedError.Error()))
  48. return nil, localizedError
  49. }
  50. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  51. if localizedError != nil {
  52. slog.Warn("Unable to fetch feed", slog.String("feed_url", feedCreationRequest.FeedURL), slog.Any("error", localizedError.Error()))
  53. return nil, localizedError
  54. }
  55. if store.FeedURLExists(userID, responseHandler.EffectiveURL()) {
  56. return nil, locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  57. }
  58. subscription, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), string(responseBody))
  59. if parseErr != nil {
  60. return nil, locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed", parseErr)
  61. }
  62. subscription.UserID = userID
  63. subscription.UserAgent = feedCreationRequest.UserAgent
  64. subscription.Cookie = feedCreationRequest.Cookie
  65. subscription.Username = feedCreationRequest.Username
  66. subscription.Password = feedCreationRequest.Password
  67. subscription.Crawler = feedCreationRequest.Crawler
  68. subscription.Disabled = feedCreationRequest.Disabled
  69. subscription.IgnoreHTTPCache = feedCreationRequest.IgnoreHTTPCache
  70. subscription.AllowSelfSignedCertificates = feedCreationRequest.AllowSelfSignedCertificates
  71. subscription.FetchViaProxy = feedCreationRequest.FetchViaProxy
  72. subscription.ScraperRules = feedCreationRequest.ScraperRules
  73. subscription.RewriteRules = feedCreationRequest.RewriteRules
  74. subscription.BlocklistRules = feedCreationRequest.BlocklistRules
  75. subscription.KeeplistRules = feedCreationRequest.KeeplistRules
  76. subscription.UrlRewriteRules = feedCreationRequest.UrlRewriteRules
  77. subscription.EtagHeader = responseHandler.ETag()
  78. subscription.LastModifiedHeader = responseHandler.LastModified()
  79. subscription.FeedURL = responseHandler.EffectiveURL()
  80. subscription.WithCategoryID(feedCreationRequest.CategoryID)
  81. subscription.CheckedNow()
  82. processor.ProcessFeedEntries(store, subscription, user, true)
  83. if storeErr := store.CreateFeed(subscription); storeErr != nil {
  84. return nil, locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  85. }
  86. slog.Debug("Created feed",
  87. slog.Int64("user_id", userID),
  88. slog.Int64("feed_id", subscription.ID),
  89. slog.String("feed_url", subscription.FeedURL),
  90. )
  91. checkFeedIcon(
  92. store,
  93. requestBuilder,
  94. subscription.ID,
  95. subscription.SiteURL,
  96. subscription.IconURL,
  97. )
  98. return subscription, nil
  99. }
  100. // RefreshFeed refreshes a feed.
  101. func RefreshFeed(store *storage.Storage, userID, feedID int64, forceRefresh bool) *locale.LocalizedErrorWrapper {
  102. slog.Debug("Begin feed refresh process",
  103. slog.Int64("user_id", userID),
  104. slog.Int64("feed_id", feedID),
  105. slog.Bool("force_refresh", forceRefresh),
  106. )
  107. user, storeErr := store.UserByID(userID)
  108. if storeErr != nil {
  109. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  110. }
  111. originalFeed, storeErr := store.FeedByID(userID, feedID)
  112. if storeErr != nil {
  113. return locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  114. }
  115. if originalFeed == nil {
  116. return locale.NewLocalizedErrorWrapper(ErrFeedNotFound, "error.feed_not_found")
  117. }
  118. weeklyEntryCount := 0
  119. if config.Opts.PollingScheduler() == model.SchedulerEntryFrequency {
  120. var weeklyCountErr error
  121. weeklyEntryCount, weeklyCountErr = store.WeeklyFeedEntryCount(userID, feedID)
  122. if weeklyCountErr != nil {
  123. return locale.NewLocalizedErrorWrapper(weeklyCountErr, "error.database_error", weeklyCountErr)
  124. }
  125. }
  126. originalFeed.CheckedNow()
  127. originalFeed.ScheduleNextCheck(weeklyEntryCount)
  128. requestBuilder := fetcher.NewRequestBuilder()
  129. requestBuilder.WithUsernameAndPassword(originalFeed.Username, originalFeed.Password)
  130. requestBuilder.WithUserAgent(originalFeed.UserAgent)
  131. requestBuilder.WithCookie(originalFeed.Cookie)
  132. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  133. requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
  134. requestBuilder.UseProxy(originalFeed.FetchViaProxy)
  135. requestBuilder.IgnoreTLSErrors(originalFeed.AllowSelfSignedCertificates)
  136. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(originalFeed.FeedURL))
  137. defer responseHandler.Close()
  138. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  139. slog.Warn("Unable to fetch feed", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  140. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  141. store.UpdateFeedError(originalFeed)
  142. return localizedError
  143. }
  144. if store.AnotherFeedURLExists(userID, originalFeed.ID, responseHandler.EffectiveURL()) {
  145. localizedError := locale.NewLocalizedErrorWrapper(ErrDuplicatedFeed, "error.duplicated_feed")
  146. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  147. store.UpdateFeedError(originalFeed)
  148. return localizedError
  149. }
  150. if originalFeed.IgnoreHTTPCache || responseHandler.IsModified(originalFeed.EtagHeader, originalFeed.LastModifiedHeader) {
  151. slog.Debug("Feed modified",
  152. slog.Int64("user_id", userID),
  153. slog.Int64("feed_id", feedID),
  154. )
  155. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  156. if localizedError != nil {
  157. slog.Warn("Unable to fetch feed", slog.String("feed_url", originalFeed.FeedURL), slog.Any("error", localizedError.Error()))
  158. return localizedError
  159. }
  160. updatedFeed, parseErr := parser.ParseFeed(responseHandler.EffectiveURL(), string(responseBody))
  161. if parseErr != nil {
  162. localizedError := locale.NewLocalizedErrorWrapper(parseErr, "error.unable_to_parse_feed")
  163. if errors.Is(parseErr, parser.ErrFeedFormatNotDetected) {
  164. localizedError = locale.NewLocalizedErrorWrapper(parseErr, "error.feed_format_not_detected", parseErr)
  165. }
  166. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  167. store.UpdateFeedError(originalFeed)
  168. return localizedError
  169. }
  170. // If the feed has a TTL defined, we use it to make sure we don't check it too often.
  171. if updatedFeed.TTL > 0 {
  172. minNextCheckAt := time.Now().Add(time.Minute * time.Duration(updatedFeed.TTL))
  173. slog.Debug("Feed TTL",
  174. slog.Int64("user_id", userID),
  175. slog.Int64("feed_id", feedID),
  176. slog.Int("ttl", updatedFeed.TTL),
  177. slog.Time("next_check_at", originalFeed.NextCheckAt),
  178. )
  179. if originalFeed.NextCheckAt.IsZero() || originalFeed.NextCheckAt.Before(minNextCheckAt) {
  180. slog.Debug("Updating next check date based on TTL",
  181. slog.Int64("user_id", userID),
  182. slog.Int64("feed_id", feedID),
  183. slog.Int("ttl", updatedFeed.TTL),
  184. slog.Time("new_next_check_at", minNextCheckAt),
  185. slog.Time("old_next_check_at", originalFeed.NextCheckAt),
  186. )
  187. originalFeed.NextCheckAt = minNextCheckAt
  188. }
  189. }
  190. originalFeed.Entries = updatedFeed.Entries
  191. processor.ProcessFeedEntries(store, originalFeed, user, forceRefresh)
  192. // We don't update existing entries when the crawler is enabled (we crawl only inexisting entries). Unless it is forced to refresh
  193. updateExistingEntries := forceRefresh || !originalFeed.Crawler
  194. newEntries, storeErr := store.RefreshFeedEntries(originalFeed.UserID, originalFeed.ID, originalFeed.Entries, updateExistingEntries)
  195. if storeErr != nil {
  196. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  197. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  198. store.UpdateFeedError(originalFeed)
  199. return localizedError
  200. }
  201. userIntegrations, intErr := store.Integration(userID)
  202. if intErr != nil {
  203. slog.Error("Fetching integrations failed; the refresh process will go on, but no integrations will run this time",
  204. slog.Int64("user_id", userID),
  205. slog.Int64("feed_id", feedID),
  206. slog.Any("error", intErr),
  207. )
  208. } else if userIntegrations != nil && len(newEntries) > 0 {
  209. go integration.PushEntries(originalFeed, newEntries, userIntegrations)
  210. }
  211. // We update caching headers only if the feed has been modified,
  212. // because some websites don't return the same headers when replying with a 304.
  213. originalFeed.EtagHeader = responseHandler.ETag()
  214. originalFeed.LastModifiedHeader = responseHandler.LastModified()
  215. checkFeedIcon(
  216. store,
  217. requestBuilder,
  218. originalFeed.ID,
  219. originalFeed.SiteURL,
  220. updatedFeed.IconURL,
  221. )
  222. } else {
  223. slog.Debug("Feed not modified",
  224. slog.Int64("user_id", userID),
  225. slog.Int64("feed_id", feedID),
  226. )
  227. }
  228. originalFeed.ResetErrorCounter()
  229. if storeErr := store.UpdateFeed(originalFeed); storeErr != nil {
  230. localizedError := locale.NewLocalizedErrorWrapper(storeErr, "error.database_error", storeErr)
  231. originalFeed.WithTranslatedErrorMessage(localizedError.Translate(user.Language))
  232. store.UpdateFeedError(originalFeed)
  233. return localizedError
  234. }
  235. return nil
  236. }
  237. func checkFeedIcon(store *storage.Storage, requestBuilder *fetcher.RequestBuilder, feedID int64, websiteURL, feedIconURL string) {
  238. if !store.HasIcon(feedID) {
  239. iconFinder := icon.NewIconFinder(requestBuilder, websiteURL, feedIconURL)
  240. if icon, err := iconFinder.FindIcon(); err != nil {
  241. slog.Debug("Unable to find feed icon",
  242. slog.Int64("feed_id", feedID),
  243. slog.String("website_url", websiteURL),
  244. slog.String("feed_icon_url", feedIconURL),
  245. slog.Any("error", err),
  246. )
  247. } else if icon == nil {
  248. slog.Debug("No icon found",
  249. slog.Int64("feed_id", feedID),
  250. slog.String("website_url", websiteURL),
  251. slog.String("feed_icon_url", feedIconURL),
  252. )
  253. } else {
  254. if err := store.CreateFeedIcon(feedID, icon); err != nil {
  255. slog.Error("Unable to store feed icon",
  256. slog.Int64("feed_id", feedID),
  257. slog.String("website_url", websiteURL),
  258. slog.String("feed_icon_url", feedIconURL),
  259. slog.Any("error", err),
  260. )
  261. }
  262. }
  263. }
  264. }