finder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package subscription // import "miniflux.app/v2/internal/reader/subscription"
  4. import (
  5. "bytes"
  6. "io"
  7. "log/slog"
  8. "net/url"
  9. "strings"
  10. "miniflux.app/v2/internal/config"
  11. "miniflux.app/v2/internal/integration/rssbridge"
  12. "miniflux.app/v2/internal/locale"
  13. "miniflux.app/v2/internal/model"
  14. "miniflux.app/v2/internal/reader/encoding"
  15. "miniflux.app/v2/internal/reader/fetcher"
  16. "miniflux.app/v2/internal/reader/parser"
  17. "miniflux.app/v2/internal/urllib"
  18. "github.com/PuerkitoBio/goquery"
  19. )
  20. type subscriptionFinder struct {
  21. requestBuilder *fetcher.RequestBuilder
  22. feedDownloaded bool
  23. feedResponseInfo *model.FeedCreationRequestFromSubscriptionDiscovery
  24. }
  25. func NewSubscriptionFinder(requestBuilder *fetcher.RequestBuilder) *subscriptionFinder {
  26. return &subscriptionFinder{
  27. requestBuilder: requestBuilder,
  28. }
  29. }
  30. func (f *subscriptionFinder) IsFeedAlreadyDownloaded() bool {
  31. return f.feedDownloaded
  32. }
  33. func (f *subscriptionFinder) FeedResponseInfo() *model.FeedCreationRequestFromSubscriptionDiscovery {
  34. return f.feedResponseInfo
  35. }
  36. func (f *subscriptionFinder) FindSubscriptions(websiteURL, rssBridgeURL string, rssBridgeToken string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  37. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(websiteURL))
  38. defer responseHandler.Close()
  39. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  40. slog.Warn("Unable to find subscriptions", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  41. return nil, localizedError
  42. }
  43. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  44. if localizedError != nil {
  45. slog.Warn("Unable to find subscriptions", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  46. return nil, localizedError
  47. }
  48. f.feedResponseInfo = &model.FeedCreationRequestFromSubscriptionDiscovery{
  49. Content: bytes.NewReader(responseBody),
  50. ETag: responseHandler.ETag(),
  51. LastModified: responseHandler.LastModified(),
  52. }
  53. // Step 1) Check if the website URL is already a feed.
  54. if feedFormat, _ := parser.DetectFeedFormat(f.feedResponseInfo.Content); feedFormat != parser.FormatUnknown {
  55. f.feedDownloaded = true
  56. return Subscriptions{NewSubscription(responseHandler.EffectiveURL(), responseHandler.EffectiveURL(), feedFormat)}, nil
  57. }
  58. // Step 2) Check if the website URL is a YouTube channel.
  59. slog.Debug("Try to detect feeds for a YouTube page", slog.String("website_url", websiteURL))
  60. if subscriptions, localizedError := f.findSubscriptionsFromYouTube(websiteURL); localizedError != nil {
  61. return nil, localizedError
  62. } else if len(subscriptions) > 0 {
  63. slog.Debug("Subscriptions found from YouTube page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  64. return subscriptions, nil
  65. }
  66. // Step 3) Parse web page to find feeds from HTML meta tags.
  67. slog.Debug("Try to detect feeds from HTML meta tags",
  68. slog.String("website_url", websiteURL),
  69. slog.String("content_type", responseHandler.ContentType()),
  70. )
  71. if subscriptions, localizedError := f.findSubscriptionsFromWebPage(websiteURL, responseHandler.ContentType(), bytes.NewReader(responseBody)); localizedError != nil {
  72. return nil, localizedError
  73. } else if len(subscriptions) > 0 {
  74. slog.Debug("Subscriptions found from web page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  75. return subscriptions, nil
  76. }
  77. // Step 4) Check if the website URL can use RSS-Bridge.
  78. if rssBridgeURL != "" {
  79. slog.Debug("Try to detect feeds with RSS-Bridge", slog.String("website_url", websiteURL))
  80. if subscriptions, localizedError := f.findSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL, rssBridgeToken); localizedError != nil {
  81. return nil, localizedError
  82. } else if len(subscriptions) > 0 {
  83. slog.Debug("Subscriptions found from RSS-Bridge", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  84. return subscriptions, nil
  85. }
  86. }
  87. // Step 5) Check if the website has a known feed URL.
  88. slog.Debug("Try to detect feeds from well-known URLs", slog.String("website_url", websiteURL))
  89. if subscriptions, localizedError := f.findSubscriptionsFromWellKnownURLs(websiteURL); localizedError != nil {
  90. return nil, localizedError
  91. } else if len(subscriptions) > 0 {
  92. slog.Debug("Subscriptions found with well-known URLs", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  93. return subscriptions, nil
  94. }
  95. return nil, nil
  96. }
  97. func (f *subscriptionFinder) findSubscriptionsFromWebPage(websiteURL, contentType string, body io.Reader) (Subscriptions, *locale.LocalizedErrorWrapper) {
  98. queries := map[string]string{
  99. "link[type='application/rss+xml']": parser.FormatRSS,
  100. "link[type='application/atom+xml']": parser.FormatAtom,
  101. "link[type='application/json'], link[type='application/feed+json']": parser.FormatJSON,
  102. }
  103. htmlDocumentReader, err := encoding.NewCharsetReader(body, contentType)
  104. if err != nil {
  105. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_parse_html_document", err)
  106. }
  107. doc, err := goquery.NewDocumentFromReader(htmlDocumentReader)
  108. if err != nil {
  109. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_parse_html_document", err)
  110. }
  111. if hrefValue, exists := doc.FindMatcher(goquery.Single("head base")).Attr("href"); exists {
  112. hrefValue = strings.TrimSpace(hrefValue)
  113. if urllib.IsAbsoluteURL(hrefValue) {
  114. websiteURL = hrefValue
  115. }
  116. }
  117. var subscriptions Subscriptions
  118. subscriptionURLs := make(map[string]bool)
  119. for query, kind := range queries {
  120. doc.Find(query).Each(func(i int, s *goquery.Selection) {
  121. subscription := new(subscription)
  122. subscription.Type = kind
  123. if feedURL, exists := s.Attr("href"); exists && feedURL != "" {
  124. subscription.URL, err = urllib.AbsoluteURL(websiteURL, feedURL)
  125. if err != nil {
  126. return
  127. }
  128. } else {
  129. return // without an url, there can be no subscription.
  130. }
  131. if title, exists := s.Attr("title"); exists {
  132. subscription.Title = title
  133. }
  134. if subscription.Title == "" {
  135. subscription.Title = subscription.URL
  136. }
  137. if !subscriptionURLs[subscription.URL] {
  138. subscriptionURLs[subscription.URL] = true
  139. subscriptions = append(subscriptions, subscription)
  140. }
  141. })
  142. }
  143. return subscriptions, nil
  144. }
  145. func (f *subscriptionFinder) findSubscriptionsFromWellKnownURLs(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  146. knownURLs := map[string]string{
  147. "atom.xml": parser.FormatAtom,
  148. "feed.atom": parser.FormatAtom,
  149. "feed.xml": parser.FormatAtom,
  150. "feed/": parser.FormatAtom,
  151. "index.rss": parser.FormatRSS,
  152. "index.xml": parser.FormatRSS,
  153. "rss.xml": parser.FormatRSS,
  154. "rss/": parser.FormatRSS,
  155. "rss/feed.xml": parser.FormatRSS,
  156. }
  157. websiteURLRoot := urllib.RootURL(websiteURL)
  158. baseURLs := []string{
  159. // Look for knownURLs in the root.
  160. websiteURLRoot,
  161. }
  162. // Look for knownURLs in current subdirectory, such as 'example.com/blog/'.
  163. websiteURL, _ = urllib.AbsoluteURL(websiteURL, "./")
  164. if websiteURL != websiteURLRoot {
  165. baseURLs = append(baseURLs, websiteURL)
  166. }
  167. var subscriptions Subscriptions
  168. for _, baseURL := range baseURLs {
  169. for knownURL, kind := range knownURLs {
  170. fullURL, err := urllib.AbsoluteURL(baseURL, knownURL)
  171. if err != nil {
  172. continue
  173. }
  174. // Some websites redirects unknown URLs to the home page.
  175. // As result, the list of known URLs is returned to the subscription list.
  176. // We don't want the user to choose between invalid feed URLs.
  177. f.requestBuilder.WithoutRedirects()
  178. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(fullURL))
  179. localizedError := responseHandler.LocalizedError()
  180. responseHandler.Close()
  181. // Do not add redirections to the possible list of subscriptions to avoid confusion.
  182. if responseHandler.IsRedirect() {
  183. slog.Debug("Ignore URL redirection during feed discovery", slog.String("fullURL", fullURL))
  184. continue
  185. }
  186. if localizedError != nil {
  187. slog.Debug("Ignore invalid feed URL during feed discovery",
  188. slog.String("fullURL", fullURL),
  189. slog.Any("error", localizedError.Error()),
  190. )
  191. continue
  192. }
  193. subscriptions = append(subscriptions, &subscription{
  194. Type: kind,
  195. Title: fullURL,
  196. URL: fullURL,
  197. })
  198. }
  199. }
  200. return subscriptions, nil
  201. }
  202. func (f *subscriptionFinder) findSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL string, rssBridgeToken string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  203. slog.Debug("Trying to detect feeds using RSS-Bridge",
  204. slog.String("website_url", websiteURL),
  205. slog.String("rssbridge_url", rssBridgeURL),
  206. slog.String("rssbridge_token", rssBridgeToken),
  207. )
  208. bridges, err := rssbridge.DetectBridges(rssBridgeURL, rssBridgeToken, websiteURL)
  209. if err != nil {
  210. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_detect_rssbridge", err)
  211. }
  212. slog.Debug("RSS-Bridge results",
  213. slog.String("website_url", websiteURL),
  214. slog.String("rssbridge_url", rssBridgeURL),
  215. slog.String("rssbridge_token", rssBridgeToken),
  216. slog.Int("nb_bridges", len(bridges)),
  217. )
  218. if len(bridges) == 0 {
  219. return nil, nil
  220. }
  221. subscriptions := make(Subscriptions, 0, len(bridges))
  222. for _, bridge := range bridges {
  223. subscriptions = append(subscriptions, &subscription{
  224. Title: bridge.BridgeMeta.Name,
  225. URL: bridge.URL,
  226. Type: parser.FormatAtom,
  227. })
  228. }
  229. return subscriptions, nil
  230. }
  231. func (f *subscriptionFinder) findSubscriptionsFromYouTube(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  232. decodedURL, err := url.Parse(websiteURL)
  233. if err != nil {
  234. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  235. }
  236. if !strings.HasSuffix(decodedURL.Host, "youtube.com") {
  237. slog.Debug("YouTube feed discovery skipped: not a YouTube domain", slog.String("website_url", websiteURL))
  238. return nil, nil
  239. }
  240. if _, channelID, found := strings.Cut(decodedURL.Path, "channel/"); found {
  241. feedURL := "https://www.youtube.com/feeds/videos.xml?channel_id=" + channelID
  242. return Subscriptions{NewSubscription(decodedURL.String(), feedURL, parser.FormatAtom)}, nil
  243. }
  244. if strings.HasPrefix(decodedURL.Path, "/watch") || strings.HasPrefix(decodedURL.Path, "/playlist") {
  245. if playlistID := decodedURL.Query().Get("list"); playlistID != "" {
  246. feedURL := "https://www.youtube.com/feeds/videos.xml?playlist_id=" + playlistID
  247. return Subscriptions{NewSubscription(decodedURL.String(), feedURL, parser.FormatAtom)}, nil
  248. }
  249. }
  250. return nil, nil
  251. }