summaryrefslogtreecommitdiff
path: root/modules/urlfilter/urlfilter.go
blob: 00a4bd260a7f686888584a39bfcc2a394a16fc40 (plain) (blame)
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package urlfilter

import (
	"regexp"

	"github.com/philippta/flyscrape"
)

func init() {
	flyscrape.RegisterModule(new(Module))
}

type Module struct {
	URL         string   `json:"url"`
	AllowedURLs []string `json:"allowedURLs"`
	BlockedURLs []string `json:"blockedURLs"`

	allowedURLsRE []*regexp.Regexp
	blockedURLsRE []*regexp.Regexp
}

func (m *Module) OnLoad(v flyscrape.Visitor) {
	for _, pat := range m.AllowedURLs {
		re, err := regexp.Compile(pat)
		if err != nil {
			continue
		}
		m.allowedURLsRE = append(m.allowedURLsRE, re)
	}

	for _, pat := range m.BlockedURLs {
		re, err := regexp.Compile(pat)
		if err != nil {
			continue
		}
		m.blockedURLsRE = append(m.blockedURLsRE, re)
	}
}

func (m *Module) CanRequest(rawurl string, depth int) bool {
	// allow root url
	if rawurl == m.URL {
		return true
	}

	// allow if no filter is set
	if len(m.allowedURLsRE) == 0 && len(m.blockedURLsRE) == 0 {
		return true
	}

	ok := false
	if len(m.allowedURLsRE) == 0 {
		ok = true
	}

	for _, re := range m.allowedURLsRE {
		if re.MatchString(rawurl) {
			ok = true
			break
		}
	}

	for _, re := range m.blockedURLsRE {
		if re.MatchString(rawurl) {
			ok = false
			break
		}
	}

	return ok
}

var (
	_ flyscrape.CanRequest = (*Module)(nil)
	_ flyscrape.OnLoad     = (*Module)(nil)
)