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