tags.mx raw
1 // Package nostr implements core Nostr protocol types.
2 package nostr
3
4 // Tag is a single tag: ["e", "abc123", "wss://relay"] etc.
5 type Tag []string
6
7 // Tags is a list of tags.
8 type Tags []Tag
9
10 // Key returns the tag key (first element), or empty string.
11 func (t Tag) Key() string {
12 if len(t) > 0 {
13 return t[0]
14 }
15 return ""
16 }
17
18 // Value returns the tag value (second element), or empty string.
19 func (t Tag) Value() string {
20 if len(t) > 1 {
21 return t[1]
22 }
23 return ""
24 }
25
26 // Relay returns the third element (relay hint), or empty string.
27 func (t Tag) Relay() string {
28 if len(t) > 2 {
29 return t[2]
30 }
31 return ""
32 }
33
34 // Marker returns the fourth element (e-tag marker), or empty string.
35 func (t Tag) Marker() string {
36 if len(t) > 3 {
37 return t[3]
38 }
39 return ""
40 }
41
42 // GetFirst returns the first tag matching key, or nil.
43 func (ts Tags) GetFirst(key string) Tag {
44 for _, t := range ts {
45 if len(t) > 0 && t[0] == key {
46 return t
47 }
48 }
49 return nil
50 }
51
52 // GetAll returns all tags matching key.
53 func (ts Tags) GetAll(key string) Tags {
54 var out Tags
55 for _, t := range ts {
56 if len(t) > 0 && t[0] == key {
57 out = append(out, t)
58 }
59 }
60 return out
61 }
62
63 // GetD returns the "d" tag value (for replaceable events).
64 func (ts Tags) GetD() string {
65 t := ts.GetFirst("d")
66 if t != nil {
67 return t.Value()
68 }
69 return ""
70 }
71
72 // ContainsValue checks if any tag with the given key has the given value.
73 func (ts Tags) ContainsValue(key, value string) bool {
74 for _, t := range ts {
75 if len(t) > 1 && t[0] == key && t[1] == value {
76 return true
77 }
78 }
79 return false
80 }
81