/
chastikey.go
529 lines (451 loc) · 12.9 KB
/
chastikey.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package main
import (
"bytes"
"encoding/json"
"fmt"
alexa "github.com/mikeflynn/go-alexa/skillserver"
"github.com/tkanos/gonfig"
"io/ioutil"
"log"
"net/http"
"os"
"runtime"
"sort"
"strconv"
"strings"
"time"
)
// Information we read from the config file
type Configuration struct {
SkillID string
ApiID string
ApiSecret string
UserName string
}
// Global variables based on that config
var configuration Configuration
// This may be set each for each request if the http request includes a name
var UserName string
// These are the fields from the Chastikey API I care about
type Lock struct {
LockID int64 `json:"lockID"`
LockName string `json:"lockName"`
LockedBy string `json:"lockedBy"`
LockFrozen int64 `json:"lockFrozen"`
FrozenByCard int64 `json:"lockFrozenByCard"`
StartTime int64 `json:"timestampLocked"`
UnlockTime int64 `json:"timestampUnlocked"`
LastPicked int64 `json:"timestampLastPicked"`
RealLast int64 `json:"timestampRealLastPicked"`
NextPicked int64 `json:"timestampNextPick"`
CardFrozTime int64 `json:"timestampFrozenByCard"`
HoldFrozTime int64 `json:"timestampFrozenByKeyholder"`
DecisionTime int64 `json:"timestampRequestedKeyholdersDecision"`
Regularity float64 `json:"regularity"`
Status string `json:"status"`
Combination string `json:"combination"`
// Card information
CardHidden int `json:"cardInfoHidden"`
DoubleCards int `json:"doubleUpCards"`
FreezeCards int `json:"freezeCards"`
GreenCards int `json:"greenCards"`
GreenPicked int `json:"greenCardsPicked"`
RedCards int `json:"redCards"`
ResetCards int `json:"resetCards"`
StickyCards int `json:"stickyCards"`
YellowCards int `json:"yellowCards"`
Fixed int `json:"fixed"`
Expected int64 `json:"timestampExpectedUnlock"`
}
type Chastikey struct {
Locks []Lock `json:"locks"`
}
// Where do config files live?
func UserHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home + "\\"
}
return os.Getenv("HOME") + "/"
}
func plural(val int, name string) string {
res := strconv.Itoa(val) + " " + name
if val != 1 {
res += "s"
}
return res
}
func optional(val int, name string) string {
if val != 0 {
return plural(val, name) + ", "
} else {
return ""
}
}
func time_to_days(val int64) string {
var res string
// If the requested time is over an hour, strip off the seconds
if val >= 3600 {
val = 60 * int64(val/60)
}
days := int64(val / 86400)
if days > 0 {
res += plural(int(days), "day") + " "
val -= days * 86400
}
hours := int64(val / 3600)
if hours > 0 {
res += plural(int(hours), "hour") + " "
val -= hours * 3600
}
mins := int64(val / 60)
if mins > 0 {
res += plural(int(mins), "minute") + " "
val -= mins * 60
}
if val > 0 {
res += plural(int(val), "second")
}
return strings.TrimSpace(res)
}
func do_talk_to_chastikey(cmd string) (string, string) {
if os.Getenv("DEBUG") != "" {
return os.Getenv("DEBUG"), ""
}
url := "https://api.chastikey.com/v0.5/" + cmd
fmt.Println("Calling " + cmd)
req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte("DiscordID="+UserName)))
if err != nil {
return "", "Problems setting up the API: " + err.Error()
}
req.Header.Set("ClientID", configuration.ApiID)
req.Header.Set("ClientSecret", configuration.ApiSecret)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", "Problems calling the API: " + err.Error()
}
// What a hassle, just to get the string
// http://dlintw.github.io/gobyexample/public/http-client.html
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err.Error()
}
res := string(body)
if resp.StatusCode != 200 {
fmt.Println("Bad result: " + res)
return "", "Error from API: " + resp.Status
}
return res, ""
}
func talk_to_chastikey(cmd string) ([]Lock, string) {
var chastikey Chastikey
json_str, http_err := do_talk_to_chastikey(cmd)
if http_err != "" {
return nil, http_err
}
err := json.Unmarshal([]byte(json_str), &chastikey)
if err != nil {
return nil, "Could not understand API results: " + err.Error()
}
// We want to look at the Locks
locks := chastikey.Locks
// Let's make sure the locks are in LockID order. They
// probably are, anyway, but let's not make assumptions :-)
// This will try to maintain consistency across calls.
sort.Slice(locks, func(i, j int) bool {
return locks[i].LockID < locks[j].LockID
})
return locks, ""
}
func one_lock(x int, y Lock) string {
res := ""
now := time.Now().Unix()
dur := now - y.StartTime
if y.UnlockTime != 0 {
dur = y.UnlockTime - y.StartTime
}
// Normally RealLast should hold the last time a card was picked
// but some versions of the app have a bug. So we take the
// maximum of LastPicked and RealLast
if y.RealLast > y.LastPicked {
y.LastPicked = y.RealLast
}
// If people are on an older version of the app the LastPicked
// won't be populated, so set it to now
if y.LastPicked == 0 {
y.LastPicked = now
}
pick := now - y.LastPicked
next := y.NextPicked - now
res += "Lock " + strconv.Itoa(x)
if y.LockName != "" {
res += ", named " + y.LockName + ","
}
if y.LockedBy == "" {
res += " is a self-lock, and "
} else {
res += " is held by " + y.LockedBy + ", and "
}
if y.UnlockTime != 0 {
res += "ran"
} else {
res += "has been running"
}
res += " for " + time_to_days(dur) + ". "
if y.Regularity != 0 {
res += "Cards can be picked every " + time_to_days(int64(3600*y.Regularity)) + ". "
}
if y.Status == "ReadyToUnlock" {
res += "This lock can be unlocked. "
} else if y.Status == "AwaitingKeyholdersDecision" {
res += "This lock has been waiting for keyholder decision for " + time_to_days(now-y.DecisionTime) + ". "
} else if y.Combination == "" {
if y.Fixed == 0 {
if pick != 0 {
res += "The last card was picked " + time_to_days(pick) + " ago. "
}
if y.LockFrozen == 0 {
res += "The next card can be picked "
if next <= 0 {
res += "now"
} else {
res += "in " + time_to_days(next)
}
res += ". "
}
} else {
res += "This is a fixed lock. "
dur := y.Expected - time.Now().Unix()
if dur < 0 {
res += "This lock is ready to unlock"
} else {
res += "This lock is expected to finish in " + time_to_days(dur)
}
}
if y.LockFrozen != 0 {
var froztime int64
res += "This lock has been frozen by "
if y.FrozenByCard != 0 {
res += "card draw"
froztime = y.CardFrozTime
} else {
res += "key holder"
froztime = y.HoldFrozTime
}
res += " for " + time_to_days(now-froztime) + ". "
}
} else {
res += "This lock can be opened; the combination is"
for _, c := range y.Combination {
res += ", " + string(c)
}
res += ". "
if y.Status == "UnlockedFake" {
res += "This was a fake lock. "
}
}
return res + "\n"
}
// Ask Chastikey for the user status and generate a friendly response
func do_status() string {
locks, err := talk_to_chastikey("lockeedata.php")
if err != "" {
return err
}
cnt := len(locks)
res := "You have " + plural(cnt, "lock") + ".\n"
for x, y := range locks {
res += one_lock(x+1, y)
}
return res
}
func report_lock(id int, lock Lock) string {
res := one_lock(id, lock)
if lock.Combination == "" {
if lock.CardHidden != 0 {
res += "Card info is hidden"
} else {
if lock.Fixed == 0 {
res += "You have picked " + plural(lock.GreenPicked, "green card")
res += ". There are " + plural(lock.GreenCards, "green card") + ", "
res += optional(lock.RedCards, "red card")
res += optional(lock.StickyCards, "sticky card")
res += optional(lock.YellowCards, "yellow card")
res += optional(lock.FreezeCards, "freeze card")
res += optional(lock.DoubleCards, "double card")
res += optional(lock.ResetCards, "reset card")
res = strings.TrimSuffix(res, ", ")
res += " remaining."
}
}
}
return res
}
func lock_summary(locks []Lock) string {
res := "You have the following locks. "
for x, y := range locks {
res += "Lock " + strconv.Itoa(x+1)
if y.LockName != "" {
res += ", named " + y.LockName + ","
}
res += " is held by " + y.LockedBy + ". "
}
return res
}
func list_locks() string {
locks, errstr := talk_to_chastikey("lockeedata.php")
if errstr != "" {
return errstr
}
return lock_summary(locks)
}
// This is meant to search the locks by name, and return the matching
// lock. However Amazon Alexa voice training means that things like "collar"
// get matched as "color" and this really doesn't work well. So this code
// is currently unused.
func get_lock_by_name(arg []string) string {
if len(arg) != 1 {
return "You need to specify one number"
}
locks, errstr := talk_to_chastikey("lockeedata.php")
if errstr != "" {
return errstr
}
lockid := -1
srch := strings.ToLower(arg[0])
for x, y := range locks {
if strings.ToLower(y.LockName) == srch {
lockid = x
}
}
if lockid == -1 {
return "I could not find a lock with that name. " + lock_summary(locks)
}
return report_lock(lockid+1, locks[lockid])
}
func get_lock_by_id(arg []string) string {
if len(arg) != 1 {
return "You need to specify one number"
}
id, err := strconv.Atoi(arg[0])
// Ideally we'd try to find this by name, but that doesn't work
// (see comments on get_lock_by_name definition) so we just
// return an error message
if err != nil {
// return get_lock_by_name(arg)
return "The value you specified wasn't understandable as a number"
}
locks, errstr := talk_to_chastikey("lockeedata.php")
if errstr != "" {
return errstr
}
cnt := len(locks)
if id < 1 || id > cnt {
return "You need to pick a number between 1 and " + strconv.Itoa(cnt)
}
return report_lock(id, locks[id-1])
}
func get_help() string {
return "Commands I understand are: " +
"Ask chasty key for status. " +
"Ask chasty key about lock 1. " +
"Ask chasty key to list locks."
}
// Validate the command passed
func parse_command(cmd string, args []string) string {
if cmd == "status" {
return do_status()
} else if cmd == "lockid" {
return get_lock_by_id(args)
} else if cmd == "listlocks" {
return list_locks()
} else if cmd == "AMAZON.HelpIntent" {
return get_help()
} else if strings.HasPrefix(cmd, "AMAZON") {
return ""
} else {
return "I don't know how to " + cmd
}
}
// Handle the Alexa query
func EchoIntentHandler(echoReq *alexa.EchoRequest, echoResp *alexa.EchoResponse) {
var response string
// This is a kludge to allow for multiple users to be used.
// If the incoming request has a chastikey username in the userId
// field then we'll use that. Otherwise fall back to the username
// in the config file
// This only works in dev mode ("?_dev=1") because otherwise the
// signature is broken. dev mode also skips the application ID
// check.
// So this isn't really good, but it means other people can program
// their alexa devices to call my hosted instance without needing
// to run their own server.
UserName = echoReq.GetUserID()
if strings.HasPrefix(UserName, "amzn1.ask.account.") {
UserName = configuration.UserName
}
log.Println("Using username " + UserName)
fn := echoReq.GetIntentName()
log.Println("Got Alexa event " + fn)
// We need to build an argument array. This can be simple; we
// only expect to have a single arguement, so lets iterate over
// the slots and just add them
var args []string
for slot, _ := range echoReq.AllSlots() {
value, _ := echoReq.GetSlotValue(slot)
// log.Printf(" with slot = %v\n", slot)
// log.Printf(" value = %v\n", value)
args = append(args, value)
}
response = parse_command(fn, args)
log.Println("Got response " + response)
echoResp.OutputSpeech(response)
}
// Start the Alexa server
func start_server(amazon_skill_id string) {
Applications := map[string]interface{}{
"/echo/chastikey": alexa.EchoApplication{ // Route
AppID: amazon_skill_id,
OnIntent: EchoIntentHandler,
},
}
alexa.Run(Applications, "3001")
fmt.Println("Server started")
}
func main() {
Args := os.Args
// If no paramter is passed, default to "server"
// otherwise split command line args
var cmd string = "server"
if len(Args) > 1 {
cmd = Args[1]
Args = Args[2:]
}
// Try and find the config file
config_file := UserHomeDir() + ".chastikey"
fmt.Println("Using configuration file " + config_file)
parse := gonfig.GetConf(config_file, &configuration)
if parse != nil {
fmt.Println("Error parsing "+config_file+"\n", parse)
os.Exit(-1)
}
if configuration.SkillID == "" {
fmt.Println("Skill ID is not defined. Aborted")
os.Exit(255)
}
if configuration.UserName == "" {
fmt.Println("Chastikey UserName is not defined. Aborted")
os.Exit(255)
}
UserName = configuration.UserName
if cmd == "server" {
start_server(configuration.SkillID)
} else {
fmt.Println(parse_command(cmd, Args))
}
}