Skip to content

Commit

Permalink
pointers from tags helpers.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed Feb 14, 2025
1 parent c37ed1a commit 6f5737a
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions pointers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package nostr

import (
"fmt"
"strconv"
"strings"
)

type Pointer interface {
Expand All @@ -15,6 +17,23 @@ type ProfilePointer struct {
Relays []string `json:"relays,omitempty"`
}

func ProfilePointerFromTag(refTag Tag) (ProfilePointer, error) {
pk := (refTag)[1]
if !IsValidPublicKey(pk) {
return ProfilePointer{}, fmt.Errorf("invalid pubkey '%s'", pk)
}

pointer := ProfilePointer{
PublicKey: pk,
}
if len(refTag) > 2 {
if relay := (refTag)[2]; IsValidRelayURL(relay) {
pointer.Relays = []string{relay}
}
}
return pointer, nil
}

func (ep ProfilePointer) MatchesEvent(_ Event) bool { return false }
func (ep ProfilePointer) AsTagReference() string { return ep.PublicKey }

Expand All @@ -32,6 +51,26 @@ type EventPointer struct {
Kind int `json:"kind,omitempty"`
}

func EventPointerFromTag(refTag Tag) (EventPointer, error) {
id := (refTag)[1]
if !IsValid32ByteHex(id) {
return EventPointer{}, fmt.Errorf("invalid id '%s'", id)
}

pointer := EventPointer{
ID: id,
}
if len(refTag) > 2 {
if relay := (refTag)[2]; IsValidRelayURL(relay) {
pointer.Relays = []string{relay}
}
if len(refTag) > 3 && IsValidPublicKey((refTag)[3]) {
pointer.Author = (refTag)[3]
}
}
return pointer, nil
}

func (ep EventPointer) MatchesEvent(evt Event) bool { return evt.ID == ep.ID }
func (ep EventPointer) AsTagReference() string { return ep.ID }

Expand All @@ -53,6 +92,34 @@ type EntityPointer struct {
Relays []string `json:"relays,omitempty"`
}

func EntityPointerFromTag(refTag Tag) (EntityPointer, error) {
spl := strings.SplitN(refTag[1], ":", 3)
if len(spl) != 3 {
return EntityPointer{}, fmt.Errorf("invalid addr ref '%s'", refTag[1])
}
if !IsValidPublicKey(spl[1]) {
return EntityPointer{}, fmt.Errorf("invalid addr pubkey '%s'", spl[1])
}

kind, err := strconv.Atoi(spl[0])
if err != nil || kind > (1<<16) {
return EntityPointer{}, fmt.Errorf("invalid addr kind '%s'", spl[0])
}

pointer := EntityPointer{
Kind: kind,
PublicKey: spl[1],
Identifier: spl[2],
}
if len(refTag) > 2 {
if relay := (refTag)[2]; IsValidRelayURL(relay) {
pointer.Relays = []string{relay}
}
}

return pointer, nil
}

func (ep EntityPointer) MatchesEvent(evt Event) bool {
return ep.PublicKey == evt.PubKey &&
ep.Kind == evt.Kind &&
Expand Down

0 comments on commit 6f5737a

Please sign in to comment.