-
Notifications
You must be signed in to change notification settings - Fork 0
/
deliver.go
208 lines (188 loc) · 5.91 KB
/
deliver.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
package main
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"strings"
"time"
"github.com/cdzombak/gotfy"
mail "github.com/xhit/go-simple-mail/v2"
)
type deliveryConfig struct {
mail *mailDeliveryConfig
ntfy *ntfyDeliveryConfig
discord *discordDeliveryConfig
}
// mailDeliveryConfig, if provided, is assumed to be complete, valid, and internally consistent.
type mailDeliveryConfig struct {
mailTo string
mailFrom string
smtpUser string
smtpPassword string
smtpHost string
smtpPort int
tabCharReplacement string
}
// ntfyDeliveryConfig, if provided, is assumed to be complete, valid, and internally consistent.
type ntfyDeliveryConfig struct {
ntfyServerURL *url.URL
ntfyTopic string
ntfyTags string
ntfyEmail string
ntfyAccessToken string
ntfyPriority int
}
// discordDeliveryConfig, if provided, is assumed to be complete, valid, and internally consistent.
type discordDeliveryConfig struct {
discordWebhookURL string
logFileName string
}
const (
successNotifyTimeout = 10 * time.Second
ntfyTimeout = 10 * time.Second
discordTimeout = 10 * time.Second
mailTimeout = 10 * time.Second
)
func executeDeliveries(config *deliveryConfig, runOutput *runOutput) []error {
var deliveryErrors []error
if config.mail != nil {
deliveryErrors = extendErrSlice(deliveryErrors,
executeMailDelivery(config.mail, runOutput))
}
if config.ntfy != nil {
deliveryErrors = extendErrSlice(deliveryErrors,
executeNtfyDelivery(config.ntfy, runOutput))
}
if config.discord != nil {
deliveryErrors = extendErrSlice(deliveryErrors,
executeDiscordDelivery(config.discord, runOutput))
}
return deliveryErrors
}
func executeMailDelivery(cfg *mailDeliveryConfig, runOutput *runOutput) error {
server := mail.NewSMTPClient()
server.Host = cfg.smtpHost
server.Port = cfg.smtpPort
server.Username = cfg.smtpUser
server.Password = cfg.smtpPassword
server.KeepAlive = false
server.ConnectTimeout = mailTimeout
server.SendTimeout = mailTimeout
smtpClient, err := server.Connect()
if err != nil {
return fmt.Errorf("failed to connect to SMTP server: %w", err)
}
email := mail.NewMSG()
email.SetFrom(cfg.mailFrom)
email.AddTo(cfg.mailTo)
email.SetSubject(fmt.Sprintf("%s %s", runOutput.emoj, runOutput.summaryLine))
email.AddHeader("X-Mailer", productIdentifier())
body := strings.ReplaceAll(runOutput.output, "\n", "\r\n")
if cfg.tabCharReplacement != "" {
body = strings.ReplaceAll(body, "\t", cfg.tabCharReplacement)
}
email.SetBody(mail.TextPlain, body)
if email.Error != nil {
return fmt.Errorf("failed to build email: %w", email.Error)
}
if err = email.Send(smtpClient); err != nil {
return fmt.Errorf("failed to send email to %s: %w", cfg.mailTo, err)
}
return nil
}
func executeNtfyDelivery(cfg *ntfyDeliveryConfig, runOutput *runOutput) error {
var ntfyAuth gotfy.Authorization
if cfg.ntfyAccessToken != "" {
ntfyAuth = gotfy.AccessToken(cfg.ntfyAccessToken)
}
ntfyPublisher := gotfy.NewPublisher(gotfy.PublisherOpts{
Server: cfg.ntfyServerURL,
Auth: ntfyAuth,
Headers: http.Header{
"User-Agent": {productIdentifier()},
},
})
ctx, cancel := context.WithTimeout(context.Background(), ntfyTimeout)
defer cancel()
_, err := ntfyPublisher.Send(ctx, gotfy.Message{
Topic: cfg.ntfyTopic,
Tags: strings.Split(cfg.ntfyTags, ","),
Priority: gotfy.Priority(cfg.ntfyPriority),
Email: cfg.ntfyEmail,
Title: runOutput.summaryLine,
Message: runOutput.output,
})
if err != nil {
return fmt.Errorf("failed to send ntfy notification: %w", err)
}
return nil
}
func executeDiscordDelivery(cfg *discordDeliveryConfig, runOutput *runOutput) error {
webhookBody := &bytes.Buffer{}
writer := multipart.NewWriter(webhookBody)
err := writer.WriteField("content", fmt.Sprintf("%s %s", runOutput.emoj, runOutput.summaryLine))
if err != nil {
return fmt.Errorf("failed building Discord webhook body (.WriteField): %w", err)
}
filePart, err := writer.CreateFormFile("files[0]", cfg.logFileName)
if err != nil {
return fmt.Errorf("failed building Discord webhook body (.CreateFormFile): %w", err)
}
_, err = filePart.Write([]byte(runOutput.output))
if err != nil {
return fmt.Errorf("failed attaching log file to Discord webhook body: %w", err)
}
err = writer.Close()
if err != nil {
return fmt.Errorf("failed building Discord webhook body (.Close): %w", err)
}
client := http.DefaultClient
client.Timeout = discordTimeout
req, err := http.NewRequest(http.MethodPost, cfg.discordWebhookURL, webhookBody)
if err != nil {
return fmt.Errorf("failed building Discord webhook HTTP request: %w", err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("User-Agent", productIdentifier())
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed POSTing Discord webhook: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
respContent, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed POSTing Discord webhook (%s) and reading response body: %w", resp.Status, err)
}
return fmt.Errorf("failed POSTing Discord webhook (%s): %s", resp.Status, respContent)
}
return nil
}
func deliverSuccessNotification(url string) error {
client := http.DefaultClient
client.Timeout = successNotifyTimeout
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("failed to build GET request for '%s': %w", url, err)
}
req.Header.Set("User-Agent", productIdentifier())
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to GET '%s': %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode > 200 || resp.StatusCode < 299 {
return fmt.Errorf("failed to GET '%s' (%s)", url, resp.Status)
}
return nil
}
func extendErrSlice(errs []error, err error) []error {
if err != nil {
errs = append(errs, err)
}
return errs
}