finder.go 12 KB

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