-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrules.go
119 lines (103 loc) · 2.36 KB
/
rules.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
package scam_backoffice_rules
import (
_ "embed"
"encoding/json"
"fmt"
"github.com/labstack/gommon/log"
"gopkg.in/yaml.v3"
"regexp"
)
//go:embed default_rules.yaml
var defaultRules []byte
type TypeOfAction string
type TypeOfItem string
const (
Accept TypeOfAction = "accept"
Drop TypeOfAction = "drop"
MarkScam TypeOfAction = "mark_scam"
UnKnown TypeOfAction = "unknown"
)
const (
All TypeOfItem = "all"
Comment TypeOfItem = "comment"
Nft TypeOfItem = "nft"
)
type ConvertedRules struct {
Rules []struct {
Pattern string `yaml:"pattern" json:"pattern"`
Action TypeOfAction `yaml:"action" json:"action"`
Type TypeOfItem `yaml:"type" json:"type"`
} `yaml:"rules" json:"rules"`
}
type Rule struct {
Evaluate func(comment string) TypeOfAction
Type TypeOfItem
}
type Rules []Rule
func LoadRules(bytesOfRules []byte, yamlConverted bool) Rules {
var rules Rules
var convertedRules ConvertedRules
var err error
if yamlConverted {
err = yaml.Unmarshal(bytesOfRules, &convertedRules)
} else {
err = json.Unmarshal(bytesOfRules, &convertedRules)
}
if err != nil {
log.Panicf("Failed to parse rules: %v", err)
}
for _, inputRule := range convertedRules.Rules {
compiledRegexp, err := regexp.Compile(inputRule.Pattern)
if err != nil {
fmt.Printf("Failed to compile regexp for pattern %s: %v", inputRule.Pattern, err)
continue
}
var rule Rule
action := inputRule.Action
rule.Evaluate = func(text string) TypeOfAction {
match := compiledRegexp.MatchString(text)
if !match {
return UnKnown
}
return action
}
rule.Type = inputRule.Type
rules = append(rules, rule)
}
return rules
}
func CheckAction(rules Rules, comment string) TypeOfAction {
var err error
comment, err = NormalizeComment(comment)
if err != nil {
return Drop
}
action := UnKnown
for _, rule := range rules {
action = rule.Evaluate(comment)
if action != UnKnown {
break
}
}
return action
}
func CheckActionOfType(rules Rules, text string, itemType TypeOfItem) TypeOfAction {
var err error
text, err = NormalizeComment(text)
if err != nil {
return Drop
}
action := UnKnown
for _, rule := range rules {
if rule.Type == itemType || rule.Type == All {
action = rule.Evaluate(text)
if action != UnKnown {
break
}
}
}
return action
}
func GetDefaultRules() Rules {
return LoadRules(defaultRules, true)
}