-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathfile_checker.go
136 lines (106 loc) · 2.23 KB
/
file_checker.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"bytes"
"io/ioutil"
"net/url"
"regexp"
"strings"
"sync"
"time"
"github.com/russross/blackfriday/v2"
"golang.org/x/net/html"
)
type fileChecker struct {
urlChecker urlChecker
semaphore semaphore
}
func newFileChecker(timeout time.Duration, d string, r *regexp.Regexp, s semaphore) fileChecker {
return fileChecker{newURLChecker(timeout, d, r, s), s}
}
func (c fileChecker) Check(f string) ([]urlResult, error) {
n, err := c.parseFile(f)
if err != nil {
return nil, err
}
us, err := c.extractURLs(n)
if err != nil {
return nil, err
}
rc := make(chan urlResult, len(us))
rs := make([]urlResult, 0, len(us))
go c.urlChecker.CheckMany(us, f, rc)
for r := range rc {
rs = append(rs, r)
}
return rs, nil
}
func (c fileChecker) CheckMany(fc <-chan string, rc chan<- fileResult) {
wg := sync.WaitGroup{}
for f := range fc {
wg.Add(1)
go func(f string) {
if rs, err := c.Check(f); err == nil {
rc <- fileResult{filename: f, urlResults: rs}
} else {
rc <- fileResult{filename: f, err: err}
}
wg.Done()
}(f)
}
wg.Wait()
close(rc)
}
func (c fileChecker) parseFile(f string) (*html.Node, error) {
c.semaphore.Request()
bs, err := ioutil.ReadFile(f)
c.semaphore.Release()
if err != nil {
return nil, err
}
if !isHTMLFile(f) {
bs = blackfriday.Run(bs)
}
n, err := html.Parse(bytes.NewReader(bs))
if err != nil {
return nil, err
}
return n, nil
}
func (c fileChecker) extractURLs(n *html.Node) ([]string, error) {
us := make(map[string]bool)
ns := []*html.Node{n}
for len(ns) > 0 {
i := len(ns) - 1
n := ns[i]
ns = ns[:i]
if n.Type == html.ElementNode {
switch n.Data {
case "a":
for _, a := range n.Attr {
if a.Key == "href" && isURL(a.Val) {
us[a.Val] = true
break
}
}
case "img":
for _, a := range n.Attr {
if a.Key == "src" && isURL(a.Val) {
us[a.Val] = true
break
}
}
}
}
for n := n.FirstChild; n != nil; n = n.NextSibling {
ns = append(ns, n)
}
}
return stringSetToSlice(us), nil
}
func isURL(s string) bool {
if strings.HasPrefix(s, "#") {
return false
}
u, err := url.Parse(s)
return err == nil && (u.Scheme == "" || u.Scheme == "http" || u.Scheme == "https")
}