scraper.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package scraper // import "miniflux.app/reader/scraper"
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "strings"
  10. "miniflux.app/config"
  11. "miniflux.app/http/client"
  12. "miniflux.app/logger"
  13. "miniflux.app/reader/readability"
  14. "miniflux.app/url"
  15. "github.com/PuerkitoBio/goquery"
  16. )
  17. // Fetch downloads a web page and returns relevant contents.
  18. func Fetch(websiteURL, rules, userAgent string) (string, error) {
  19. clt := client.NewClientWithConfig(websiteURL, config.Opts)
  20. if userAgent != "" {
  21. clt.WithUserAgent(userAgent)
  22. }
  23. response, err := clt.Get()
  24. if err != nil {
  25. return "", err
  26. }
  27. if response.HasServerFailure() {
  28. return "", errors.New("scraper: unable to download web page")
  29. }
  30. if !isAllowedContentType(response.ContentType) {
  31. return "", fmt.Errorf("scraper: this resource is not a HTML document (%s)", response.ContentType)
  32. }
  33. if err = response.EnsureUnicodeBody(); err != nil {
  34. return "", err
  35. }
  36. // The entry URL could redirect somewhere else.
  37. websiteURL = response.EffectiveURL
  38. if rules == "" {
  39. rules = getPredefinedScraperRules(websiteURL)
  40. }
  41. var content string
  42. if rules != "" {
  43. logger.Debug(`[Scraper] Using rules %q for %q`, rules, websiteURL)
  44. content, err = scrapContent(response.Body, rules)
  45. } else {
  46. logger.Debug(`[Scraper] Using readability for %q`, websiteURL)
  47. content, err = readability.ExtractContent(response.Body)
  48. }
  49. if err != nil {
  50. return "", err
  51. }
  52. return content, nil
  53. }
  54. func scrapContent(page io.Reader, rules string) (string, error) {
  55. document, err := goquery.NewDocumentFromReader(page)
  56. if err != nil {
  57. return "", err
  58. }
  59. contents := ""
  60. document.Find(rules).Each(func(i int, s *goquery.Selection) {
  61. var content string
  62. content, _ = goquery.OuterHtml(s)
  63. contents += content
  64. })
  65. return contents, nil
  66. }
  67. func getPredefinedScraperRules(websiteURL string) string {
  68. urlDomain := url.Domain(websiteURL)
  69. for domain, rules := range predefinedRules {
  70. if strings.Contains(urlDomain, domain) {
  71. return rules
  72. }
  73. }
  74. return ""
  75. }
  76. func isAllowedContentType(contentType string) bool {
  77. contentType = strings.ToLower(contentType)
  78. return strings.HasPrefix(contentType, "text/html") ||
  79. strings.HasPrefix(contentType, "application/xhtml+xml")
  80. }