-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblastr.go
104 lines (86 loc) · 1.98 KB
/
blastr.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
package blastr
import (
"context"
"fmt"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
)
func New(nsec string, opts ...Option) (*Blastr, error) {
options := defaultOptions()
for _, opt := range opts {
opt(options)
}
var npub, pubkey, privateKey string
{
_, sk, err := nip19.Decode(nsec)
if err != nil {
return nil, fmt.Errorf("nip19 decode: %w", err)
}
privateKey = sk.(string)
pk, err := nostr.GetPublicKey(privateKey)
if err != nil {
return nil, fmt.Errorf("get pubkey: %w", err)
}
pubkey = pk
_npub, err := nip19.EncodePublicKey(pubkey)
if err != nil {
return nil, fmt.Errorf("encode pubkey: %w", err)
}
npub = _npub
}
return &Blastr{
opts: options,
npub: npub,
pubkey: pubkey,
privateKey: privateKey,
}, nil
}
type Blastr struct {
opts *Options
npub, pubkey, privateKey string
}
func (b *Blastr) SendText(ctx context.Context, content string) error {
event := b.newEvent(content)
return b.connectAndSend(ctx, event)
}
func (b *Blastr) Send(ctx context.Context, event nostr.Event) error {
event.PubKey = b.pubkey
event.CreatedAt = nostr.Now()
event.Sign(b.privateKey)
return b.connectAndSend(ctx, event)
}
func (b *Blastr) newEvent(content string) nostr.Event {
event := nostr.Event{
PubKey: b.pubkey,
CreatedAt: nostr.Now(),
Kind: nostr.KindTextNote,
Tags: nil,
Content: content,
}
event.Sign(b.privateKey)
return event
}
func (b *Blastr) connectAndSend(ctx context.Context, event nostr.Event) error {
for _, url := range b.opts.relayURLs {
relay, err := nostr.RelayConnect(ctx, url)
if err != nil {
err = fmt.Errorf("connect %v: %w", url, err)
if b.opts.strictErrors {
return err
}
fmt.Println(err)
continue
}
defer relay.Close()
_, err = relay.Publish(ctx, event)
if err != nil {
err = fmt.Errorf("publish %v: %w", url, err)
if b.opts.strictErrors {
return err
}
fmt.Println(err)
continue
}
}
return nil
}