finder.go 11 KB

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