-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlistener.go
66 lines (53 loc) · 1.06 KB
/
listener.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
package main
import (
"sync"
"github.com/fiatjaf/go-nostr/event"
"github.com/fiatjaf/go-nostr/filter"
"github.com/gorilla/websocket"
)
type Listener struct {
ws *websocket.Conn
filters []*filter.EventFilter
}
var listeners = make(map[string]*Listener)
var listenersMutex = sync.Mutex{}
func setListener(id string, conn *websocket.Conn, filters []*filter.EventFilter) {
listenersMutex.Lock()
defer func() {
listenersMutex.Unlock()
}()
listeners[id] = &Listener{
ws: conn,
filters: filters,
}
}
func removeListener(id string) {
listenersMutex.Lock()
defer func() {
listenersMutex.Unlock()
}()
delete(listeners, id)
}
func notifyListeners(event *event.Event) {
listenersMutex.Lock()
defer func() {
listenersMutex.Unlock()
}()
for id, listener := range listeners {
match := false
for _, filter := range listener.filters {
if filter == nil {
match = false
break
}
if filter.Matches(event) {
match = true
break
}
}
if !match {
continue
}
listener.ws.WriteJSON([]interface{}{"EVENT", id, event})
}
}