Skip to content

Commit

Permalink
inbox-outbox relay barebones helpers on sdk package.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed Jul 8, 2023
1 parent 62e0068 commit 9b2b3b9
Showing 1 changed file with 107 additions and 0 deletions.
107 changes: 107 additions & 0 deletions sdk/relays.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package sdk

import (
"context"
"encoding/json"

"github.com/nbd-wtf/go-nostr"
)

type Relay struct {
URL string
Inbox bool
Outbox bool
}

func FetchRelaysForPubkey(ctx context.Context, pool *nostr.SimplePool, pubkey string, extraRelays ...string) []Relay {
ctx, cancel := context.WithCancel(ctx)
defer cancel()

relays := append(extraRelays,
"wss://nostr-pub.wellorder.net",
"wss://relay.damus.io",
"wss://nos.lol",
"wss://nostr.mom",
"wss://relay.nostr.bg",
)

ch := pool.SubManyEose(ctx, relays, nostr.Filters{
{
Kinds: []int{10002, 3},
Authors: []string{pubkey},
Limit: 2,
},
})

result := make([]Relay, 0, 20)
i := 0
for event := range ch {
switch event.Kind {
case 10002:
result = append(result, ParseRelaysFromKind10002(event)...)
case 3:
result = append(result, ParseRelaysFromKind3(event)...)
}

i++
if i >= 2 {
break
}
}

return result
}

func ParseRelaysFromKind10002(evt *nostr.Event) []Relay {
result := make([]Relay, 0, len(evt.Tags))
for _, tag := range evt.Tags {
if u := tag.Value(); u != "" && tag[0] == "r" {
relay := Relay{
URL: u,
}

if len(tag) == 2 {
relay.Inbox = true
relay.Outbox = true
} else if tag[2] == "write" {
relay.Outbox = true
} else if tag[2] == "read" {
relay.Inbox = true
}

result = append(result, relay)
}
}

return result
}

func ParseRelaysFromKind3(evt *nostr.Event) []Relay {
type Item struct {
Read bool `json:"read"`
Write bool `json:"write"`
}

items := make(map[string]Item, 20)
json.Unmarshal([]byte(evt.Content), &items)

results := make([]Relay, len(items))
i := 0
for u, item := range items {
relay := Relay{
URL: u,
}

if item.Read {
relay.Inbox = true
}
if item.Write {
relay.Outbox = true
}

results = append(results, relay)
i++
}

return results
}

0 comments on commit 9b2b3b9

Please sign in to comment.