finder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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/encoding"
  17. "miniflux.app/v2/internal/reader/fetcher"
  18. "miniflux.app/v2/internal/reader/parser"
  19. "miniflux.app/v2/internal/urllib"
  20. "github.com/PuerkitoBio/goquery"
  21. )
  22. var (
  23. youtubeChannelRegex = regexp.MustCompile(`channel/(.*)$`)
  24. )
  25. type SubscriptionFinder struct {
  26. requestBuilder *fetcher.RequestBuilder
  27. feedDownloaded bool
  28. feedResponseInfo *model.FeedCreationRequestFromSubscriptionDiscovery
  29. }
  30. func NewSubscriptionFinder(requestBuilder *fetcher.RequestBuilder) *SubscriptionFinder {
  31. return &SubscriptionFinder{
  32. requestBuilder: requestBuilder,
  33. }
  34. }
  35. func (f *SubscriptionFinder) IsFeedAlreadyDownloaded() bool {
  36. return f.feedDownloaded
  37. }
  38. func (f *SubscriptionFinder) FeedResponseInfo() *model.FeedCreationRequestFromSubscriptionDiscovery {
  39. return f.feedResponseInfo
  40. }
  41. func (f *SubscriptionFinder) FindSubscriptions(websiteURL, rssBridgeURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  42. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(websiteURL))
  43. defer responseHandler.Close()
  44. if localizedError := responseHandler.LocalizedError(); 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. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  49. if localizedError != nil {
  50. slog.Warn("Unable to find subscriptions", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  51. return nil, localizedError
  52. }
  53. f.feedResponseInfo = &model.FeedCreationRequestFromSubscriptionDiscovery{
  54. Content: bytes.NewReader(responseBody),
  55. ETag: responseHandler.ETag(),
  56. LastModified: responseHandler.LastModified(),
  57. }
  58. // Step 1) Check if the website URL is already a feed.
  59. if feedFormat, _ := parser.DetectFeedFormat(f.feedResponseInfo.Content); feedFormat != parser.FormatUnknown {
  60. f.feedDownloaded = true
  61. return Subscriptions{NewSubscription(responseHandler.EffectiveURL(), responseHandler.EffectiveURL(), feedFormat)}, nil
  62. }
  63. // Step 2) Check if the website URL is a YouTube channel.
  64. slog.Debug("Try to detect feeds from YouTube channel page", slog.String("website_url", websiteURL))
  65. if subscriptions, localizedError := f.FindSubscriptionsFromYouTubeChannelPage(websiteURL); localizedError != nil {
  66. return nil, localizedError
  67. } else if len(subscriptions) > 0 {
  68. slog.Debug("Subscriptions found from YouTube channel page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  69. return subscriptions, nil
  70. }
  71. // Step 3) Check if the website URL is a YouTube playlist.
  72. slog.Debug("Try to detect feeds from YouTube playlist page", slog.String("website_url", websiteURL))
  73. if subscriptions, localizedError := f.FindSubscriptionsFromYouTubePlaylistPage(websiteURL); localizedError != nil {
  74. return nil, localizedError
  75. } else if len(subscriptions) > 0 {
  76. slog.Debug("Subscriptions found from YouTube playlist page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  77. return subscriptions, nil
  78. }
  79. // Step 4) Parse web page to find feeds from HTML meta tags.
  80. slog.Debug("Try to detect feeds from HTML meta tags",
  81. slog.String("website_url", websiteURL),
  82. slog.String("content_type", responseHandler.ContentType()),
  83. )
  84. if subscriptions, localizedError := f.FindSubscriptionsFromWebPage(websiteURL, responseHandler.ContentType(), bytes.NewReader(responseBody)); localizedError != nil {
  85. return nil, localizedError
  86. } else if len(subscriptions) > 0 {
  87. slog.Debug("Subscriptions found from web page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  88. return subscriptions, nil
  89. }
  90. // Step 5) Check if the website URL can use RSS-Bridge.
  91. if rssBridgeURL != "" {
  92. slog.Debug("Try to detect feeds with RSS-Bridge", slog.String("website_url", websiteURL))
  93. if subscriptions, localizedError := f.FindSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL); localizedError != nil {
  94. return nil, localizedError
  95. } else if len(subscriptions) > 0 {
  96. slog.Debug("Subscriptions found from RSS-Bridge", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  97. return subscriptions, nil
  98. }
  99. }
  100. // Step 6) Check if the website has a known feed URL.
  101. slog.Debug("Try to detect feeds from well-known URLs", slog.String("website_url", websiteURL))
  102. if subscriptions, localizedError := f.FindSubscriptionsFromWellKnownURLs(websiteURL); localizedError != nil {
  103. return nil, localizedError
  104. } else if len(subscriptions) > 0 {
  105. slog.Debug("Subscriptions found with well-known URLs", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  106. return subscriptions, nil
  107. }
  108. return nil, nil
  109. }
  110. func (f *SubscriptionFinder) FindSubscriptionsFromWebPage(websiteURL, contentType string, body io.Reader) (Subscriptions, *locale.LocalizedErrorWrapper) {
  111. queries := map[string]string{
  112. "link[type='application/rss+xml']": parser.FormatRSS,
  113. "link[type='application/atom+xml']": parser.FormatAtom,
  114. "link[type='application/json']": parser.FormatJSON,
  115. "link[type='application/feed+json']": parser.FormatJSON,
  116. }
  117. htmlDocumentReader, err := encoding.NewCharsetReader(body, contentType)
  118. if err != nil {
  119. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_parse_html_document", err)
  120. }
  121. doc, err := goquery.NewDocumentFromReader(htmlDocumentReader)
  122. if err != nil {
  123. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_parse_html_document", err)
  124. }
  125. if hrefValue, exists := doc.FindMatcher(goquery.Single("head base")).Attr("href"); exists {
  126. hrefValue = strings.TrimSpace(hrefValue)
  127. if urllib.IsAbsoluteURL(hrefValue) {
  128. websiteURL = hrefValue
  129. }
  130. }
  131. var subscriptions Subscriptions
  132. subscriptionURLs := make(map[string]bool)
  133. for query, kind := range queries {
  134. doc.Find(query).Each(func(i int, s *goquery.Selection) {
  135. subscription := new(Subscription)
  136. subscription.Type = kind
  137. if title, exists := s.Attr("title"); exists {
  138. subscription.Title = title
  139. }
  140. if feedURL, exists := s.Attr("href"); exists {
  141. if feedURL != "" {
  142. subscription.URL, err = urllib.AbsoluteURL(websiteURL, feedURL)
  143. if err != nil {
  144. return
  145. }
  146. }
  147. }
  148. if subscription.Title == "" {
  149. subscription.Title = subscription.URL
  150. }
  151. if subscription.URL != "" && !subscriptionURLs[subscription.URL] {
  152. subscriptionURLs[subscription.URL] = true
  153. subscriptions = append(subscriptions, subscription)
  154. }
  155. })
  156. }
  157. return subscriptions, nil
  158. }
  159. func (f *SubscriptionFinder) FindSubscriptionsFromWellKnownURLs(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  160. knownURLs := map[string]string{
  161. "atom.xml": parser.FormatAtom,
  162. "feed.atom": parser.FormatAtom,
  163. "feed.xml": parser.FormatAtom,
  164. "feed/": parser.FormatAtom,
  165. "index.rss": parser.FormatRSS,
  166. "index.xml": parser.FormatRSS,
  167. "rss.xml": parser.FormatRSS,
  168. "rss/": parser.FormatRSS,
  169. "rss/feed.xml": parser.FormatRSS,
  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. // Do not add redirections to the possible list of subscriptions to avoid confusion.
  196. if responseHandler.IsRedirect() {
  197. slog.Debug("Ignore URL redirection during feed discovery", slog.String("fullURL", fullURL))
  198. continue
  199. }
  200. if localizedError != nil {
  201. slog.Debug("Ignore invalid feed URL during feed discovery",
  202. slog.String("fullURL", fullURL),
  203. slog.Any("error", localizedError.Error()),
  204. )
  205. continue
  206. }
  207. subscriptions = append(subscriptions, &Subscription{
  208. Type: kind,
  209. Title: fullURL,
  210. URL: fullURL,
  211. })
  212. }
  213. }
  214. return subscriptions, nil
  215. }
  216. func (f *SubscriptionFinder) FindSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  217. slog.Debug("Trying to detect feeds using RSS-Bridge",
  218. slog.String("website_url", websiteURL),
  219. slog.String("rssbridge_url", rssBridgeURL),
  220. )
  221. bridges, err := rssbridge.DetectBridges(rssBridgeURL, 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.Int("nb_bridges", len(bridges)),
  229. )
  230. if len(bridges) == 0 {
  231. return nil, nil
  232. }
  233. subscriptions := make(Subscriptions, 0, len(bridges))
  234. for _, bridge := range bridges {
  235. subscriptions = append(subscriptions, &Subscription{
  236. Title: bridge.BridgeMeta.Name,
  237. URL: bridge.URL,
  238. Type: parser.FormatAtom,
  239. })
  240. }
  241. return subscriptions, nil
  242. }
  243. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubeChannelPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  244. decodedUrl, err := url.Parse(websiteURL)
  245. if err != nil {
  246. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  247. }
  248. if !strings.HasSuffix(decodedUrl.Host, "youtube.com") {
  249. slog.Debug("This website is not a YouTube page, the regex doesn't match", slog.String("website_url", websiteURL))
  250. return nil, nil
  251. }
  252. if matches := youtubeChannelRegex.FindStringSubmatch(decodedUrl.Path); len(matches) == 2 {
  253. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?channel_id=%s`, matches[1])
  254. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  255. }
  256. return nil, nil
  257. }
  258. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubePlaylistPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  259. decodedUrl, err := url.Parse(websiteURL)
  260. if err != nil {
  261. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  262. }
  263. if !strings.HasSuffix(decodedUrl.Host, "youtube.com") {
  264. slog.Debug("This website is not a YouTube page, the regex doesn't match", slog.String("website_url", websiteURL))
  265. return nil, nil
  266. }
  267. if (strings.HasPrefix(decodedUrl.Path, "/watch") && decodedUrl.Query().Has("list")) || strings.HasPrefix(decodedUrl.Path, "/playlist") {
  268. playlistID := decodedUrl.Query().Get("list")
  269. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?playlist_id=%s`, playlistID)
  270. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  271. }
  272. return nil, nil
  273. }