This repository has been archived by the owner on Sep 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
109 lines (90 loc) · 2.17 KB
/
state.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
package state
import (
"encoding/json"
"fmt"
"strings"
"time"
"slackbot_atlassian/config"
"gopkg.in/redis.v3"
)
const redis_state_key = "slackbot_atlassian_last_event"
type Event struct {
Id string `json:"id"`
}
type State interface {
RecordLastEvent(Event) error
GetLastEvent() (Event, bool, error)
RecordUserImageURL(username, url string) error
GetUserImageURL(username string) (string, bool, error)
}
func New(cfg config.StateConfig) (State, error) {
return new(cfg, redis_state_key)
}
func new(cfg config.StateConfig, key string) (State, error) {
var db int64
switch cfg.DB.(type) {
case int:
db = int64(cfg.DB.(int))
case int64:
db = cfg.DB.(int64)
case float64:
db = int64(cfg.DB.(float64))
}
redisOptions := redis.Options{
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
DB: db,
}
client := redis.NewClient(&redisOptions)
return &redisState{client, key}, nil
}
type redisState struct {
client *redis.Client
key string
}
func (r *redisState) RecordLastEvent(ev Event) error {
b, err := json.Marshal(ev)
if err != nil {
return err
}
sc := r.client.Set(r.key, string(b), time.Duration(0))
return sc.Err()
}
func (r *redisState) GetLastEvent() (Event, bool, error) {
var ev Event
sc := r.client.Get(r.key)
err := sc.Err()
if err != nil && err == redis.Nil {
// No key found
return ev, false, nil
} else if err != nil {
// Error looking up key
return ev, false, err
}
val, err := sc.Result()
if err != nil {
return ev, false, err
}
return ev, true, json.Unmarshal([]byte(val), &ev)
}
func user_image_url_key(username string) string {
return "image-url-" + strings.Replace(username, " ", "_", -1)
}
func (r *redisState) RecordUserImageURL(username, url string) error {
key := user_image_url_key(username)
sc := r.client.Set(key, url, time.Duration(0))
return sc.Err()
}
func (r *redisState) GetUserImageURL(username string) (string, bool, error) {
key := user_image_url_key(username)
sc := r.client.Get(key)
err := sc.Err()
if err != nil && err == redis.Nil {
// No key found
return "", false, nil
} else if err != nil {
// Error looking up key
return "", false, err
}
val, err := sc.Result()
return val, true, err
}