/
hipchat.go
81 lines (70 loc) · 1.64 KB
/
hipchat.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"html"
"log"
"net/http"
"time"
)
const (
hipchatURL = "https://api.hipchat.com/v2"
)
// HipChatReminder reminds pull requests on a HipChat room.
type HipChatReminder struct {
Token string
url string
room string
client http.Client
}
// NewHipChatReminder initializes a new HipChatReminder with given room.
func NewHipChatReminder(room string) *HipChatReminder {
if room == "" {
log.Fatal("empty hipchat room")
}
return &HipChatReminder{
url: hipchatURL,
room: room,
}
}
// Remind sends a notification for given pull requests.
func (r *HipChatReminder) Remind(pr []*PullRequest) {
if len(pr) == 0 {
return
}
now := time.Now()
var buf bytes.Buffer
fmt.Fprintf(&buf, "Reminders (%d)", len(pr))
for _, p := range pr {
fmt.Fprintf(&buf, " <a href=%q>%s</a> (%s %s ago)",
p.URL, html.EscapeString(p.Title), p.Author,
(now.Sub(p.CreatedTime)/time.Second)*time.Second)
}
notif := make(map[string]string)
notif["from"] = "GitReminder"
notif["message"] = buf.String()
buf.Reset()
encoder := json.NewEncoder(&buf)
err := encoder.Encode(notif)
if err != nil {
log.Fatal(err)
}
url := fmt.Sprintf("%s/room/%s/notification", r.url, r.room)
log.Println("sending notification to", url)
req, err := http.NewRequest("POST", url, &buf)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
if r.Token != "" {
req.Header.Set("Authorization", "Bearer "+r.Token)
}
res, err := r.client.Do(req)
if err != nil {
log.Fatal(err)
}
if res.StatusCode != http.StatusNoContent {
log.Fatalf("unexpected hipchat status code: %d", res.StatusCode)
}
}