-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.go
117 lines (91 loc) · 2.21 KB
/
filter.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
package gowon
import (
"regexp"
"strings"
"github.com/pkg/errors"
)
const ErrorFilterInvalidChars = "filter contains invalid characters"
const ErrorFilterInvertNotAtBeginning = "Inversion (!) can only exist at the beginning of the filter"
const ErrorFilterInvalidFields = "Filter does not contain two fields, equals should appear once"
const ErrorFilterInvalidKey = "Filter key is invalid, must be one of module, msg, nick, dest, command, args"
func checkFilterSingle(filter string) error {
m, err := regexp.MatchString(`^[!=a-zA-Z0-9]+$`, filter)
if err != nil {
return err
}
if !m {
return errors.New(ErrorFilterInvalidChars)
}
m, err = regexp.MatchString(`[=a-zA-Z]!`, filter)
if err != nil {
return err
}
if m {
return errors.New(ErrorFilterInvertNotAtBeginning)
}
if strings.Count(filter, "=") != 1 {
return errors.New(ErrorFilterInvalidFields)
}
contains := func(ss []string, c string) bool {
for _, s := range ss {
if s == c {
return true
}
}
return false
}
key := strings.TrimPrefix(strings.Split(filter, "=")[0], "!")
if !contains([]string{"module", "msg", "nick", "dest", "command", "args"}, key) {
return errors.New(ErrorFilterInvalidKey)
}
return nil
}
func CheckFilter(filter string) error {
for _, f := range strings.Split(filter, "+") {
err := checkFilterSingle(f)
if err != nil {
return err
}
}
return nil
}
func invert(b, inv bool) bool {
if inv {
return !b
}
return b
}
func filterSingle(m *Message, filter string) (bool, error) {
err := checkFilterSingle(filter)
if err != nil {
return false, err
}
out := false
messageFields := map[string]string{
"module": m.Module,
"msg": m.Msg,
"nick": m.Nick,
"dest": m.Dest,
"command": m.Command,
"args": m.Args,
}
invertFilter := strings.HasPrefix(filter, "!")
kv := strings.Split(strings.TrimPrefix(filter, "!"), "=")
key, value := kv[0], kv[1]
if messageFields[key] == value {
out = true
}
return invert(out, invertFilter), nil
}
func Filter(m *Message, filter string) (bool, error) {
for _, f := range strings.Split(filter, "+") {
res, err := filterSingle(m, f)
if err != nil {
return false, err
}
if !res {
return false, nil
}
}
return true, nil
}