miniflux/reader/scraper/scraper.go

106 lines
2.5 KiB
Go
Raw Normal View History

// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package scraper // import "miniflux.app/v2/reader/scraper"
import (
"errors"
"fmt"
2017-12-11 05:51:04 +01:00
"io"
"strings"
"miniflux.app/v2/config"
"miniflux.app/v2/http/client"
"miniflux.app/v2/logger"
"miniflux.app/v2/reader/readability"
"miniflux.app/v2/url"
2018-08-25 06:51:50 +02:00
2017-12-11 05:51:04 +01:00
"github.com/PuerkitoBio/goquery"
)
// Fetch downloads a web page and returns relevant contents.
2021-08-28 11:30:04 +02:00
func Fetch(websiteURL, rules, userAgent string, cookie string, allowSelfSignedCertificates, useProxy bool) (string, error) {
clt := client.NewClientWithConfig(websiteURL, config.Opts)
clt.WithUserAgent(userAgent)
2021-03-23 04:27:58 +01:00
clt.WithCookie(cookie)
2021-08-28 11:30:04 +02:00
if useProxy {
clt.WithProxy()
}
clt.AllowSelfSignedCertificates = allowSelfSignedCertificates
2018-04-28 19:51:07 +02:00
response, err := clt.Get()
if err != nil {
return "", err
}
if response.HasServerFailure() {
return "", errors.New("scraper: unable to download web page")
}
2020-09-28 01:01:06 +02:00
if !isAllowedContentType(response.ContentType) {
return "", fmt.Errorf("scraper: this resource is not a HTML document (%s)", response.ContentType)
}
if err = response.EnsureUnicodeBody(); err != nil {
return "", err
}
// The entry URL could redirect somewhere else.
sameSite := url.Domain(websiteURL) == url.Domain(response.EffectiveURL)
2017-12-14 06:30:40 +01:00
websiteURL = response.EffectiveURL
2017-12-11 05:51:04 +01:00
if rules == "" {
rules = getPredefinedScraperRules(websiteURL)
}
var content string
if sameSite && rules != "" {
logger.Debug(`[Scraper] Using rules %q for %q`, rules, websiteURL)
content, err = scrapContent(response.Body, rules)
2017-12-11 05:51:04 +01:00
} else {
2018-12-03 05:51:06 +01:00
logger.Debug(`[Scraper] Using readability for %q`, websiteURL)
content, err = readability.ExtractContent(response.Body)
2017-12-11 05:51:04 +01:00
}
if err != nil {
return "", err
}
return content, nil
}
2017-12-11 05:51:04 +01:00
func scrapContent(page io.Reader, rules string) (string, error) {
document, err := goquery.NewDocumentFromReader(page)
if err != nil {
return "", err
}
contents := ""
document.Find(rules).Each(func(i int, s *goquery.Selection) {
var content string
content, _ = goquery.OuterHtml(s)
2017-12-11 05:51:04 +01:00
contents += content
})
return contents, nil
}
func getPredefinedScraperRules(websiteURL string) string {
urlDomain := url.Domain(websiteURL)
for domain, rules := range predefinedRules {
if strings.Contains(urlDomain, domain) {
return rules
}
}
return ""
}
2020-09-28 01:01:06 +02:00
func isAllowedContentType(contentType string) bool {
contentType = strings.ToLower(contentType)
return strings.HasPrefix(contentType, "text/html") ||
strings.HasPrefix(contentType, "application/xhtml+xml")
}