finder.go 13 KB

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