handler.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package feed // import "miniflux.app/reader/feed"
  5. import (
  6. "fmt"
  7. "time"
  8. "miniflux.app/config"
  9. "miniflux.app/errors"
  10. "miniflux.app/http/client"
  11. "miniflux.app/locale"
  12. "miniflux.app/logger"
  13. "miniflux.app/model"
  14. "miniflux.app/reader/browser"
  15. "miniflux.app/reader/icon"
  16. "miniflux.app/reader/parser"
  17. "miniflux.app/reader/processor"
  18. "miniflux.app/storage"
  19. "miniflux.app/timer"
  20. )
  21. var (
  22. errDuplicate = "This feed already exists (%s)"
  23. errNotFound = "Feed %d not found"
  24. errCategoryNotFound = "Category not found for this user"
  25. )
  26. // Handler contains all the logic to create and refresh feeds.
  27. type Handler struct {
  28. store *storage.Storage
  29. }
  30. // CreateFeed fetch, parse and store a new feed.
  31. func (h *Handler) CreateFeed(userID, categoryID int64, url string, crawler bool, userAgent, username, password, scraperRules, rewriteRules string) (*model.Feed, error) {
  32. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[Handler:CreateFeed] feedUrl=%s", url))
  33. if !h.store.CategoryExists(userID, categoryID) {
  34. return nil, errors.NewLocalizedError(errCategoryNotFound)
  35. }
  36. request := client.New(url)
  37. request.WithCredentials(username, password)
  38. request.WithUserAgent(userAgent)
  39. response, requestErr := browser.Exec(request)
  40. if requestErr != nil {
  41. return nil, requestErr
  42. }
  43. if h.store.FeedURLExists(userID, response.EffectiveURL) {
  44. return nil, errors.NewLocalizedError(errDuplicate, response.EffectiveURL)
  45. }
  46. subscription, parseErr := parser.ParseFeed(response.BodyAsString())
  47. if parseErr != nil {
  48. return nil, parseErr
  49. }
  50. subscription.UserID = userID
  51. subscription.WithCategoryID(categoryID)
  52. subscription.WithBrowsingParameters(crawler, userAgent, username, password, scraperRules, rewriteRules)
  53. subscription.WithClientResponse(response)
  54. subscription.CheckedNow()
  55. processor.ProcessFeedEntries(h.store, subscription)
  56. if storeErr := h.store.CreateFeed(subscription); storeErr != nil {
  57. return nil, storeErr
  58. }
  59. logger.Debug("[Handler:CreateFeed] Feed saved with ID: %d", subscription.ID)
  60. checkFeedIcon(h.store, subscription.ID, subscription.SiteURL)
  61. return subscription, nil
  62. }
  63. // RefreshFeed fetch and update a feed if necessary.
  64. func (h *Handler) RefreshFeed(userID, feedID int64) error {
  65. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[Handler:RefreshFeed] feedID=%d", feedID))
  66. userLanguage := h.store.UserLanguage(userID)
  67. printer := locale.NewPrinter(userLanguage)
  68. originalFeed, storeErr := h.store.FeedByID(userID, feedID)
  69. if storeErr != nil {
  70. return storeErr
  71. }
  72. if originalFeed == nil {
  73. return errors.NewLocalizedError(errNotFound, feedID)
  74. }
  75. weeklyEntryCount := 0
  76. if config.Opts.PollingScheduler() == model.SchedulerEntryFrequency {
  77. var weeklyCountErr error
  78. weeklyEntryCount, weeklyCountErr = h.store.WeeklyFeedEntryCount(userID, feedID)
  79. if weeklyCountErr != nil {
  80. return weeklyCountErr
  81. }
  82. }
  83. originalFeed.CheckedNow()
  84. originalFeed.ScheduleNextCheck(weeklyEntryCount)
  85. request := client.New(originalFeed.FeedURL)
  86. request.WithCredentials(originalFeed.Username, originalFeed.Password)
  87. request.WithUserAgent(originalFeed.UserAgent)
  88. if !originalFeed.IgnoreHTTPCache {
  89. request.WithCacheHeaders(originalFeed.EtagHeader, originalFeed.LastModifiedHeader)
  90. }
  91. response, requestErr := browser.Exec(request)
  92. if requestErr != nil {
  93. originalFeed.WithError(requestErr.Localize(printer))
  94. h.store.UpdateFeedError(originalFeed)
  95. return requestErr
  96. }
  97. if originalFeed.IgnoreHTTPCache || response.IsModified(originalFeed.EtagHeader, originalFeed.LastModifiedHeader) {
  98. logger.Debug("[Handler:RefreshFeed] Feed #%d has been modified", feedID)
  99. updatedFeed, parseErr := parser.ParseFeed(response.BodyAsString())
  100. if parseErr != nil {
  101. originalFeed.WithError(parseErr.Localize(printer))
  102. h.store.UpdateFeedError(originalFeed)
  103. return parseErr
  104. }
  105. originalFeed.Entries = updatedFeed.Entries
  106. processor.ProcessFeedEntries(h.store, originalFeed)
  107. // We don't update existing entries when the crawler is enabled (we crawl only inexisting entries).
  108. if storeErr := h.store.UpdateEntries(originalFeed.UserID, originalFeed.ID, originalFeed.Entries, !originalFeed.Crawler); storeErr != nil {
  109. originalFeed.WithError(storeErr.Error())
  110. h.store.UpdateFeedError(originalFeed)
  111. return storeErr
  112. }
  113. // We update caching headers only if the feed has been modified,
  114. // because some websites don't return the same headers when replying with a 304.
  115. originalFeed.WithClientResponse(response)
  116. checkFeedIcon(h.store, originalFeed.ID, originalFeed.SiteURL)
  117. } else {
  118. logger.Debug("[Handler:RefreshFeed] Feed #%d not modified", feedID)
  119. }
  120. originalFeed.ResetErrorCounter()
  121. if storeErr := h.store.UpdateFeed(originalFeed); storeErr != nil {
  122. originalFeed.WithError(storeErr.Error())
  123. h.store.UpdateFeedError(originalFeed)
  124. return storeErr
  125. }
  126. return nil
  127. }
  128. // NewFeedHandler returns a feed handler.
  129. func NewFeedHandler(store *storage.Storage) *Handler {
  130. return &Handler{store}
  131. }
  132. func checkFeedIcon(store *storage.Storage, feedID int64, websiteURL string) {
  133. if !store.HasIcon(feedID) {
  134. icon, err := icon.FindIcon(websiteURL)
  135. if err != nil {
  136. logger.Debug("CheckFeedIcon: %v (feedID=%d websiteURL=%s)", err, feedID, websiteURL)
  137. } else if icon == nil {
  138. logger.Debug("CheckFeedIcon: No icon found (feedID=%d websiteURL=%s)", feedID, websiteURL)
  139. } else {
  140. if err := store.CreateFeedIcon(feedID, icon); err != nil {
  141. logger.Debug("CheckFeedIcon: %v (feedID=%d websiteURL=%s)", err, feedID, websiteURL)
  142. }
  143. }
  144. }
  145. }