-
Notifications
You must be signed in to change notification settings - Fork 113
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
inbox-outbox relay barebones helpers on sdk package.
- Loading branch information
Showing
1 changed file
with
107 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |