finder.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. "regexp"
  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/fetcher"
  15. "miniflux.app/v2/internal/reader/parser"
  16. "miniflux.app/v2/internal/urllib"
  17. "github.com/PuerkitoBio/goquery"
  18. )
  19. var (
  20. youtubeChannelRegex = regexp.MustCompile(`youtube\.com/channel/(.*)`)
  21. youtubeVideoRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)`)
  22. )
  23. type SubscriptionFinder struct {
  24. requestBuilder *fetcher.RequestBuilder
  25. feedDownloaded bool
  26. feedResponseInfo *model.FeedCreationRequestFromSubscriptionDiscovery
  27. }
  28. func NewSubscriptionFinder(requestBuilder *fetcher.RequestBuilder) *SubscriptionFinder {
  29. return &SubscriptionFinder{
  30. requestBuilder: requestBuilder,
  31. }
  32. }
  33. func (f *SubscriptionFinder) IsFeedAlreadyDownloaded() bool {
  34. return f.feedDownloaded
  35. }
  36. func (f *SubscriptionFinder) FeedResponseInfo() *model.FeedCreationRequestFromSubscriptionDiscovery {
  37. return f.feedResponseInfo
  38. }
  39. func (f *SubscriptionFinder) FindSubscriptions(websiteURL, rssBridgeURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  40. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(websiteURL))
  41. defer responseHandler.Close()
  42. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  43. slog.Warn("Unable to find subscriptions", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  44. return nil, localizedError
  45. }
  46. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  47. if localizedError != nil {
  48. slog.Warn("Unable to find subscriptions", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  49. return nil, localizedError
  50. }
  51. f.feedResponseInfo = &model.FeedCreationRequestFromSubscriptionDiscovery{
  52. Content: bytes.NewReader(responseBody),
  53. ETag: responseHandler.ETag(),
  54. LastModified: responseHandler.LastModified(),
  55. }
  56. // Step 1) Check if the website URL is a feed.
  57. if feedFormat := parser.DetectFeedFormat(f.feedResponseInfo.Content); feedFormat != parser.FormatUnknown {
  58. f.feedDownloaded = true
  59. return Subscriptions{NewSubscription(responseHandler.EffectiveURL(), responseHandler.EffectiveURL(), feedFormat)}, nil
  60. }
  61. // Step 2) Check if the website URL is a YouTube channel.
  62. slog.Debug("Try to detect feeds from YouTube channel page", slog.String("website_url", websiteURL))
  63. subscriptions, localizedError := f.FindSubscriptionsFromYouTubeChannelPage(websiteURL)
  64. if localizedError != nil {
  65. return nil, localizedError
  66. }
  67. 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 video.
  72. slog.Debug("Try to detect feeds from YouTube video page", slog.String("website_url", websiteURL))
  73. subscriptions, localizedError = f.FindSubscriptionsFromYouTubeVideoPage(websiteURL)
  74. if localizedError != nil {
  75. return nil, localizedError
  76. }
  77. if len(subscriptions) > 0 {
  78. slog.Debug("Subscriptions found from YouTube video page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  79. return subscriptions, nil
  80. }
  81. // Step 4) Parse web page to find feeds from HTML meta tags.
  82. slog.Debug("Try to detect feeds from HTML meta tags", slog.String("website_url", websiteURL))
  83. subscriptions, localizedError = f.FindSubscriptionsFromWebPage(websiteURL, bytes.NewReader(responseBody))
  84. if localizedError != nil {
  85. return nil, localizedError
  86. }
  87. 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. subscriptions, localizedError := f.FindSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL)
  95. if localizedError != nil {
  96. return nil, localizedError
  97. }
  98. if len(subscriptions) > 0 {
  99. slog.Debug("Subscriptions found from RSS-Bridge", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  100. return subscriptions, nil
  101. }
  102. }
  103. // Step 6) Check if the website has a known feed URL.
  104. slog.Debug("Try to detect feeds from well-known URLs", slog.String("website_url", websiteURL))
  105. subscriptions, localizedError = f.FindSubscriptionsFromWellKnownURLs(websiteURL)
  106. if localizedError != nil {
  107. return nil, localizedError
  108. }
  109. if len(subscriptions) > 0 {
  110. slog.Debug("Subscriptions found with well-known URLs", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  111. return subscriptions, nil
  112. }
  113. return nil, nil
  114. }
  115. func (f *SubscriptionFinder) FindSubscriptionsFromWebPage(websiteURL string, body io.Reader) (Subscriptions, *locale.LocalizedErrorWrapper) {
  116. queries := map[string]string{
  117. "link[type='application/rss+xml']": parser.FormatRSS,
  118. "link[type='application/atom+xml']": parser.FormatAtom,
  119. "link[type='application/json']": parser.FormatJSON,
  120. "link[type='application/feed+json']": parser.FormatJSON,
  121. }
  122. doc, err := goquery.NewDocumentFromReader(body)
  123. if err != nil {
  124. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_parse_html_document", err)
  125. }
  126. var subscriptions Subscriptions
  127. for query, kind := range queries {
  128. doc.Find(query).Each(func(i int, s *goquery.Selection) {
  129. subscription := new(Subscription)
  130. subscription.Type = kind
  131. if title, exists := s.Attr("title"); exists {
  132. subscription.Title = title
  133. }
  134. if feedURL, exists := s.Attr("href"); exists {
  135. if feedURL != "" {
  136. subscription.URL, _ = urllib.AbsoluteURL(websiteURL, feedURL)
  137. }
  138. }
  139. if subscription.Title == "" {
  140. subscription.Title = subscription.URL
  141. }
  142. if subscription.URL != "" {
  143. subscriptions = append(subscriptions, subscription)
  144. }
  145. })
  146. }
  147. return subscriptions, nil
  148. }
  149. func (f *SubscriptionFinder) FindSubscriptionsFromWellKnownURLs(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  150. knownURLs := map[string]string{
  151. "atom.xml": parser.FormatAtom,
  152. "feed.xml": parser.FormatAtom,
  153. "feed/": parser.FormatAtom,
  154. "rss.xml": parser.FormatRSS,
  155. "rss/": parser.FormatRSS,
  156. }
  157. websiteURLRoot := urllib.RootURL(websiteURL)
  158. baseURLs := []string{
  159. // Look for knownURLs in the root.
  160. websiteURLRoot,
  161. }
  162. // Look for knownURLs in current subdirectory, such as 'example.com/blog/'.
  163. websiteURL, _ = urllib.AbsoluteURL(websiteURL, "./")
  164. if websiteURL != websiteURLRoot {
  165. baseURLs = append(baseURLs, websiteURL)
  166. }
  167. var subscriptions Subscriptions
  168. for _, baseURL := range baseURLs {
  169. for knownURL, kind := range knownURLs {
  170. fullURL, err := urllib.AbsoluteURL(baseURL, knownURL)
  171. if err != nil {
  172. continue
  173. }
  174. // Some websites redirects unknown URLs to the home page.
  175. // As result, the list of known URLs is returned to the subscription list.
  176. // We don't want the user to choose between invalid feed URLs.
  177. f.requestBuilder.WithoutRedirects()
  178. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(fullURL))
  179. defer responseHandler.Close()
  180. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  181. continue
  182. }
  183. subscription := new(Subscription)
  184. subscription.Type = kind
  185. subscription.Title = fullURL
  186. subscription.URL = fullURL
  187. subscriptions = append(subscriptions, subscription)
  188. }
  189. }
  190. return subscriptions, nil
  191. }
  192. func (f *SubscriptionFinder) FindSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  193. slog.Debug("Trying to detect feeds using RSS-Bridge",
  194. slog.String("website_url", websiteURL),
  195. slog.String("rssbridge_url", rssBridgeURL),
  196. )
  197. bridges, err := rssbridge.DetectBridges(rssBridgeURL, websiteURL)
  198. if err != nil {
  199. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_detect_rssbridge", err)
  200. }
  201. slog.Debug("RSS-Bridge results",
  202. slog.String("website_url", websiteURL),
  203. slog.String("rssbridge_url", rssBridgeURL),
  204. slog.Int("nb_bridges", len(bridges)),
  205. )
  206. if len(bridges) == 0 {
  207. return nil, nil
  208. }
  209. var subscriptions Subscriptions
  210. for _, bridge := range bridges {
  211. subscriptions = append(subscriptions, &Subscription{
  212. Title: bridge.BridgeMeta.Name,
  213. URL: bridge.URL,
  214. Type: parser.FormatAtom,
  215. })
  216. }
  217. return subscriptions, nil
  218. }
  219. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubeChannelPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  220. matches := youtubeChannelRegex.FindStringSubmatch(websiteURL)
  221. if len(matches) == 2 {
  222. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?channel_id=%s`, matches[1])
  223. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  224. }
  225. slog.Debug("This website is not a YouTube channel page, the regex doesn't match", slog.String("website_url", websiteURL))
  226. return nil, nil
  227. }
  228. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubeVideoPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  229. if !youtubeVideoRegex.MatchString(websiteURL) {
  230. slog.Debug("This website is not a YouTube video page, the regex doesn't match", slog.String("website_url", websiteURL))
  231. return nil, nil
  232. }
  233. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(websiteURL))
  234. defer responseHandler.Close()
  235. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  236. return nil, localizedError
  237. }
  238. doc, docErr := goquery.NewDocumentFromReader(responseHandler.Body(config.Opts.HTTPClientMaxBodySize()))
  239. if docErr != nil {
  240. return nil, locale.NewLocalizedErrorWrapper(docErr, "error.unable_to_parse_html_document", docErr)
  241. }
  242. if channelID, exists := doc.Find(`meta[itemprop="channelId"]`).First().Attr("content"); exists {
  243. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?channel_id=%s`, channelID)
  244. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  245. }
  246. return nil, nil
  247. }