-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
111 lines (98 loc) · 2.29 KB
/
service.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package oniontree
import (
"github.com/oniontree-org/go-oniontree/validator"
"github.com/oniontree-org/go-oniontree/validator/jsonschema"
"regexp"
"strings"
)
type serviceID string
func (i serviceID) String() string {
return string(i)
}
func (i serviceID) Validate() error {
pattern := `^[a-z0-9\-]+$`
matched, err := regexp.MatchString(pattern, string(i))
if err != nil {
return err
}
if !matched {
return &ErrInvalidID{string(i), pattern}
}
return nil
}
type Service struct {
Name string `json:"name" yaml:"name"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
URLs []string `json:"urls" yaml:"urls"`
PublicKeys PublicKeys `json:"public_keys,omitempty" yaml:"public_keys,omitempty"`
id serviceID
validator *validator.Validator
}
func (s *Service) ID() string {
return string(s.id)
}
func (s *Service) SetURLs(urls []string) int {
s.URLs = []string{}
return s.AddURLs(urls)
}
func (s *Service) AddURLs(urls []string) int {
urlExists := func(url string) bool {
for idx, _ := range s.URLs {
if s.URLs[idx] == url {
return true
}
}
return false
}
added := 0
for _, url := range urls {
url = strings.TrimSpace(url)
if urlExists(url) {
continue
}
s.URLs = append(s.URLs, url)
added++
}
return added
}
func (s *Service) SetPublicKeys(publicKeys []*PublicKey) int {
s.PublicKeys = []*PublicKey{}
return s.AddPublicKeys(publicKeys)
}
func (s *Service) AddPublicKeys(publicKeys []*PublicKey) int {
publicKeyExists := func(publicKey *PublicKey) bool {
for idx, _ := range s.PublicKeys {
if s.PublicKeys[idx].Fingerprint == "" && s.PublicKeys[idx].ID == "" {
continue
}
if s.PublicKeys[idx].Fingerprint == publicKey.Fingerprint || s.PublicKeys[idx].ID == publicKey.ID {
return true
}
}
return false
}
added := 0
for _, publicKey := range publicKeys {
if publicKeyExists(publicKey) {
continue
}
s.PublicKeys = append(s.PublicKeys, publicKey)
added++
}
return added
}
func (s *Service) Validate() error {
if err := s.id.Validate(); err != nil {
return err
}
if s.validator != nil {
return s.validator.Validate(s)
}
return nil
}
func NewService(id string) *Service {
return &Service{
id: serviceID(id),
validator: validator.NewValidator(jsonschema.V0),
}
}