1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/services/mail/mailwhale.go

93 lines
2.4 KiB
Go
Raw Normal View History

2021-04-05 17:25:13 +03:00
package mail
import (
"bytes"
"encoding/json"
"errors"
"fmt"
conf "github.com/muety/wakapi/config"
"github.com/muety/wakapi/models"
"net/http"
"time"
)
type MailWhaleMailService struct {
publicUrl string
config conf.MailwhaleMailConfig
2021-04-05 17:25:13 +03:00
httpClient *http.Client
}
type MailWhaleSendRequest struct {
To []string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text"`
Html string `json:"html"`
TemplateId string `json:"template_id"`
TemplateVars map[string]string `json:"template_vars"`
}
func NewMailWhaleService(config conf.MailwhaleMailConfig, publicUrl string) *MailWhaleMailService {
return &MailWhaleMailService{
publicUrl: publicUrl,
config: config,
2021-04-05 17:25:13 +03:00
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func (s *MailWhaleMailService) SendPasswordReset(recipient *models.User, resetLink string) error {
template, err := getPasswordResetTemplate(PasswordResetTplData{ResetLink: resetLink})
2021-04-05 17:25:13 +03:00
if err != nil {
return err
}
return s.send(recipient.Email, subjectPasswordReset, template.String(), true)
2021-04-05 17:25:13 +03:00
}
func (s *MailWhaleMailService) SendImportNotification(recipient *models.User, duration time.Duration, numHeartbeats int) error {
template, err := getImportNotificationTemplate(ImportNotificationTplData{
PublicUrl: s.publicUrl,
Duration: fmt.Sprintf("%.0f seconds", duration.Seconds()),
NumHeartbeats: numHeartbeats,
})
if err != nil {
return err
}
return s.send(recipient.Email, subjectImportNotification, template.String(), true)
}
func (s *MailWhaleMailService) send(to, subject, body string, isHtml bool) error {
2021-04-05 17:25:13 +03:00
if to == "" {
return errors.New("not sending mail as recipient mail address seems to be invalid")
2021-04-05 17:25:13 +03:00
}
sendRequest := &MailWhaleSendRequest{
To: []string{to},
Subject: subject,
}
if isHtml {
sendRequest.Html = body
} else {
sendRequest.Text = body
}
payload, _ := json.Marshal(sendRequest)
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/mail", s.config.Url), bytes.NewBuffer(payload))
2021-04-05 17:25:13 +03:00
if err != nil {
return err
}
req.SetBasicAuth(s.config.ClientId, s.config.ClientSecret)
2021-04-05 17:25:13 +03:00
req.Header.Set("Content-Type", "application/json")
res, err := s.httpClient.Do(req)
2021-04-05 17:25:13 +03:00
if err != nil {
return err
}
if res.StatusCode >= 400 {
return errors.New(fmt.Sprintf("got status %d from mailwhale", res.StatusCode))
2021-04-05 17:25:13 +03:00
}
return nil
}