-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
101 lines (87 loc) · 2.37 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
package backend
import (
"context"
"errors"
"io"
"net/http"
"strings"
"sync"
"github.com/vennekilde/gw2-alliance-bot/internal/api"
"go.uber.org/zap"
)
const PlatformID = 2
const (
SettingWvWWorld = "wvw_world"
SettingPrimaryRole = "wvw_primary_role"
SettingLinkedRole = "wvw_linked_role"
SettingAssociatedRoles = "wvw_associated_roles"
SettingAccRepEnabled = "acc_rep_nick"
SettingGuildTagRepEnabled = "guild_tag_rep_nick"
SettingEnforceGuildRep = "enforce_guild_rep"
SettingGuildCommonRole = "verification_role"
)
type Service struct {
m sync.Mutex
backend *api.ClientWithResponses
settings map[string]map[string]string
serviceUUID string
}
func NewService(backend *api.ClientWithResponses, serviceUUID string) *Service {
return &Service{
backend: backend,
serviceUUID: serviceUUID,
settings: make(map[string]map[string]string),
}
}
func (s *Service) Synchronize() error {
// settings
ctx := context.Background()
resp, err := s.backend.GetServicePropertiesWithResponse(ctx, s.serviceUUID)
if err != nil {
return err
} else if resp.JSON200 == nil {
zap.L().Error("unexpected response", zap.Any("response", resp))
return errors.New("unexpected response")
}
settings := make(map[string]map[string]string)
for _, property := range *resp.JSON200 {
subject := *property.Subject
subjectSettings, ok := settings[subject]
if !ok {
subjectSettings = make(map[string]string)
settings[subject] = subjectSettings
}
subjectSettings[property.Name] = property.Value
}
s.m.Lock()
defer s.m.Unlock()
s.settings = settings
return nil
}
func (s *Service) GetSetting(subject string, name string) string {
s.m.Lock()
defer s.m.Unlock()
subjectSettings, ok := s.settings[subject]
if !ok {
return ""
}
return subjectSettings[name]
}
func (s *Service) SetSetting(ctx context.Context, subject string, name string, value string) error {
s.m.Lock()
defer s.m.Unlock()
_, err := s.backend.PutServiceSubjectPropertyWithResponse(ctx, s.serviceUUID, subject, name, func(ctx context.Context, req *http.Request) error {
req.Body = io.NopCloser(strings.NewReader(value))
return nil
})
if err != nil {
return err
}
subjectSettings, ok := s.settings[subject]
if !ok {
subjectSettings = make(map[string]string)
s.settings[subject] = subjectSettings
}
subjectSettings[name] = value
return nil
}