-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
link_finder.go
115 lines (91 loc) · 2.1 KB
/
link_finder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"net/url"
"regexp"
"strings"
"unicode"
"github.com/yhat/scrape"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
var atomToAttributes = map[atom.Atom][]string{
atom.A: {"href"},
atom.Frame: {"src"},
atom.Iframe: {"src"},
atom.Img: {"src"},
atom.Link: {"href"},
atom.Script: {"src"},
atom.Source: {"src", "srcset"},
atom.Track: {"src"},
atom.Meta: {"content"},
}
var imageDescriptorPattern = regexp.MustCompile(`(\S)\s+\S+\s*$`)
type linkFinder struct {
linkFilterer linkFilterer
}
func newLinkFinder(f linkFilterer) linkFinder {
return linkFinder{f}
}
func (f linkFinder) Find(n *html.Node, base *url.URL) map[string]error {
ls := map[string]error{}
for _, n := range scrape.FindAllNested(n, func(n *html.Node) bool {
_, ok := atomToAttributes[n.DataAtom]
return ok
}) {
// `preconnect` and `dns-prefetch` links are not HTTP resources.
if n.DataAtom == atom.Link {
if rel := scrape.Attr(n, "rel"); rel == "preconnect" || rel == "dns-prefetch" {
continue
}
}
for _, a := range atomToAttributes[n.DataAtom] {
ss := f.parseLinks(n, a)
for _, s := range ss {
s := f.trimUrl(s)
if s == "" {
continue
}
u, err := url.Parse(s)
if err != nil {
ls[s] = err
continue
}
u = base.ResolveReference(u)
if f.linkFilterer.IsValid(u) {
ls[u.String()] = nil
}
}
}
}
return ls
}
func (f linkFinder) parseLinks(n *html.Node, a string) []string {
s := scrape.Attr(n, a)
ss := []string{}
switch a {
case "srcset":
for _, s := range strings.Split(s, ",") {
ss = append(ss, f.trimUrl(imageDescriptorPattern.ReplaceAllString(s, "$1")))
}
case "content":
switch scrape.Attr(n, "property") {
case "og:image", "og:audio", "og:video", "og:image:url", "og:image:secure_url", "twitter:image":
ss = append(ss, s)
}
default:
ss = append(ss, s)
}
return ss
}
func (linkFinder) trimUrl(s string) string {
s = strings.TrimSpace(s)
if !strings.HasPrefix(s, "data:") {
return s
}
return strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, s)
}