finder.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. "log/slog"
  7. "net/url"
  8. "strings"
  9. "miniflux.app/v2/internal/config"
  10. "miniflux.app/v2/internal/integration/rssbridge"
  11. "miniflux.app/v2/internal/locale"
  12. "miniflux.app/v2/internal/model"
  13. "miniflux.app/v2/internal/reader/encoding"
  14. "miniflux.app/v2/internal/reader/fetcher"
  15. "miniflux.app/v2/internal/reader/parser"
  16. "miniflux.app/v2/internal/urllib"
  17. "github.com/PuerkitoBio/goquery"
  18. )
  19. type subscriptionFinder struct {
  20. requestBuilder *fetcher.RequestBuilder
  21. feedDownloaded bool
  22. feedResponseInfo *model.FeedCreationRequestFromSubscriptionDiscovery
  23. }
  24. func NewSubscriptionFinder(requestBuilder *fetcher.RequestBuilder) *subscriptionFinder {
  25. return &subscriptionFinder{
  26. requestBuilder: requestBuilder,
  27. }
  28. }
  29. func (f *subscriptionFinder) IsFeedAlreadyDownloaded() bool {
  30. return f.feedDownloaded
  31. }
  32. func (f *subscriptionFinder) FeedResponseInfo() *model.FeedCreationRequestFromSubscriptionDiscovery {
  33. return f.feedResponseInfo
  34. }
  35. func (f *subscriptionFinder) FindSubscriptions(websiteURL, rssBridgeURL string, rssBridgeToken string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  36. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(websiteURL))
  37. defer responseHandler.Close()
  38. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  39. slog.Warn("Unable to find subscriptions", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  40. return nil, localizedError
  41. }
  42. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  43. if 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. f.feedResponseInfo = &model.FeedCreationRequestFromSubscriptionDiscovery{
  48. Content: bytes.NewReader(responseBody),
  49. ETag: responseHandler.ETag(),
  50. LastModified: responseHandler.LastModified(),
  51. }
  52. // Step 1) Check if the website URL is already a feed.
  53. if feedFormat, _ := parser.DetectFeedFormat(f.feedResponseInfo.Content); feedFormat != parser.FormatUnknown {
  54. f.feedDownloaded = true
  55. return Subscriptions{NewSubscription(responseHandler.EffectiveURL(), responseHandler.EffectiveURL(), feedFormat)}, nil
  56. }
  57. // It's not a feed, so we have to process its HTML.
  58. doc, err := parseHTMLDocument(responseHandler.ContentType(), responseBody)
  59. if err != nil {
  60. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_parse_html_document", err)
  61. }
  62. baseURL := getBaseURL(websiteURL, doc)
  63. // Step 2) Find the canonical URL of the website.
  64. slog.Debug("Try to find the canonical URL of the website", slog.String("website_url", websiteURL))
  65. websiteURL = f.findCanonicalURL(websiteURL, baseURL, doc)
  66. // Step 3) Check if the website URL is a YouTube channel.
  67. slog.Debug("Try to detect feeds for a YouTube page", slog.String("website_url", websiteURL))
  68. if subscriptions, localizedError := f.findSubscriptionsFromYouTube(websiteURL); localizedError != nil {
  69. return nil, localizedError
  70. } else if len(subscriptions) > 0 {
  71. slog.Debug("Subscriptions found from YouTube page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  72. return subscriptions, nil
  73. }
  74. // Step 4) Check if the website URL is a GitHub page.
  75. slog.Debug("Try to detect feeds for a GitHub page", slog.String("website_url", websiteURL))
  76. if subscriptions, localizedError := f.findSubscriptionsFromGitHub(websiteURL); localizedError != nil {
  77. return nil, localizedError
  78. } else if len(subscriptions) > 0 {
  79. slog.Debug("Subscriptions found from GitHub page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  80. return subscriptions, nil
  81. }
  82. // Step 5) 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. if subscriptions, localizedError := f.findSubscriptionsFromWebPage(baseURL, doc); localizedError != nil {
  88. return nil, localizedError
  89. } else if len(subscriptions) > 0 {
  90. slog.Debug("Subscriptions found from web page", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  91. return subscriptions, nil
  92. }
  93. // Step 6) Check if the website URL can use RSS-Bridge.
  94. if rssBridgeURL != "" {
  95. slog.Debug("Try to detect feeds with RSS-Bridge", slog.String("website_url", websiteURL))
  96. if subscriptions, localizedError := f.findSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL, rssBridgeToken); localizedError != nil {
  97. return nil, localizedError
  98. } else if len(subscriptions) > 0 {
  99. slog.Debug("Subscriptions found from RSS-Bridge", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  100. return subscriptions, nil
  101. }
  102. }
  103. // Step 7) Check if the website has a known feed URL.
  104. slog.Debug("Try to detect feeds from well-known URLs", slog.String("website_url", websiteURL))
  105. if subscriptions, localizedError := f.findSubscriptionsFromWellKnownURLs(websiteURL); localizedError != nil {
  106. return nil, localizedError
  107. } else if len(subscriptions) > 0 {
  108. slog.Debug("Subscriptions found with well-known URLs", slog.String("website_url", websiteURL), slog.Any("subscriptions", subscriptions))
  109. return subscriptions, nil
  110. }
  111. return nil, nil
  112. }
  113. func (f *subscriptionFinder) findSubscriptionsFromWebPage(websiteURL string, doc *goquery.Document) (Subscriptions, *locale.LocalizedErrorWrapper) {
  114. var subscriptions Subscriptions
  115. // There are 4 possible feed formats
  116. subscriptionURLs := make(map[string]bool, 4)
  117. // Single DOM walk over every <link> with a type attribute, then dispatch on
  118. // the MIME type. This is better than doing a separate goquery.Find pass per
  119. // type.
  120. doc.Find("link[type]").Each(func(_ int, s *goquery.Selection) {
  121. typeAttr, _ := s.Attr("type")
  122. var feedFormat string
  123. switch typeAttr {
  124. case "application/rss+xml":
  125. feedFormat = parser.FormatRSS
  126. case "application/atom+xml":
  127. feedFormat = parser.FormatAtom
  128. case "application/feed+json":
  129. feedFormat = parser.FormatJSON
  130. case "application/json":
  131. // Ignore JSON feed URLs that contain "/wp-json/" to avoid confusion
  132. // with WordPress REST API endpoints.
  133. if href, _ := s.Attr("href"); strings.Contains(href, "/wp-json/") {
  134. return
  135. }
  136. feedFormat = parser.FormatJSON
  137. default:
  138. return
  139. }
  140. feedURL, _ := s.Attr("href")
  141. if feedURL == "" {
  142. return // without an url, there can be no subscription.
  143. }
  144. absoluteURL, err := urllib.ResolveToAbsoluteURL(websiteURL, feedURL)
  145. if err != nil {
  146. return
  147. }
  148. if subscriptionURLs[absoluteURL] {
  149. return
  150. }
  151. subscriptionURLs[absoluteURL] = true
  152. title, _ := s.Attr("title")
  153. if title == "" {
  154. title = absoluteURL
  155. }
  156. subscriptions = append(subscriptions, &subscription{
  157. Type: feedFormat,
  158. Title: title,
  159. URL: absoluteURL,
  160. })
  161. })
  162. return subscriptions, nil
  163. }
  164. func (f *subscriptionFinder) findSubscriptionsFromWellKnownURLs(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  165. type pair struct{ path, format string }
  166. knownURLs := []pair{
  167. {"atom.xml", parser.FormatAtom},
  168. {"feed.atom", parser.FormatAtom},
  169. {"feed.xml", parser.FormatAtom},
  170. {"feed/", parser.FormatAtom},
  171. {"index.rss", parser.FormatRSS},
  172. {"index.xml", parser.FormatRSS},
  173. {"rss.xml", parser.FormatRSS},
  174. {"rss/", parser.FormatRSS},
  175. {"rss/feed.xml", parser.FormatRSS},
  176. }
  177. websiteURLRoot := urllib.RootURL(websiteURL)
  178. baseURLs := []string{
  179. // Look for knownURLs in the root.
  180. websiteURLRoot,
  181. }
  182. // Look for knownURLs in current subdirectory, such as 'example.com/blog/'.
  183. websiteURL, _ = urllib.ResolveToAbsoluteURL(websiteURL, "./")
  184. if websiteURL != websiteURLRoot {
  185. baseURLs = append(baseURLs, websiteURL)
  186. }
  187. var subscriptions Subscriptions
  188. for _, baseURL := range baseURLs {
  189. for _, known := range knownURLs {
  190. fullURL, err := urllib.ResolveToAbsoluteURL(baseURL, known.path)
  191. if err != nil {
  192. continue
  193. }
  194. // Some websites redirects unknown URLs to the home page.
  195. // As result, the list of known URLs is returned to the subscription list.
  196. // We don't want the user to choose between invalid feed URLs.
  197. //
  198. // Probe each known URL on its own builder so disabling redirects
  199. // here doesn't leak into the finder's other requests.
  200. requestBuilder := f.requestBuilder.Clone().WithoutRedirects()
  201. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(fullURL))
  202. localizedError := responseHandler.LocalizedError()
  203. responseHandler.Close()
  204. // Do not add redirections to the possible list of subscriptions to avoid confusion.
  205. if responseHandler.IsRedirect() {
  206. slog.Debug("Ignore URL redirection during feed discovery", slog.String("fullURL", fullURL))
  207. continue
  208. }
  209. if localizedError != nil {
  210. slog.Debug("Ignore invalid feed URL during feed discovery",
  211. slog.String("fullURL", fullURL),
  212. slog.Any("error", localizedError.Error()),
  213. )
  214. continue
  215. }
  216. subscriptions = append(subscriptions, &subscription{
  217. Type: known.format,
  218. Title: fullURL,
  219. URL: fullURL,
  220. })
  221. }
  222. }
  223. return subscriptions, nil
  224. }
  225. func (f *subscriptionFinder) findSubscriptionsFromRSSBridge(websiteURL, rssBridgeURL string, rssBridgeToken string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  226. slog.Debug("Trying to detect feeds using RSS-Bridge",
  227. slog.String("website_url", websiteURL),
  228. slog.String("rssbridge_url", rssBridgeURL),
  229. slog.String("rssbridge_token", rssBridgeToken),
  230. )
  231. bridges, err := rssbridge.DetectBridges(rssBridgeURL, rssBridgeToken, websiteURL)
  232. if err != nil {
  233. return nil, locale.NewLocalizedErrorWrapper(err, "error.unable_to_detect_rssbridge", err)
  234. }
  235. slog.Debug("RSS-Bridge results",
  236. slog.String("website_url", websiteURL),
  237. slog.String("rssbridge_url", rssBridgeURL),
  238. slog.String("rssbridge_token", rssBridgeToken),
  239. slog.Int("nb_bridges", len(bridges)),
  240. )
  241. if len(bridges) == 0 {
  242. return nil, nil
  243. }
  244. subscriptions := make(Subscriptions, 0, len(bridges))
  245. for _, bridge := range bridges {
  246. subscriptions = append(subscriptions, &subscription{
  247. Title: bridge.BridgeMeta.Name,
  248. URL: bridge.URL,
  249. Type: parser.FormatAtom,
  250. })
  251. }
  252. return subscriptions, nil
  253. }
  254. func (f *subscriptionFinder) findSubscriptionsFromYouTube(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  255. playlistPrefixes := []struct {
  256. prefix string
  257. title string
  258. }{
  259. {"UULF", "Videos"},
  260. {"UUSH", "Short videos"},
  261. {"UULV", "Live streams"},
  262. }
  263. decodedURL, err := url.Parse(websiteURL)
  264. if err != nil {
  265. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  266. }
  267. if !strings.HasSuffix(decodedURL.Host, "youtube.com") {
  268. slog.Debug("YouTube feed discovery skipped: not a YouTube domain", slog.String("website_url", websiteURL))
  269. return nil, nil
  270. }
  271. if _, baseID, found := strings.Cut(decodedURL.Path, "channel/UC"); found {
  272. var subscriptions Subscriptions
  273. channelFeedURL := "https://www.youtube.com/feeds/videos.xml?channel_id=UC" + baseID
  274. subscriptions = append(subscriptions, NewSubscription("Channel", channelFeedURL, parser.FormatAtom))
  275. for _, playlist := range playlistPrefixes {
  276. playlistFeedURL := "https://www.youtube.com/feeds/videos.xml?playlist_id=" + playlist.prefix + baseID
  277. subscriptions = append(subscriptions, NewSubscription(playlist.title, playlistFeedURL, parser.FormatAtom))
  278. }
  279. return subscriptions, nil
  280. }
  281. if strings.HasPrefix(decodedURL.Path, "/watch") || strings.HasPrefix(decodedURL.Path, "/playlist") {
  282. if playlistID := decodedURL.Query().Get("list"); playlistID != "" {
  283. feedURL := "https://www.youtube.com/feeds/videos.xml?playlist_id=" + playlistID
  284. return Subscriptions{NewSubscription(decodedURL.String(), feedURL, parser.FormatAtom)}, nil
  285. }
  286. }
  287. return nil, nil
  288. }
  289. // findSubscriptionsFromGitHub builds the Atom feed URLs that GitHub exposes for
  290. // user/organization profiles and repositories. These feeds are not advertised
  291. // in the HTML of the pages, so they cannot be discovered through the usual
  292. // mechanisms.
  293. func (f *subscriptionFinder) findSubscriptionsFromGitHub(websiteURL string) (Subscriptions, *locale.LocalizedErrorWrapper) {
  294. decodedURL, err := url.Parse(websiteURL)
  295. if err != nil {
  296. return nil, locale.NewLocalizedErrorWrapper(err, "error.invalid_site_url", err)
  297. }
  298. if decodedURL.Host != "github.com" && decodedURL.Host != "www.github.com" {
  299. slog.Debug("GitHub feed discovery skipped: not a GitHub domain", slog.String("website_url", websiteURL))
  300. return nil, nil
  301. }
  302. // Split the path into at most three segments to determine the kind of page.
  303. // We only care about the first two, so there is no need to keep splitting.
  304. path := strings.Trim(decodedURL.Path, "/")
  305. if path == "" {
  306. // The root page (https://github.com/) has no feed.
  307. return nil, nil
  308. }
  309. segments := strings.SplitN(path, "/", 3)
  310. switch len(segments) {
  311. case 1:
  312. // User or organization profile: https://github.com/<user>
  313. // The activity feed lives at https://github.com/<user>.atom
  314. user := segments[0]
  315. feedURL := "https://github.com/" + user + ".atom"
  316. return Subscriptions{NewSubscription(user, feedURL, parser.FormatAtom)}, nil
  317. case 2:
  318. // Repository: https://github.com/<owner>/<repo>
  319. // GitHub exposes commits, releases and tags Atom feeds for repositories.
  320. repoPath := "https://github.com/" + segments[0] + "/" + segments[1] + "/"
  321. return Subscriptions{
  322. NewSubscription("Commits", repoPath+"commits.atom", parser.FormatAtom),
  323. NewSubscription("Releases", repoPath+"releases.atom", parser.FormatAtom),
  324. NewSubscription("Tags", repoPath+"tags.atom", parser.FormatAtom),
  325. }, nil
  326. default:
  327. // Deeper paths that don't map to a user profile or a repository (e.g.
  328. // https://github.com/owner/repo/tree/branch/dir) have no dedicated feed.
  329. return nil, nil
  330. }
  331. }
  332. // findCanonicalURL extracts the canonical URL from the HTML <link rel="canonical"> tag.
  333. // Returns the canonical URL if found, otherwise returns the effective URL.
  334. func (f *subscriptionFinder) findCanonicalURL(effectiveURL, baseURL string, doc *goquery.Document) string {
  335. canonicalHref, exists := doc.FindMatcher(goquery.Single("head link[rel='canonical' i]")).Attr("href")
  336. if !exists {
  337. return effectiveURL
  338. }
  339. canonicalHref = strings.TrimSpace(canonicalHref)
  340. if canonicalHref == "" {
  341. return effectiveURL
  342. }
  343. canonicalURL, err := urllib.ResolveToAbsoluteURL(baseURL, canonicalHref)
  344. if err != nil {
  345. return effectiveURL
  346. }
  347. return canonicalURL
  348. }
  349. // getBaseURL returns the url specified in the <base> tag, and `websiteURL` otherwise.
  350. func getBaseURL(websiteURL string, doc *goquery.Document) string {
  351. baseURL := websiteURL
  352. if hrefValue, exists := doc.FindMatcher(goquery.Single("head base")).Attr("href"); exists {
  353. hrefValue = strings.TrimSpace(hrefValue)
  354. if urllib.IsAbsoluteURL(hrefValue) {
  355. baseURL = hrefValue
  356. }
  357. }
  358. return baseURL
  359. }
  360. func parseHTMLDocument(contentType string, body []byte) (*goquery.Document, error) {
  361. htmlDocumentReader, err := encoding.NewCharsetReaderFromBytes(body, contentType)
  362. if err != nil {
  363. return nil, err
  364. }
  365. doc, err := goquery.NewDocumentFromReader(htmlDocumentReader)
  366. if err != nil {
  367. return nil, err
  368. }
  369. return doc, nil
  370. }