finder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. "fmt"
  7. "io"
  8. "log/slog"
  9. "net/url"
  10. "regexp"
  11. "strings"
  12. "miniflux.app/v2/internal/config"
  13. "miniflux.app/v2/internal/integration/rssbridge"
  14. "miniflux.app/v2/internal/locale"
  15. "miniflux.app/v2/internal/model"
  16. "miniflux.app/v2/internal/reader/fetcher"
  17. "miniflux.app/v2/internal/reader/parser"
  18. "miniflux.app/v2/internal/urllib"
  19. "github.com/PuerkitoBio/goquery"
  20. "golang.org/x/net/html/charset"
  21. )
  22. var (
  23. youtubeHostRegex = regexp.MustCompile(`youtube\.com$`)
  24. youtubeChannelRegex = regexp.MustCompile(`channel/(.*)$`)
  25. )
  26. type SubscriptionFinder struct {
  27. requestBuilder *fetcher.RequestBuilder
  28. feedDownloaded bool
  29. feedResponseInfo *model.FeedCreationRequestFromSubscriptionDiscovery
  30. }
  31. func NewSubscriptionFinder(requestBuilder *fetcher.RequestBuilder) *SubscriptionFinder {
  32. return &SubscriptionFinder{
  33. requestBuilder: requestBuilder,
  34. }
  35. }
  36. func (f *SubscriptionFinder) IsFeedAlreadyDownloaded() bool {
  37. return f.feedDownloaded
  38. }
  39. func (f *SubscriptionFinder) FeedResponseInfo() *model.FeedCreationRequestFromSubscriptionDiscovery {
  40. return f.feedResponseInfo
  41. }
  42. func (f *SubscriptionFinder) FindSubscriptions(websiteURL, rssBridgeURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  43. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(websiteURL))
  44. defer responseHandler.Close()
  45. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  46. slog.Warn("Unable to find subscriptions", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  47. return nil, localizedError
  48. }
  49. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  50. if localizedError != nil {
  51. slog.Warn("Unable to find subscriptions", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  52. return nil, localizedError
  53. }
  54. f.feedResponseInfo = &model.FeedCreationRequestFromSubscriptionDiscovery{
  55. Content: bytes.NewReader(responseBody),
  56. ETag: responseHandler.ETag(),
  57. LastModified: responseHandler.LastModified(),
  58. }
  59. // Step 1) Check if the website URL is already a feed.
  60. if feedFormat, _ := parser.DetectFeedFormat(f.feedResponseInfo.Content); feedFormat != parser.FormatUnknown {
  61. f.feedDownloaded = true
  62. return Subscriptions{NewSubscription(responseHandler.EffectiveURL(), responseHandler.EffectiveURL(), feedFormat)}, nil
  63. }
  64. // Step 2) Check if the website URL is a YouTube channel.
  65. slog.Debug("Try to detect feeds from YouTube channel page", slog.String("website_url", websiteURL))
  66. if subscriptions, localizedError := f.FindSubscriptionsFromYouTubeChannelPage(websiteURL); localizedError != nil {
  67. return nil, localizedError
  68. } else if len(subscriptions) > 0 {
  69. slog.Debug("Subscriptions found from YouTube channel page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  70. return subscriptions, nil
  71. }
  72. // Step 3) Check if the website URL is a YouTube playlist.
  73. slog.Debug("Try to detect feeds from YouTube playlist page", slog.String("website_url", websiteURL))
  74. if subscriptions, localizedError := f.FindSubscriptionsFromYouTubePlaylistPage(websiteURL); localizedError != nil {
  75. return nil, localizedError
  76. } else if len(subscriptions) > 0 {
  77. slog.Debug("Subscriptions found from YouTube playlist page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  78. return subscriptions, nil
  79. }
  80. // Step 4) Parse web page to find feeds from HTML meta tags.
  81. slog.Debug("Try to detect feeds from HTML meta tags",
  82. slog.String("website_url", websiteURL),
  83. slog.String("content_type", responseHandler.ContentType()),
  84. )
  85. if subscriptions, localizedError := f.FindSubscriptionsFromWebPage(websiteURL, responseHandler.ContentType(), bytes.NewReader(responseBody)); localizedError != nil {
  86. return nil, localizedError
  87. } else if len(subscriptions) > 0 {
  88. slog.Debug("Subscriptions found from web page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  89. return subscriptions, nil
  90. }
  91. // Step 5) Check if the website URL can use RSS-Bridge.
  92. if rssBridgeURL != "" {
  93. slog.Debug("Try to detect feeds with RSS-Bridge", slog.String("website_url", websiteURL))
  94. if subscriptions, localizedError := f.FindSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL); localizedError != nil {
  95. return nil, localizedError
  96. } else if len(subscriptions) > 0 {
  97. slog.Debug("Subscriptions found from RSS-Bridge", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  98. return subscriptions, nil
  99. }
  100. }
  101. // Step 6) Check if the website has a known feed URL.
  102. slog.Debug("Try to detect feeds from well-known URLs", slog.String("website_url", websiteURL))
  103. if subscriptions, localizedError := f.FindSubscriptionsFromWellKnownURLs(websiteURL); localizedError != nil {
  104. return nil, localizedError
  105. } else if len(subscriptions) > 0 {
  106. slog.Debug("Subscriptions found with well-known URLs", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  107. return subscriptions, nil
  108. }
  109. return nil, nil
  110. }
  111. func (f *SubscriptionFinder) FindSubscriptionsFromWebPage(websiteURL, contentType string, body io.Reader) (Subscriptions, *locale.LocalizedErrorWrapper) {
  112. queries := map[string]string{
  113. "link[type='application/rss+xml']": parser.FormatRSS,
  114. "link[type='application/atom+xml']": parser.FormatAtom,
  115. "link[type='application/json']": parser.FormatJSON,
  116. "link[type='application/feed+json']": parser.FormatJSON,
  117. }
  118. htmlDocumentReader, err := charset.NewReader(body, contentType)
  119. if err != nil {
  120. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_parse_html_document", err)
  121. }
  122. doc, err := goquery.NewDocumentFromReader(htmlDocumentReader)
  123. if err != nil {
  124. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_parse_html_document", err)
  125. }
  126. var subscriptions Subscriptions
  127. subscriptionURLs := make(map[string]bool)
  128. for query, kind := range queries {
  129. doc.Find(query).Each(func(i int, s *goquery.Selection) {
  130. subscription := new(Subscription)
  131. subscription.Type = kind
  132. if title, exists := s.Attr("title"); exists {
  133. subscription.Title = title
  134. }
  135. if feedURL, exists := s.Attr("href"); exists {
  136. if feedURL != "" {
  137. subscription.URL, err = urllib.AbsoluteURL(websiteURL, feedURL)
  138. if err != nil {
  139. return
  140. }
  141. }
  142. }
  143. if subscription.Title == "" {
  144. subscription.Title = subscription.URL
  145. }
  146. if subscription.URL != "" && !subscriptionURLs[subscription.URL] {
  147. subscriptionURLs[subscription.URL] = true
  148. subscriptions = append(subscriptions, subscription)
  149. }
  150. })
  151. }
  152. return subscriptions, nil
  153. }
  154. func (f *SubscriptionFinder) FindSubscriptionsFromWellKnownURLs(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  155. knownURLs := map[string]string{
  156. "atom.xml": parser.FormatAtom,
  157. "feed.xml": parser.FormatAtom,
  158. "feed/": parser.FormatAtom,
  159. "rss.xml": parser.FormatRSS,
  160. "rss/": parser.FormatRSS,
  161. "index.rss": parser.FormatRSS,
  162. "index.xml": parser.FormatRSS,
  163. "feed.atom": parser.FormatAtom,
  164. }
  165. websiteURLRoot := urllib.RootURL(websiteURL)
  166. baseURLs := []string{
  167. // Look for knownURLs in the root.
  168. websiteURLRoot,
  169. }
  170. // Look for knownURLs in current subdirectory, such as 'example.com/blog/'.
  171. websiteURL, _ = urllib.AbsoluteURL(websiteURL, "./")
  172. if websiteURL != websiteURLRoot {
  173. baseURLs = append(baseURLs, websiteURL)
  174. }
  175. var subscriptions Subscriptions
  176. for _, baseURL := range baseURLs {
  177. for knownURL, kind := range knownURLs {
  178. fullURL, err := urllib.AbsoluteURL(baseURL, knownURL)
  179. if err != nil {
  180. continue
  181. }
  182. // Some websites redirects unknown URLs to the home page.
  183. // As result, the list of known URLs is returned to the subscription list.
  184. // We don't want the user to choose between invalid feed URLs.
  185. f.requestBuilder.WithoutRedirects()
  186. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(fullURL))
  187. localizedError := responseHandler.LocalizedError()
  188. responseHandler.Close()
  189. if localizedError != nil {
  190. slog.Debug("Unable to subscribe", slog.String("fullURL", fullURL), slog.Any("error", localizedError.Error()))
  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) (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. )
  207. bridges, err := rssbridge.DetectBridges(rssBridgeURL, websiteURL)
  208. if err != nil {
  209. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_detect_rssbridge", err)
  210. }
  211. slog.Debug("RSS-Bridge results",
  212. slog.String("website_url", websiteURL),
  213. slog.String("rssbridge_url", rssBridgeURL),
  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) FindSubscriptionsFromYouTubeChannelPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  230. decodedUrl, err := url.Parse(websiteURL)
  231. if err != nil {
  232. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  233. }
  234. if !youtubeHostRegex.MatchString(decodedUrl.Host) {
  235. slog.Debug("This website is not a YouTube page, the regex doesn't match", slog.String("website_url", websiteURL))
  236. return nil, nil
  237. }
  238. if matches := youtubeChannelRegex.FindStringSubmatch(decodedUrl.Path); len(matches) == 2 {
  239. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?channel_id=%s`, matches[1])
  240. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  241. }
  242. return nil, nil
  243. }
  244. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubePlaylistPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  245. decodedUrl, err := url.Parse(websiteURL)
  246. if err != nil {
  247. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  248. }
  249. if !youtubeHostRegex.MatchString(decodedUrl.Host) {
  250. slog.Debug("This website is not a YouTube page, the regex doesn't match", slog.String("website_url", websiteURL))
  251. return nil, nil
  252. }
  253. if (strings.HasPrefix(decodedUrl.Path, "/watch") && decodedUrl.Query().Has("list")) || strings.HasPrefix(decodedUrl.Path, "/playlist") {
  254. playlistID := decodedUrl.Query().Get("list")
  255. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?playlist_id=%s`, playlistID)
  256. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  257. }
  258. return nil, nil
  259. }