-
Notifications
You must be signed in to change notification settings - Fork 1
/
listener.go
107 lines (88 loc) · 2.12 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
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
package relayer
import (
"sync"
"github.com/nbd-wtf/go-nostr"
)
type Listener struct {
filters nostr.Filters
}
var listeners = make(map[*WebSocket]map[string]*Listener)
var listenersMutex = sync.Mutex{}
func GetListeningFilters() nostr.Filters {
var respfilters = make(nostr.Filters, 0, len(listeners)*2)
listenersMutex.Lock()
defer func() {
listenersMutex.Unlock()
}()
// here we go through all the existing listeners
for _, connlisteners := range listeners {
for _, listener := range connlisteners {
for _, listenerfilter := range listener.filters {
for _, respfilter := range respfilters {
// check if this filter specifically is already added to respfilters
if nostr.FilterEqual(listenerfilter, respfilter) {
goto nextconn
}
}
// field not yet present on respfilters, add it
respfilters = append(respfilters, listenerfilter)
// continue to the next filter
nextconn:
continue
}
}
}
// respfilters will be a slice with all the distinct filter we currently have active
return respfilters
}
func setListener(id string, ws *WebSocket, filters nostr.Filters) {
listenersMutex.Lock()
defer func() {
listenersMutex.Unlock()
}()
subs, ok := listeners[ws]
if !ok {
subs = make(map[string]*Listener)
listeners[ws] = subs
}
subs[id] = &Listener{
filters: filters,
}
}
// Remove a specific subscription id from listeners for a given ws client
func removeListenerId(ws *WebSocket, id string) {
listenersMutex.Lock()
defer func() {
listenersMutex.Unlock()
}()
subs, ok := listeners[ws]
if ok {
delete(listeners[ws], id)
if len(subs) == 0 {
delete(listeners, ws)
}
}
}
// Remove WebSocket conn from listeners
func removeListener(ws *WebSocket) {
listenersMutex.Lock()
defer listenersMutex.Unlock()
_, ok := listeners[ws]
if ok {
delete(listeners, ws)
}
}
func notifyListeners(event *nostr.Event) {
listenersMutex.Lock()
defer func() {
listenersMutex.Unlock()
}()
for ws, subs := range listeners {
for id, listener := range subs {
if !listener.filters.Match(event) {
continue
}
ws.WriteJSON([]interface{}{"EVENT", id, event})
}
}
}