finder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. if hrefValue, exists := doc.Find("head base").First().Attr("href"); exists {
  127. hrefValue = strings.TrimSpace(hrefValue)
  128. if urllib.IsAbsoluteURL(hrefValue) {
  129. websiteURL = hrefValue
  130. }
  131. }
  132. var subscriptions Subscriptions
  133. subscriptionURLs := make(map[string]bool)
  134. for query, kind := range queries {
  135. doc.Find(query).Each(func(i int, s *goquery.Selection) {
  136. subscription := new(Subscription)
  137. subscription.Type = kind
  138. if title, exists := s.Attr("title"); exists {
  139. subscription.Title = title
  140. }
  141. if feedURL, exists := s.Attr("href"); exists {
  142. if feedURL != "" {
  143. subscription.URL, err = urllib.AbsoluteURL(websiteURL, feedURL)
  144. if err != nil {
  145. return
  146. }
  147. }
  148. }
  149. if subscription.Title == "" {
  150. subscription.Title = subscription.URL
  151. }
  152. if subscription.URL != "" && !subscriptionURLs[subscription.URL] {
  153. subscriptionURLs[subscription.URL] = true
  154. subscriptions = append(subscriptions, subscription)
  155. }
  156. })
  157. }
  158. return subscriptions, nil
  159. }
  160. func (f *SubscriptionFinder) FindSubscriptionsFromWellKnownURLs(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  161. knownURLs := map[string]string{
  162. "atom.xml": parser.FormatAtom,
  163. "feed.xml": parser.FormatAtom,
  164. "feed/": parser.FormatAtom,
  165. "rss.xml": parser.FormatRSS,
  166. "rss/": parser.FormatRSS,
  167. "index.rss": parser.FormatRSS,
  168. "index.xml": parser.FormatRSS,
  169. "feed.atom": parser.FormatAtom,
  170. }
  171. websiteURLRoot := urllib.RootURL(websiteURL)
  172. baseURLs := []string{
  173. // Look for knownURLs in the root.
  174. websiteURLRoot,
  175. }
  176. // Look for knownURLs in current subdirectory, such as 'example.com/blog/'.
  177. websiteURL, _ = urllib.AbsoluteURL(websiteURL, "./")
  178. if websiteURL != websiteURLRoot {
  179. baseURLs = append(baseURLs, websiteURL)
  180. }
  181. var subscriptions Subscriptions
  182. for _, baseURL := range baseURLs {
  183. for knownURL, kind := range knownURLs {
  184. fullURL, err := urllib.AbsoluteURL(baseURL, knownURL)
  185. if err != nil {
  186. continue
  187. }
  188. // Some websites redirects unknown URLs to the home page.
  189. // As result, the list of known URLs is returned to the subscription list.
  190. // We don't want the user to choose between invalid feed URLs.
  191. f.requestBuilder.WithoutRedirects()
  192. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(fullURL))
  193. localizedError := responseHandler.LocalizedError()
  194. responseHandler.Close()
  195. if localizedError != nil {
  196. slog.Debug("Unable to subscribe", slog.String("fullURL", fullURL), slog.Any("error", localizedError.Error()))
  197. continue
  198. }
  199. subscriptions = append(subscriptions, &Subscription{
  200. Type: kind,
  201. Title: fullURL,
  202. URL: fullURL,
  203. })
  204. }
  205. }
  206. return subscriptions, nil
  207. }
  208. func (f *SubscriptionFinder) FindSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  209. slog.Debug("Trying to detect feeds using RSS-Bridge",
  210. slog.String("website_url", websiteURL),
  211. slog.String("rssbridge_url", rssBridgeURL),
  212. )
  213. bridges, err := rssbridge.DetectBridges(rssBridgeURL, 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.Int("nb_bridges", len(bridges)),
  221. )
  222. if len(bridges) == 0 {
  223. return nil, nil
  224. }
  225. subscriptions := make(Subscriptions, 0, len(bridges))
  226. for _, bridge := range bridges {
  227. subscriptions = append(subscriptions, &Subscription{
  228. Title: bridge.BridgeMeta.Name,
  229. URL: bridge.URL,
  230. Type: parser.FormatAtom,
  231. })
  232. }
  233. return subscriptions, nil
  234. }
  235. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubeChannelPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  236. decodedUrl, err := url.Parse(websiteURL)
  237. if err != nil {
  238. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  239. }
  240. if !youtubeHostRegex.MatchString(decodedUrl.Host) {
  241. slog.Debug("This website is not a YouTube page, the regex doesn't match", slog.String("website_url", websiteURL))
  242. return nil, nil
  243. }
  244. if matches := youtubeChannelRegex.FindStringSubmatch(decodedUrl.Path); len(matches) == 2 {
  245. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?channel_id=%s`, matches[1])
  246. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  247. }
  248. return nil, nil
  249. }
  250. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubePlaylistPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  251. decodedUrl, err := url.Parse(websiteURL)
  252. if err != nil {
  253. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  254. }
  255. if !youtubeHostRegex.MatchString(decodedUrl.Host) {
  256. slog.Debug("This website is not a YouTube page, the regex doesn't match", slog.String("website_url", websiteURL))
  257. return nil, nil
  258. }
  259. if (strings.HasPrefix(decodedUrl.Path, "/watch") && decodedUrl.Query().Has("list")) || strings.HasPrefix(decodedUrl.Path, "/playlist") {
  260. playlistID := decodedUrl.Query().Get("list")
  261. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?playlist_id=%s`, playlistID)
  262. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  263. }
  264. return nil, nil
  265. }