finder.go 12 KB

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