-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
209 lines (177 loc) · 4.8 KB
/
main.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
package main
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/smtp"
"os"
"time"
)
func main() {
slog.Info("getting builds")
prag_user, prag_passwd := os.Getenv("PRAG_USER"), os.Getenv("PRAG_PASSWD")
if prag_user == "" || prag_passwd == "" {
fmt.Fprintf(os.Stderr, "error: no pragmatic credentials")
os.Exit(1)
}
gmail_user, gmail_passwd := os.Getenv("GMAIL_USER"), os.Getenv("GMAIL_PASSWD")
if gmail_user == "" || gmail_passwd == "" {
fmt.Fprintln(os.Stderr, "error: no gmail credentials")
os.Exit(1)
}
histFile := "notifications.json"
hist, err := OpenDB(histFile)
if err != nil {
fmt.Fprintf(os.Stderr, "error: can't open history at %q - %s", histFile, err)
os.Exit(1)
}
defer hist.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
rc, err := fetchBuilds(ctx, prag_user, prag_passwd)
if err != nil {
fmt.Fprintf(os.Stderr, "error: fetch builds - %s", err)
os.Exit(1)
}
defer rc.Close()
builds, err := parseHTML(rc)
if err != nil {
fmt.Fprintf(os.Stderr, "error: can't parse HTML - %s", err)
os.Exit(1)
}
slog.Info("builds", "count", len(builds))
var s Sender
if os.Getenv("DEBUG") != "" {
s = debugSender{}
} else {
s = GmailSender{gmail_user, gmail_passwd}
}
if err := notify(context.Background(), builds, db, hist, s); err != nil {
fmt.Fprintf(os.Stderr, "error: can't notify - %s", err)
os.Exit(1)
}
}
const buildsURL = "https://portal.pragprog.com/build_statuses"
func fetchBuilds(ctx context.Context, user, passwd string) (io.ReadCloser, error) {
var r io.ReadCloser
var err error
for i := range 3 {
r, err = fetchBuildsOnce(ctx, user, passwd)
if err == nil {
return r, nil
}
slog.Warn("can't fetch builds", "try", i+1, "error", err)
time.Sleep(time.Second)
}
return nil, err
}
func fetchBuildsOnce(ctx context.Context, user, passwd string) (io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, buildsURL, nil)
if err != nil {
return nil, fmt.Errorf("can't build request for %q - %w", buildsURL, err)
}
req.SetBasicAuth(user, passwd)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("can't GET %q - %w", buildsURL, err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%q: bad status - %s", buildsURL, resp.Status)
}
return resp.Body, nil
}
func notify(ctx context.Context, builds []Build, observers map[string][]string, hist *DB, sender Sender) error {
var errs []error
for _, b := range builds {
if !b.Failed {
continue
}
for _, email := range observers[b.Name] {
// FIXME: Don't double notify
slog.Info("notifying %q on %+v", email, b)
if hist.Has(b.ID, email) {
slog.Info("skipping (already sent)")
continue
}
content := formatEmail(email, b)
if err := sender.Send(ctx, email, content); err != nil {
slog.Error("can't email", "email", email, "error", err)
errs = append(errs, err)
}
hist.Add(b.ID, email)
}
}
return errors.Join(errs...)
}
type Sender interface {
Send(ctx context.Context, to, content string) error
}
type debugSender struct{}
func (s debugSender) Send(ctx context.Context, to, content string) error {
slog.Info("sending", "email", to, "content", content)
return nil
}
type GmailSender struct {
user string
passwd string
}
func (s GmailSender) Send(ctx context.Context, to, content string) error {
auth := LoginAuth(s.user, s.passwd)
// FIXME
return smtp.SendMail(
"smtp.gmail.com:587",
auth,
s.user,
[]string{to},
[]byte(content),
)
}
var emailTemplate = `From: PragBuilds Bot <[email protected]>
To: %s
Subject: [pragbuilds bot] %q build %d failed
Hi There,
I'm sorry to inform you that build %d of %q has failed.
You can see the logs at https://portal.pragprog.com/build_statuses/%d/log.
Onward and upward,
The pragbuilds bot
`
func formatEmail(to string, build Build) string {
text := fmt.Sprintf(
emailTemplate,
to,
build.Name, build.ID, // subject
build.ID, build.Name, build.ID, // body
)
return text
}
// https://gist.github.com/jpillora/cb46d183eca0710d909a?permalink_comment_id=3519541
type loginAuth struct {
username, password string
}
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, nil
}
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(a.username), nil
case "Password:":
return []byte(a.password), nil
default:
return nil, errors.New("Unkown fromServer")
}
}
return nil, nil
}
// Poor man's database
var db = map[string][]string{
"Effective Go Recipes": {"[email protected]"},
"Go Optimization Handbook": {"[email protected]"},
}