-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
303 lines (267 loc) · 7.92 KB
/
utils.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package main
import (
"encoding/gob"
"encoding/json"
"expvar"
"fmt"
"os"
"os/signal"
"regexp"
"runtime"
"strings"
"syscall"
"time"
lru "github.com/hashicorp/golang-lru"
log "gopkg.in/inconshreveable/log15.v2"
)
var (
//Pulling all regex here *should* make it all compile once and then be left alone
//Stuff pared from main.go
botCommandRegex = regexp.MustCompile(`[!&]([^=!&?[)][^!&?[)]+)\.\s|[!&]([^=!&?[)][^!&?[)]+)|\[\[(.*?)\]\]`)
singleQuotedWord = regexp.MustCompile(`^(?:"\w+"|'\w+')$`)
nonTextRegex = regexp.MustCompile(`^\W+$`)
wordEndingInBang = regexp.MustCompile(`!["'] |\n+`)
wordStartingWithBang = regexp.MustCompile(`\s+! *\S+`)
coinRegex = regexp.MustCompile(`^coin(?:\s+(\d+))?`)
diceRegex = regexp.MustCompile(`^(?:roll\s+)?(\d*)d(\d+)([+-]\d+)?`)
cardMetadataRegex = regexp.MustCompile(`(?i)^(?:rulings?|reminder|flavou?r) `)
gathererRulingRegex = regexp.MustCompile(`^(?:(?P<start_number>\d+) ?(?P<name>.+)|(?P<name2>.*?) ?(?P<end_number>\d+).*?|(?P<name3>.+))`)
seeRuleRegexp = regexp.MustCompile(`rule (\d+\.?\d*\w?)`)
noPunctuationRegex = regexp.MustCompile(`\W$`)
// Used in multiple functions.
ruleRegexpLiteral = `(\d+\.\d{1,3}[a-zA-Z]?)`
ruleRegexp = regexp.MustCompile(ruleRegexpLiteral)
ruleExampleRegexp = regexp.MustCompile(`(\d+) ` + ruleRegexpLiteral + `|` + ruleRegexpLiteral + ` (\d+)` + `|` + ruleRegexpLiteral)
greetingRegexp = regexp.MustCompile(`(?i)^h(ello|i) *[!.?]* *$`)
//Stuff pared from card.go
reminderRegexp = regexp.MustCompile(`\((.*?)\)`)
nonAlphaRegex = regexp.MustCompile(`\W+`)
emojiRegex = regexp.MustCompile(`{\d+}|{[A-Z]}|{\d/[A-Z]}|{[A-Z]/[A-Z]}`)
// Super rudimentary policy regex to parse e.g '4.8' into 4-8 for link generation
policyRegex = regexp.MustCompile(`[^0-9]+`)
// Metrics
totalLines = expvar.NewInt("bot_totalLines")
ircLines = expvar.NewInt("bot_ircLines")
slackLines = expvar.NewInt("bot_slackLines")
totalQueries = expvar.NewInt("bot_totalQueries")
ircQueries = expvar.NewInt("bot_ircQueries")
slackQueries = expvar.NewInt("bot_slackQueries")
cardsInCache = expvar.NewInt("bot_cardsInCache")
cardCacheQueries = expvar.NewInt("bot_cardCacheQueries")
cardCacheHits = expvar.NewInt("bot_cardCacheHits")
cardCacheHitPercentage = expvar.NewInt("bot_cardCacheHitPercentage")
cardUniquePrefixHits = expvar.NewInt("bot_cardUniquePrefixHits")
searchRequests = expvar.NewInt("bot_searchRequests")
randomRequests = expvar.NewInt("bot_randomRequests")
cardRequests = expvar.NewInt("bot_cardRequests")
dumbCardRequests = expvar.NewInt("bot_dumbCardRequests")
metadataRequests = expvar.NewInt("bot_metadataRequests")
reminderRequests = expvar.NewInt("bot_reminderRequests")
flavourRequests = expvar.NewInt("bot_flavourRequests")
rulingRequests = expvar.NewInt("bot_rulingRequests")
exampleRequests = expvar.NewInt("bot_exampleRequests")
rulesRequests = expvar.NewInt("bot_rulesRequests")
defineRequests = expvar.NewInt("bot_defineRequests")
hearthstoneRequests = expvar.NewInt("bot_hearthstoneRequests")
)
func sliceUniqMap(s []string) []string {
seen := make(map[string]struct{}, len(s))
j := 0
for _, v := range s {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
s[j] = v
j++
}
return s[:j]
}
func stringSliceContains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func removeEmptyStrings(s []string) []string {
var r []string
for _, str := range s {
if str != "" {
r = append(r, str)
}
}
return r
}
func wordWrap(text string, lineWidth int) string {
words := strings.Fields(strings.TrimSpace(text))
if len(words) == 0 {
return text
}
wrapped := words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += " [...]\n" + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return wrapped
}
func writeGob(filePath string, object interface{}) error {
file, err := os.Create(filePath)
if err == nil {
encoder := gob.NewEncoder(file)
err = encoder.Encode(object)
} else {
log.Warn("Error creating GOB file", "Error", err)
}
file.Close()
return err
}
func readGob(filePath string, object interface{}) error {
file, err := os.Open(filePath)
if err == nil {
decoder := gob.NewDecoder(file)
err = decoder.Decode(object)
// log.Debug("readGOB", "Object", object)
}
file.Close()
return err
}
func dumpCardCache(conf *configuration, cache *lru.ARCCache) error {
// Dump cache keys
log.Debug("Dumping card cache", "len", cache.Len())
cardsInCache.Set(int64(cache.Len()))
var outCards []Card
for _, k := range cache.Keys() {
if v, ok := cache.Peek(k); ok {
if v != nil {
if conf.DevMode {
log.Debug("Dumping card", "Key", k, "Name", (v.(Card)).Name)
}
outCards = append(outCards, v.(Card))
}
}
}
return writeGob(cardCacheGob, outCards)
}
func getExitChannel() chan os.Signal {
c := make(chan os.Signal, 1)
signal.Notify(c,
syscall.SIGTERM,
syscall.SIGINT,
syscall.SIGQUIT,
syscall.SIGHUP,
)
return c
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// A dumb function that returns the minimum of two ints
// with the restriction that the result will try to be bigger than
// a third given value.
func cappedMin(a, b, c int) int {
if a < b && a > c {
return a
}
if b < a && b > c {
return b
}
return max(a, b)
}
func readConfig() configuration {
file, _ := os.Open(configFile)
defer file.Close()
decoder := json.NewDecoder(file)
conf := configuration{}
err := decoder.Decode(&conf)
if err != nil {
panic(err)
}
log.Debug("Conf", "Parsed as", conf)
return conf
}
func dumpCardCacheTimer(conf *configuration, cache *lru.ARCCache) {
for {
// Override for Dev
if conf.DevMode {
log.Debug("Dumping cache, sleeping (short)")
time.Sleep(30 * time.Second)
} else {
log.Debug("Dumping cache, sleeping (long)")
time.Sleep(cacheDumpTimer)
}
if err := dumpCardCache(conf, cache); err != nil {
log.Warn("Dump card cache timer", "Error", err)
}
}
}
func reduceCardSentence(tokens []string) []string {
log.Debug("In ReduceCard -- Tokens were", "Tokens", tokens, "Length", len(tokens))
var ret []string
for i := len(tokens); i >= 1; i-- {
msg := strings.Join(tokens[0:i], " ")
msg = noPunctuationRegex.ReplaceAllString(msg, "")
// Eliminate short names which are not valid and would match too much
if len(msg) > 2 {
log.Debug("Reverse descent", "i", i, "msg", msg)
ret = append(ret, msg)
}
}
return ret
}
func deleteItemFromCache(key string) error {
if nameToCardCache.Contains(key) {
nameToCardCache.Remove(key)
return nil
}
return fmt.Errorf("Key not found")
}
func formatMessageForIRC(input string) string {
input = strings.Replace(input, "<b>", "\x02", -1)
input = strings.Replace(input, "</b>", "\x0F", -1)
input = strings.Replace(input, "<i>", "\x1D", -1)
input = strings.Replace(input, "</i>", "\x0F", -1)
return input
}
func formatMessageForSlack(input string) string {
input = strings.Replace(input, "<b>", "*", -1)
input = strings.Replace(input, "</b>", "*", -1)
input = strings.Replace(input, "<i>", "_", -1)
input = strings.Replace(input, "</i>", "_", -1)
return input
}
func goRoutines() interface{} {
return runtime.NumGoroutine()
}
func handleICC(cardTokens []string) string {
return fmt.Sprintf("%cce %crown %citadel", strings.ToUpper(cardTokens[0])[0], strings.ToUpper(cardTokens[1])[0], strings.ToUpper(cardTokens[2])[0])
}
// Null Coalescing Operator
func nco(a string, b string) string {
if a != "" {
return a
}
return b
}
func mergeIntStringMaps(new map[int]string, existing map[int]string) map[int]string {
for k, v := range new {
existing[k] = v
}
return existing
}