forked from raviqqe/muffet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
link_finder.go
73 lines (60 loc) · 1.32 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
package main
import (
"net/url"
"regexp"
"strings"
"github.com/yhat/scrape"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
var validSchemes = map[string]struct{}{
"": {},
"http": {},
"https": {},
}
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"},
}
type linkFinder struct {
excludedPatterns []*regexp.Regexp
}
func newLinkFinder(rs []*regexp.Regexp) linkFinder {
return linkFinder{rs}
}
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
}) {
for _, a := range atomToAttributes[n.DataAtom] {
s := strings.TrimSpace(scrape.Attr(n, a))
if s == "" || f.isLinkExcluded(s) {
continue
}
u, err := url.Parse(s)
if err != nil {
ls[s] = err
continue
} else if _, ok := validSchemes[u.Scheme]; ok {
ls[base.ResolveReference(u).String()] = nil
}
}
}
return ls
}
func (f linkFinder) isLinkExcluded(u string) bool {
for _, r := range f.excludedPatterns {
if r.MatchString(u) {
return true
}
}
return false
}