/
service.go
334 lines (279 loc) · 8.66 KB
/
service.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Package mail implements an email sending API that uses MailGun and SendInBlue.
package mail
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"github.com/mailgun/mailgun-go/v4"
"github.com/savannahghi/engagementcore/pkg/engagement/application/common/dto"
"github.com/savannahghi/engagementcore/pkg/engagement/application/common/helpers"
"github.com/savannahghi/engagementcore/pkg/engagement/infrastructure/database"
"github.com/savannahghi/serverutils"
"go.opentelemetry.io/otel"
)
var tracer = otel.Tracer("github.com/savannahghi/engagementcore/pkg/engagement/services/mail")
// Mail configuration constants
const (
MailGunAPIKeyEnvVarName = "MAILGUN_API_KEY"
MailGunAPIBaseURLEnvVarName = "MAILGUN_API_BASE_URL"
MailGunDomainEnvVarName = "MAILGUN_DOMAIN"
MailGunFromEnvVarName = "MAILGUN_FROM"
MailGunTimeoutSeconds = 15
SendInBlueAPIKeyEnvVarName = "SEND_IN_BLUE_API_KEY"
SendInBlueEnabledEnvVarName = "SEND_IN_BLUE_ENABLED"
appName = "Slade 360 HealthCloud"
defaultUser = "HealthCloud User"
sendInBlueBaseURL = "https://api.sendinblue.com/v3/smtp/email"
)
// ServiceMail defines a Mail service interface
type ServiceMail interface {
SendInBlue(ctx context.Context, subject, text string, to ...string) (string, string, error)
SendMailgun(
ctx context.Context,
subject, text string,
body *string,
to ...string,
) (string, string, error)
SendEmail(
ctx context.Context,
subject, text string,
body *string,
to ...string,
) (string, string, error)
SimpleEmail(
ctx context.Context,
subject, text string,
body *string,
to ...string,
) (string, error)
UpdateMailgunDeliveryStatus(
ctx context.Context,
payload *dto.MailgunEvent,
) (*dto.OutgoingEmailsLog, error)
GenerateEmailTemplate(name string, templateName string) string
}
// NewService initializes a new MailGun service
func NewService(repository database.Repository) *ServiceMailImpl {
apiKey := serverutils.MustGetEnvVar(MailGunAPIKeyEnvVarName)
domain := serverutils.MustGetEnvVar(MailGunDomainEnvVarName)
from := serverutils.MustGetEnvVar(MailGunFromEnvVarName)
mg := mailgun.NewMailgun(domain, apiKey)
mg.SetAPIBase(mailgun.APIBaseEU)
// special case for sandbox
if strings.Contains(domain, "sandbox") {
mg.SetAPIBase(mailgun.APIBase)
}
sendInBlueEnabled := false
if serverutils.MustGetEnvVar(SendInBlueEnabledEnvVarName) == "true" {
sendInBlueEnabled = true
}
return &ServiceMailImpl{
Mg: mg,
From: from,
SendInBlueAPIKey: serverutils.MustGetEnvVar(SendInBlueAPIKeyEnvVarName),
SendInBlueEnabled: sendInBlueEnabled,
Repository: repository,
}
}
// ServiceMailImpl is an email sending service
type ServiceMailImpl struct {
Mg *mailgun.MailgunImpl
From string
SendInBlueEnabled bool
SendInBlueAPIKey string
Repository database.Repository
}
// CheckPreconditions checks that all the required preconditions are satisfied
func (s ServiceMailImpl) CheckPreconditions() {
if s.Mg == nil {
log.Panicf("uninitialized MailGun")
}
if s.From == "" {
log.Panicf("uninitialized email from")
}
if s.SendInBlueAPIKey == "" {
log.Panicf("uninitialized sendInBlueAPIKey")
}
if s.Repository == nil {
log.Panicf("uninitialized repository in mail service")
}
}
// MakeSendInBlueRequest makes a request to SendInBlue
func (s ServiceMailImpl) MakeSendInBlueRequest(
ctx context.Context,
data map[string]interface{},
target interface{},
) error {
_, span := tracer.Start(ctx, "MakeSendInBlueRequest")
defer span.End()
bs, err := json.Marshal(data)
if err != nil {
helpers.RecordSpanError(span, err)
return fmt.Errorf("makeSendInBlueRequest: can't marshal data [%#v] to JSON: %w", data, err)
}
r := bytes.NewBuffer(bs)
req, reqErr := http.NewRequest(http.MethodPost, sendInBlueBaseURL, r)
if reqErr != nil {
helpers.RecordSpanError(span, err)
return reqErr
}
sendInBlueAPIKey := serverutils.MustGetEnvVar(SendInBlueAPIKeyEnvVarName)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("api-key", sendInBlueAPIKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
helpers.RecordSpanError(span, err)
return fmt.Errorf("SendInBlue API error: %w", err)
}
respBs, err := ioutil.ReadAll(resp.Body)
if err != nil {
helpers.RecordSpanError(span, err)
return fmt.Errorf("SendInBlue content error: %w", err)
}
if resp.StatusCode > 201 {
return fmt.Errorf("SendInBlue API Error: %s", string(respBs))
}
err = json.Unmarshal(respBs, target)
if err != nil {
helpers.RecordSpanError(span, err)
return fmt.Errorf("unable to unmarshal SendInBlue resp: %w", err)
}
return nil
}
// SendInBlue sends email via the SendInBlue service
func (s ServiceMailImpl) SendInBlue(
ctx context.Context,
subject, text string,
to ...string,
) (string, string, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "SendInBlue")
defer span.End()
sender := map[string]string{
"name": appName,
"email": s.From,
}
addresses := []map[string]string{}
for _, address := range to {
addresses = append(addresses, map[string]string{
"email": address,
})
}
data := map[string]interface{}{
"sender": sender,
"to": addresses,
"subject": subject,
"htmlContent": text,
}
result := map[string]interface{}{}
err := s.MakeSendInBlueRequest(ctx, data, &result)
if err != nil {
helpers.RecordSpanError(span, err)
return "", "", fmt.Errorf("unable to send email via sendInBlue: %w", err)
}
messageID, ok := result["messageId"].(string)
if !ok {
return "", "", fmt.Errorf("string messageID not found in SendInBlue response %#v", result)
}
return "ok", messageID, nil
}
// SendMailgun sends email via MailGun
func (s ServiceMailImpl) SendMailgun(
ctx context.Context,
subject, text string,
body *string,
to ...string,
) (string, string, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "SendMailgun")
defer span.End()
message := s.Mg.NewMessage(s.From, subject, text, to...)
if body != nil {
message.SetHtml(*body)
} else {
message.SetHtml(text)
}
ctx, cancel := context.WithTimeout(ctx, time.Second*MailGunTimeoutSeconds)
defer cancel()
resp, id, err := s.Mg.Send(ctx, message)
if err != nil {
helpers.RecordSpanError(span, err)
return resp, id, fmt.Errorf("mailgun email sending error: %s", err)
}
messageID := helpers.StripMailGunIDSpecialCharacters(id)
outgoingEmail := &dto.OutgoingEmailsLog{
UUID: uuid.NewString(),
To: to,
From: MailGunFromEnvVarName,
Subject: subject,
Text: text,
MessageID: messageID,
EmailSentOn: time.Now(),
}
err = s.SaveOutgoingEmails(ctx, outgoingEmail)
if err != nil {
return resp, id, fmt.Errorf("unable to save outgoing email(s): %s", err)
}
return resp, id, err
}
// SendEmail sends the specified email to the recipient(s) specified in `to`
// and returns the status
func (s ServiceMailImpl) SendEmail(
ctx context.Context,
subject, text string,
body *string,
to ...string,
) (string, string, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "SendEmail")
defer span.End()
if s.SendInBlueEnabled {
return s.SendInBlue(ctx, subject, text, to...)
}
return s.SendMailgun(ctx, subject, text, body, to...)
}
// SimpleEmail is a simplified API to send email.
// It returns only a status or error.
func (s ServiceMailImpl) SimpleEmail(
ctx context.Context,
subject, text string,
body *string,
to ...string,
) (string, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "SimpleEmail")
defer span.End()
status, _, err := s.SendEmail(ctx, subject, text, nil, to...)
return status, err
}
// SaveOutgoingEmails saves all the outgoing emails
func (s ServiceMailImpl) SaveOutgoingEmails(ctx context.Context, payload *dto.OutgoingEmailsLog) error {
ctx, span := tracer.Start(ctx, "SaveOutgoingEmails")
defer span.End()
return s.Repository.SaveOutgoingEmails(ctx, payload)
}
// UpdateMailgunDeliveryStatus updates the status and delivery time of the sent email message
func (s ServiceMailImpl) UpdateMailgunDeliveryStatus(
ctx context.Context,
payload *dto.MailgunEvent,
) (*dto.OutgoingEmailsLog, error) {
ctx, span := tracer.Start(ctx, "UpdateMailgunDeliveryStatus")
defer span.End()
return s.Repository.UpdateMailgunDeliveryStatus(ctx, payload)
}
// GenerateEmailTemplate generates custom emails to be sent to the users
func (s ServiceMailImpl) GenerateEmailTemplate(name string, templateName string) string {
t := template.Must(template.New("Be.WellEmailTemplate").Parse(templateName))
buf := new(bytes.Buffer)
_ = t.Execute(buf, name)
return buf.String()
}