forked from nbd-wtf/go-nostr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.go
148 lines (117 loc) · 2.46 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package nostr
import (
"encoding/json"
"slices"
"github.com/mailru/easyjson"
)
type Filters []Filter
type Filter struct {
IDs []string `json:"ids,omitempty"`
Kinds []int `json:"kinds,omitempty"`
Authors []string `json:"authors,omitempty"`
Tags TagMap `json:"-,omitempty"`
Since *Timestamp `json:"since,omitempty"`
Until *Timestamp `json:"until,omitempty"`
Limit int `json:"limit,omitempty"`
Search string `json:"search,omitempty"`
}
type TagMap map[string][]string
func (eff Filters) String() string {
j, _ := json.Marshal(eff)
return string(j)
}
func (eff Filters) Match(event *Event) bool {
for _, filter := range eff {
if filter.Matches(event) {
return true
}
}
return false
}
func (ef Filter) String() string {
j, _ := easyjson.Marshal(ef)
return string(j)
}
func (ef Filter) Matches(event *Event) bool {
if event == nil {
return false
}
if ef.IDs != nil && !slices.Contains(ef.IDs, event.ID) {
return false
}
if ef.Kinds != nil && !slices.Contains(ef.Kinds, event.Kind) {
return false
}
if ef.Authors != nil && !slices.Contains(ef.Authors, event.PubKey) {
return false
}
for f, v := range ef.Tags {
if v != nil && !event.Tags.ContainsAny(f, v) {
return false
}
}
if ef.Since != nil && event.CreatedAt < *ef.Since {
return false
}
if ef.Until != nil && event.CreatedAt > *ef.Until {
return false
}
return true
}
func FilterEqual(a Filter, b Filter) bool {
if !similar(a.Kinds, b.Kinds) {
return false
}
if !similar(a.IDs, b.IDs) {
return false
}
if !similar(a.Authors, b.Authors) {
return false
}
if len(a.Tags) != len(b.Tags) {
return false
}
for f, av := range a.Tags {
if bv, ok := b.Tags[f]; !ok {
return false
} else {
if !similar(av, bv) {
return false
}
}
}
if !arePointerValuesEqual(a.Since, b.Since) {
return false
}
if !arePointerValuesEqual(a.Until, b.Until) {
return false
}
if a.Search != b.Search {
return false
}
return true
}
func (ef Filter) Clone() Filter {
clone := Filter{
IDs: slices.Clone(ef.IDs),
Authors: slices.Clone(ef.Authors),
Kinds: slices.Clone(ef.Kinds),
Limit: ef.Limit,
Search: ef.Search,
}
if ef.Tags != nil {
clone.Tags = make(TagMap, len(ef.Tags))
for k, v := range ef.Tags {
clone.Tags[k] = slices.Clone(v)
}
}
if ef.Since != nil {
since := *ef.Since
clone.Since = &since
}
if ef.Until != nil {
until := *ef.Until
clone.Until = &until
}
return clone
}