finder.go 12 KB

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