summaryrefslogtreecommitdiffstats
path: root/tags.go
blob: 4fe3d048060707e390bf20eb165e307f9fb99b60 (plain)
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
package nostr

// Tag represents a single Nostr tag, which is an array of strings.
// The first element is the tag key, followed by its values.
type Tag []string

// Key returns the tag key (first element), or empty string if tag is empty.
func (t Tag) Key() string {
	if len(t) == 0 {
		return ""
	}
	return t[0]
}

// Value returns the first value (second element), or empty string if not present.
func (t Tag) Value() string {
	if len(t) < 2 {
		return ""
	}
	return t[1]
}

// Tags represents a collection of tags.
type Tags []Tag

// Find returns the first tag matching the given key, or nil if not found.
func (tags Tags) Find(key string) Tag {
	for _, tag := range tags {
		if tag.Key() == key {
			return tag
		}
	}
	return nil
}

// FindAll returns all tags matching the given key.
func (tags Tags) FindAll(key string) Tags {
	var result Tags
	for _, tag := range tags {
		if tag.Key() == key {
			result = append(result, tag)
		}
	}
	return result
}

// GetD returns the value of the "d" tag, used for addressable events.
func (tags Tags) GetD() string {
	tag := tags.Find("d")
	if tag == nil {
		return ""
	}
	return tag.Value()
}

// ContainsValue checks if any tag with the given key contains the specified value.
func (tags Tags) ContainsValue(key, value string) bool {
	for _, tag := range tags {
		if tag.Key() == key && tag.Value() == value {
			return true
		}
	}
	return false
}