-
Notifications
You must be signed in to change notification settings - Fork 0
/
hipwatch.go
134 lines (104 loc) · 2.38 KB
/
hipwatch.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
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
)
import (
"github.com/tbruyelle/hipchat-go/hipchat"
)
type config struct {
Token string `json:"token"`
Notify []string `json:"notify"`
Statefile string `json:"statefile"`
}
type Hipwatch struct {
config config
client *hipchat.Client
}
func (h Hipwatch) notify(s string) {
msg := &hipchat.MessageRequest{Message: s}
for _, u := range h.config.Notify {
_, err := h.client.User.Message(u, msg)
if err != nil {
log.Printf("Unable to deliver notification to %v: %v", s, err)
}
}
}
func (h Hipwatch) fetchusers() (*[]hipchat.User, error) {
var users []hipchat.User
var opts hipchat.UserListOptions
opts.MaxResults = 1000
for {
u, _, err := h.client.User.List(&opts)
if err != nil {
return nil, err
}
users = append(users, u...)
if len(u) == opts.MaxResults {
opts.StartIndex += opts.MaxResults
} else {
break
}
}
return &users, nil
}
func NewHipwatch(configfile string) *Hipwatch {
var h Hipwatch
d, err := ioutil.ReadFile(configfile)
if err != nil {
log.Fatalf("couldn't read %v: %v", configfile, err)
}
err = json.Unmarshal(d, &h.config)
if err != nil {
log.Fatalf("couldn't understand %v: %v", configfile, err)
}
h.client = hipchat.NewClient(h.config.Token)
return &h
}
func main() {
var state []hipchat.User
var configfile string
flag.StringVar(&configfile, "c", "config.json", "configuration filename")
flag.Parse()
h := NewHipwatch(configfile)
users, err := h.fetchusers()
if err != nil {
panic(err)
}
d, _ := ioutil.ReadFile(h.config.Statefile)
err = json.Unmarshal(d, &state)
if err != nil {
log.Println("invalid state: resetting")
state = *users
}
cur := make(map[int]*hipchat.User)
prev := make(map[int]*hipchat.User)
for i, u := range *users {
cur[u.ID] = &(*users)[i]
}
for i, u := range state {
prev[u.ID] = &state[i]
}
for k, v := range prev {
if cur[k] == nil {
h.notify(fmt.Sprintf("Goodbye to @%v (%v)", v.MentionName, v.Name))
}
}
for k, v := range cur {
if prev[k] == nil {
h.notify(fmt.Sprintf("Say hello to @%v (%v)", v.MentionName, v.Name))
}
}
j, err := json.MarshalIndent(users, "", " ")
if err == nil {
err = ioutil.WriteFile(h.config.Statefile, j, 0644)
if err != nil {
log.Fatalln("Unable to write state file: %v", err)
}
} else {
log.Fatalln("Unable to marshal json: %v", err)
}
}