finder.go 12 KB

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