-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
194 lines (173 loc) · 4.41 KB
/
config.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"go.uber.org/zap"
)
const (
configFileName = "twitch-integration.json"
)
type chatCommand struct {
Actions []string `json:"actions"`
CooldownSec int32 `json:"cooldown_sec"`
Message string `json:"message"`
}
type config struct {
Debug bool `json:"debug"`
Twitch twitch `json:"twitch"`
StreamElements streamElements `json:"streamElements"`
}
type twitch struct {
Rewards map[string][]string `json:"rewards"`
Bits map[int][]string `json:"bits"`
Chat map[string]chatCommand `json:"chat"`
}
type streamElements struct {
Perks map[string][]string `json:"perks"`
}
func defaultConfig() config {
return config{
Debug: false,
StreamElements: streamElements{
Perks: map[string][]string{
"Item1": {"TWI_XXX", "TWI_YYY"},
},
},
Twitch: twitch{
Rewards: map[string][]string{
"Item1": {"TWI_XXX", "TWI_YYY"},
},
Chat: map[string]chatCommand{
"#help": {
Actions: []string{"XXXXXXXXXXXXXXXXXXXX"},
Message: "Dies hier wird im Chat angezeigt",
CooldownSec: 5,
},
},
Bits: map[int][]string{
50: {"TWI_XXX", "TWI_YYY"},
100: {"TWI_XXX", "TWI_YYY"},
},
},
}
}
func allKeysToUpper(m map[string][]string) map[string][]string {
copy := make(map[string][]string, len(m))
for k, v := range m {
copy[strings.ToUpper(k)] = v
}
return copy
}
func prettyJson(data any) ([]byte, error) {
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
err := enc.Encode(data)
return buf.Bytes(), err
}
func getConfigPath() (string, error) {
execPath, err := os.Executable()
if err != nil {
app.logger.Error("failed to locate current executable", zap.Error(err))
return "", err
}
return filepath.Join(filepath.Dir(execPath), configFileName), nil
}
func readConfigJson() (config, error) {
cnf := defaultConfig()
configPath, err := getConfigPath()
if err != nil {
app.logger.Error("failed to locate the config file", zap.Error(err))
return cnf, err
}
configContent, err := os.ReadFile(configPath)
if err != nil {
if os.IsNotExist(err) {
def, err := prettyJson(cnf)
if err != nil {
app.logger.Error("failed to marshal default config", zap.Error(err))
return cnf, err
}
os.WriteFile(configPath, def, 0640)
}
} else {
if err := json.Unmarshal(configContent, &cnf); err != nil {
app.logger.Error("failed to unmarshal config", zap.Error(err))
return cnf, err
}
}
if cnf.Twitch.Rewards == nil {
cnf.Twitch.Rewards = make(map[string][]string)
}
if cnf.StreamElements.Perks == nil {
cnf.StreamElements.Perks = make(map[string][]string)
}
cnf.Twitch.Rewards = allKeysToUpper(cnf.Twitch.Rewards)
cnf.StreamElements.Perks = allKeysToUpper(cnf.StreamElements.Perks)
if cnf.Twitch.Chat == nil {
cnf.Twitch.Chat = make(map[string]chatCommand)
}
return cnf, nil
}
func watchForConfigChanges(ctx context.Context, watcher *fsnotify.Watcher, logger *zap.Logger) {
execPath, err := os.Executable()
if err != nil {
logger.Error("failed to locate current executable", zap.Error(err))
return
}
configDir := filepath.Dir(execPath)
if err := watcher.Add(configDir); err != nil {
logger.Error("failed to watch for config changes", zap.Error(err))
return
}
// creates an encapsulated function that cancels any previous call to it
fnTriggerReload, cancel := func() (func(), func()) {
mtx := &sync.Mutex{}
reloadCtx, cancel := context.WithCancel(ctx)
return func() {
mtx.Lock()
cancel()
reloadCtx, cancel = context.WithCancel(ctx)
currentCtx := reloadCtx
mtx.Unlock()
select {
case <-currentCtx.Done():
return
case <-time.After(time.Second):
logger.Info("config file changed, reloading")
if err := loadConfig(); err != nil {
logger.Warn("reading the configuration yieled an error", zap.Error(err))
}
}
}, func() { cancel() }
}()
go func() {
defer cancel()
for {
select {
case <-ctx.Done():
return
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Has(fsnotify.Write) && strings.EqualFold(filepath.Base(event.Name), configFileName) {
go fnTriggerReload()
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
logger.Warn("fsnotify received an error", zap.Error(err))
}
}
}()
}