finder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. "index.rss": parser.FormatRSS,
  170. "index.xml": parser.FormatRSS,
  171. "feed.atom": parser.FormatAtom,
  172. }
  173. websiteURLRoot := urllib.RootURL(websiteURL)
  174. baseURLs := []string{
  175. // Look for knownURLs in the root.
  176. websiteURLRoot,
  177. }
  178. // Look for knownURLs in current subdirectory, such as 'example.com/blog/'.
  179. websiteURL, _ = urllib.AbsoluteURL(websiteURL, "./")
  180. if websiteURL != websiteURLRoot {
  181. baseURLs = append(baseURLs, websiteURL)
  182. }
  183. var subscriptions Subscriptions
  184. for _, baseURL := range baseURLs {
  185. for knownURL, kind := range knownURLs {
  186. fullURL, err := urllib.AbsoluteURL(baseURL, knownURL)
  187. if err != nil {
  188. continue
  189. }
  190. // Some websites redirects unknown URLs to the home page.
  191. // As result, the list of known URLs is returned to the subscription list.
  192. // We don't want the user to choose between invalid feed URLs.
  193. f.requestBuilder.WithoutRedirects()
  194. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(fullURL))
  195. localizedError := responseHandler.LocalizedError()
  196. responseHandler.Close()
  197. if localizedError != nil {
  198. slog.Debug("Unable to subscribe", slog.String("fullURL", fullURL), slog.Any("error", localizedError.Error()))
  199. continue
  200. }
  201. subscriptions = append(subscriptions, &Subscription{
  202. Type: kind,
  203. Title: fullURL,
  204. URL: fullURL,
  205. })
  206. }
  207. }
  208. return subscriptions, nil
  209. }
  210. func (f *SubscriptionFinder) FindSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  211. slog.Debug("Trying to detect feeds using RSS-Bridge",
  212. slog.String("website_url", websiteURL),
  213. slog.String("rssbridge_url", rssBridgeURL),
  214. )
  215. bridges, err := rssbridge.DetectBridges(rssBridgeURL, websiteURL)
  216. if err != nil {
  217. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_detect_rssbridge", err)
  218. }
  219. slog.Debug("RSS-Bridge results",
  220. slog.String("website_url", websiteURL),
  221. slog.String("rssbridge_url", rssBridgeURL),
  222. slog.Int("nb_bridges", len(bridges)),
  223. )
  224. if len(bridges) == 0 {
  225. return nil, nil
  226. }
  227. subscriptions := make(Subscriptions, 0, len(bridges))
  228. for _, bridge := range bridges {
  229. subscriptions = append(subscriptions, &Subscription{
  230. Title: bridge.BridgeMeta.Name,
  231. URL: bridge.URL,
  232. Type: parser.FormatAtom,
  233. })
  234. }
  235. return subscriptions, nil
  236. }
  237. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubeChannelPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  238. matches := youtubeChannelRegex.FindStringSubmatch(websiteURL)
  239. if len(matches) == 2 {
  240. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?channel_id=%s`, matches[1])
  241. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  242. }
  243. slog.Debug("This website is not a YouTube channel page, the regex doesn't match", slog.String("website_url", websiteURL))
  244. return nil, nil
  245. }
  246. func (f *SubscriptionFinder) FindSubscriptionsFromYouTubeVideoPage(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  247. if !youtubeVideoRegex.MatchString(websiteURL) {
  248. slog.Debug("This website is not a YouTube video page, the regex doesn't match", slog.String("website_url", websiteURL))
  249. return nil, nil
  250. }
  251. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(websiteURL))
  252. defer responseHandler.Close()
  253. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  254. return nil, localizedError
  255. }
  256. doc, docErr := goquery.NewDocumentFromReader(responseHandler.Body(config.Opts.HTTPClientMaxBodySize()))
  257. if docErr != nil {
  258. return nil, locale.NewLocalizedErrorWrapper(docErr, "error.unable_to_parse_html_document", docErr)
  259. }
  260. if channelID, exists := doc.Find(`meta[itemprop="channelId"]`).First().Attr("content"); exists {
  261. feedURL := fmt.Sprintf(`https://www.youtube.com/feeds/videos.xml?channel_id=%s`, channelID)
  262. return Subscriptions{NewSubscription(websiteURL, feedURL, parser.FormatAtom)}, nil
  263. }
  264. return nil, nil
  265. }