go-nostr/subscription.go

62 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-01-02 08:44:18 -03:00
package nostr
2021-02-20 17:44:05 -03:00
import (
2023-01-01 20:22:40 -03:00
"context"
"sync"
)
2021-02-20 17:44:05 -03:00
type Subscription struct {
id string
conn *Connection
mutex sync.Mutex
2021-02-20 17:44:05 -03:00
Relay *Relay
Filters Filters
2023-01-26 09:04:27 -03:00
Events chan *Event
EndOfStoredEvents chan struct{}
stopped bool
emitEose sync.Once
}
type EventMessage struct {
2022-01-02 08:44:18 -03:00
Event Event
Relay string
2021-02-20 17:44:05 -03:00
}
// Unsub closes the subscription, sending "CLOSE" to relay as in NIP-01.
// Unsub() also closes the channel sub.Events.
func (sub *Subscription) Unsub() {
sub.mutex.Lock()
defer sub.mutex.Unlock()
2021-02-20 17:44:05 -03:00
sub.conn.WriteJSON([]interface{}{"CLOSE", sub.id})
if sub.stopped == false && sub.Events != nil {
close(sub.Events)
2021-02-20 17:44:05 -03:00
}
sub.stopped = true
2021-02-20 17:44:05 -03:00
}
// Sub sets sub.Filters and then calls sub.Fire(ctx).
2023-01-01 20:22:40 -03:00
func (sub *Subscription) Sub(ctx context.Context, filters Filters) {
sub.Filters = filters
2023-01-01 20:22:40 -03:00
sub.Fire(ctx)
}
// Fire sends the "REQ" command to the relay.
// When ctx is cancelled, sub.Unsub() is called, closing the subscription.
2023-01-01 20:22:40 -03:00
func (sub *Subscription) Fire(ctx context.Context) {
message := []interface{}{"REQ", sub.id}
for _, filter := range sub.Filters {
message = append(message, filter)
}
sub.conn.WriteJSON(message)
2023-01-01 20:22:40 -03:00
// the subscription ends once the context is canceled
go func() {
<-ctx.Done()
sub.Unsub()
}()
2021-02-20 17:44:05 -03:00
}