finder.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. var subscriptions Subscriptions
  107. // There are 4 possible feed formats
  108. subscriptionURLs := make(map[string]bool, 4)
  109. // Single DOM walk over every <link> with a type attribute, then dispatch on
  110. // the MIME type. This is better than doing a separate goquery.Find pass per
  111. // type.
  112. doc.Find("link[type]").Each(func(_ int, s *goquery.Selection) {
  113. typeAttr, _ := s.Attr("type")
  114. var feedFormat string
  115. switch typeAttr {
  116. case "application/rss+xml":
  117. feedFormat = parser.FormatRSS
  118. case "application/atom+xml":
  119. feedFormat = parser.FormatAtom
  120. case "application/feed+json":
  121. feedFormat = parser.FormatJSON
  122. case "application/json":
  123. // Ignore JSON feed URLs that contain "/wp-json/" to avoid confusion
  124. // with WordPress REST API endpoints.
  125. if href, _ := s.Attr("href"); strings.Contains(href, "/wp-json/") {
  126. return
  127. }
  128. feedFormat = parser.FormatJSON
  129. default:
  130. return
  131. }
  132. feedURL, _ := s.Attr("href")
  133. if feedURL == "" {
  134. return // without an url, there can be no subscription.
  135. }
  136. absoluteURL, err := urllib.ResolveToAbsoluteURL(websiteURL, feedURL)
  137. if err != nil {
  138. return
  139. }
  140. if subscriptionURLs[absoluteURL] {
  141. return
  142. }
  143. subscriptionURLs[absoluteURL] = true
  144. title, _ := s.Attr("title")
  145. if title == "" {
  146. title = absoluteURL
  147. }
  148. subscriptions = append(subscriptions, &subscription{
  149. Type: feedFormat,
  150. Title: title,
  151. URL: absoluteURL,
  152. })
  153. })
  154. return subscriptions, nil
  155. }
  156. func (f *subscriptionFinder) findSubscriptionsFromWellKnownURLs(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  157. knownURLs := [...]struct {
  158. path, format string
  159. }{
  160. {"atom.xml", parser.FormatAtom},
  161. {"feed.atom", parser.FormatAtom},
  162. {"feed.xml", parser.FormatAtom},
  163. {"feed/", parser.FormatAtom},
  164. {"index.rss", parser.FormatRSS},
  165. {"index.xml", parser.FormatRSS},
  166. {"rss.xml", parser.FormatRSS},
  167. {"rss/", parser.FormatRSS},
  168. {"rss/feed.xml", parser.FormatRSS},
  169. }
  170. websiteURLRoot := urllib.RootURL(websiteURL)
  171. baseURLs := []string{
  172. // Look for knownURLs in the root.
  173. websiteURLRoot,
  174. }
  175. // Look for knownURLs in current subdirectory, such as 'example.com/blog/'.
  176. websiteURL, _ = urllib.ResolveToAbsoluteURL(websiteURL, "./")
  177. if websiteURL != websiteURLRoot {
  178. baseURLs = append(baseURLs, websiteURL)
  179. }
  180. var subscriptions Subscriptions
  181. for _, baseURL := range baseURLs {
  182. for _, known := range knownURLs {
  183. fullURL, err := urllib.ResolveToAbsoluteURL(baseURL, known.path)
  184. if err != nil {
  185. continue
  186. }
  187. // Some websites redirects unknown URLs to the home page.
  188. // As result, the list of known URLs is returned to the subscription list.
  189. // We don't want the user to choose between invalid feed URLs.
  190. f.requestBuilder.WithoutRedirects()
  191. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(fullURL))
  192. localizedError := responseHandler.LocalizedError()
  193. responseHandler.Close()
  194. // Do not add redirections to the possible list of subscriptions to avoid confusion.
  195. if responseHandler.IsRedirect() {
  196. slog.Debug("Ignore URL redirection during feed discovery", slog.String("fullURL", fullURL))
  197. continue
  198. }
  199. if localizedError != nil {
  200. slog.Debug("Ignore invalid feed URL during feed discovery",
  201. slog.String("fullURL", fullURL),
  202. slog.Any("error", localizedError.Error()),
  203. )
  204. continue
  205. }
  206. subscriptions = append(subscriptions, &subscription{
  207. Type: known.format,
  208. Title: fullURL,
  209. URL: fullURL,
  210. })
  211. }
  212. }
  213. return subscriptions, nil
  214. }
  215. func (f *subscriptionFinder) findSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL string, rssBridgeToken string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  216. slog.Debug("Trying to detect feeds using RSS-Bridge",
  217. slog.String("website_url", websiteURL),
  218. slog.String("rssbridge_url", rssBridgeURL),
  219. slog.String("rssbridge_token", rssBridgeToken),
  220. )
  221. bridges, err := rssbridge.DetectBridges(rssBridgeURL, rssBridgeToken, websiteURL)
  222. if err != nil {
  223. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_detect_rssbridge", err)
  224. }
  225. slog.Debug("RSS-Bridge results",
  226. slog.String("website_url", websiteURL),
  227. slog.String("rssbridge_url", rssBridgeURL),
  228. slog.String("rssbridge_token", rssBridgeToken),
  229. slog.Int("nb_bridges", len(bridges)),
  230. )
  231. if len(bridges) == 0 {
  232. return nil, nil
  233. }
  234. subscriptions := make(Subscriptions, 0, len(bridges))
  235. for _, bridge := range bridges {
  236. subscriptions = append(subscriptions, &subscription{
  237. Title: bridge.BridgeMeta.Name,
  238. URL: bridge.URL,
  239. Type: parser.FormatAtom,
  240. })
  241. }
  242. return subscriptions, nil
  243. }
  244. func (f *subscriptionFinder) findSubscriptionsFromYouTube(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  245. playlistPrefixes := []struct {
  246. prefix string
  247. title string
  248. }{
  249. {"UULF", "Videos"},
  250. {"UUSH", "Short videos"},
  251. {"UULV", "Live streams"},
  252. }
  253. decodedURL, err := url.Parse(websiteURL)
  254. if err != nil {
  255. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  256. }
  257. if !strings.HasSuffix(decodedURL.Host, "youtube.com") {
  258. slog.Debug("YouTube feed discovery skipped: not a YouTube domain", slog.String("website_url", websiteURL))
  259. return nil, nil
  260. }
  261. if _, baseID, found := strings.Cut(decodedURL.Path, "channel/UC"); found {
  262. var subscriptions Subscriptions
  263. channelFeedURL := "https://www.youtube.com/feeds/videos.xml?channel_id=UC" + baseID
  264. subscriptions = append(subscriptions, NewSubscription("Channel", channelFeedURL, parser.FormatAtom))
  265. for _, playlist := range playlistPrefixes {
  266. playlistFeedURL := "https://www.youtube.com/feeds/videos.xml?playlist_id=" + playlist.prefix + baseID
  267. subscriptions = append(subscriptions, NewSubscription(playlist.title, playlistFeedURL, parser.FormatAtom))
  268. }
  269. return subscriptions, nil
  270. }
  271. if strings.HasPrefix(decodedURL.Path, "/watch") || strings.HasPrefix(decodedURL.Path, "/playlist") {
  272. if playlistID := decodedURL.Query().Get("list"); playlistID != "" {
  273. feedURL := "https://www.youtube.com/feeds/videos.xml?playlist_id=" + playlistID
  274. return Subscriptions{NewSubscription(decodedURL.String(), feedURL, parser.FormatAtom)}, nil
  275. }
  276. }
  277. return nil, nil
  278. }
  279. // findCanonicalURL extracts the canonical URL from the HTML <link rel="canonical"> tag.
  280. // Returns the canonical URL if found, otherwise returns the effective URL.
  281. func (f *subscriptionFinder) findCanonicalURL(effectiveURL, baseURL string, doc *goquery.Document) string {
  282. canonicalHref, exists := doc.FindMatcher(goquery.Single("head link[rel='canonical' i]")).Attr("href")
  283. if !exists {
  284. return effectiveURL
  285. }
  286. canonicalHref = strings.TrimSpace(canonicalHref)
  287. if canonicalHref == "" {
  288. return effectiveURL
  289. }
  290. canonicalURL, err := urllib.ResolveToAbsoluteURL(baseURL, canonicalHref)
  291. if err != nil {
  292. return effectiveURL
  293. }
  294. return canonicalURL
  295. }
  296. // getBaseURL returns the url specified in the <base> tag, and `websiteURL` otherwise.
  297. func getBaseURL(websiteURL string, doc *goquery.Document) string {
  298. baseURL := websiteURL
  299. if hrefValue, exists := doc.FindMatcher(goquery.Single("head base")).Attr("href"); exists {
  300. hrefValue = strings.TrimSpace(hrefValue)
  301. if urllib.IsAbsoluteURL(hrefValue) {
  302. baseURL = hrefValue
  303. }
  304. }
  305. return baseURL
  306. }
  307. func parseHTMLDocument(contentType string, body []byte) (*goquery.Document, error) {
  308. htmlDocumentReader, err := encoding.NewCharsetReaderFromBytes(body, contentType)
  309. if err != nil {
  310. return nil, err
  311. }
  312. doc, err := goquery.NewDocumentFromReader(htmlDocumentReader)
  313. if err != nil {
  314. return nil, err
  315. }
  316. return doc, nil
  317. }