go-nostr/filter.go

119 lines
1.7 KiB
Go
Raw Normal View History

2022-01-02 08:44:18 -03:00
package nostr
import (
2022-11-26 09:25:31 -03:00
"encoding/json"
"time"
"golang.org/x/exp/slices"
)
type Filters []Filter
type Filter struct {
IDs []string
Kinds []int
Authors []string
2022-07-24 19:53:10 -03:00
Tags TagMap
Since *time.Time
Until *time.Time
2022-07-24 19:53:10 -03:00
Limit int
2023-02-13 20:32:09 -05:00
Search string
2022-01-02 08:44:18 -03:00
}
type TagMap map[string][]string
2022-02-09 20:25:20 -03:00
2022-11-26 09:25:31 -03:00
func (eff Filters) String() string {
j, _ := json.Marshal(eff)
return string(j)
}
func (eff Filters) Match(event *Event) bool {
2022-01-02 08:44:18 -03:00
for _, filter := range eff {
if filter.Matches(event) {
return true
}
}
return false
}
2022-11-26 09:25:31 -03:00
func (ef Filter) String() string {
j, _ := json.Marshal(ef)
return string(j)
}
func (ef Filter) Matches(event *Event) bool {
2022-01-02 08:44:18 -03:00
if event == nil {
return false
}
if ef.IDs != nil && !containsPrefixOf(ef.IDs, event.ID) {
2022-01-02 08:44:18 -03:00
return false
}
if ef.Kinds != nil && !slices.Contains(ef.Kinds, event.Kind) {
2022-01-02 08:44:18 -03:00
return false
}
if ef.Authors != nil && !containsPrefixOf(ef.Authors, event.PubKey) {
2022-01-02 08:44:18 -03:00
return false
}
for f, v := range ef.Tags {
if v != nil && !event.Tags.ContainsAny(f, v) {
return false
}
2022-01-02 08:44:18 -03:00
}
if ef.Since != nil && time.Time(event.CreatedAt).Before(*ef.Since) {
2022-01-02 08:44:18 -03:00
return false
}
if ef.Until != nil && time.Time(event.CreatedAt).After(*ef.Until) {
2022-01-02 08:44:18 -03:00
return false
}
return true
}
func FilterEqual(a Filter, b Filter) bool {
if !similar(a.Kinds, b.Kinds) {
2022-01-02 08:44:18 -03:00
return false
}
if !similar(a.IDs, b.IDs) {
2022-01-02 08:44:18 -03:00
return false
}
if !similar(a.Authors, b.Authors) {
2022-01-02 08:44:18 -03:00
return false
}
if len(a.Tags) != len(b.Tags) {
2022-01-02 08:44:18 -03:00
return false
}
for f, av := range a.Tags {
if bv, ok := b.Tags[f]; !ok {
return false
} else {
if !similar(av, bv) {
return false
}
}
2022-01-02 08:44:18 -03:00
}
if a.Since != b.Since {
return false
}
if a.Until != b.Until {
return false
}
2023-02-13 20:32:09 -05:00
if a.Search != b.Search {
return false
}
2022-01-02 08:44:18 -03:00
return true
}