2018-11-28 15:59:57 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2024-03-25 18:19:40 +08:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
2020-03-08 14:57:41 +08:00
|
|
|
|
2023-05-09 01:13:25 +08:00
|
|
|
"github.com/knadh/listmonk/models"
|
2018-11-28 15:59:57 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2019-12-01 20:18:36 +08:00
|
|
|
notifTplImport = "import-status"
|
|
|
|
notifTplCampaign = "campaign-status"
|
|
|
|
notifSubscriberOptin = "subscriber-optin"
|
|
|
|
notifSubscriberData = "subscriber-data"
|
2018-11-28 15:59:57 +08:00
|
|
|
)
|
|
|
|
|
2024-03-25 18:19:40 +08:00
|
|
|
var (
|
|
|
|
reTitle = regexp.MustCompile(`(?s)<title\s*data-i18n\s*>(.+?)</title>`)
|
|
|
|
)
|
|
|
|
|
2019-12-01 20:18:36 +08:00
|
|
|
// notifData represents params commonly used across different notification
|
|
|
|
// templates.
|
|
|
|
type notifData struct {
|
|
|
|
RootURL string
|
|
|
|
LogoURL string
|
|
|
|
}
|
2018-11-28 15:59:57 +08:00
|
|
|
|
2019-12-01 20:18:36 +08:00
|
|
|
// sendNotification sends out an e-mail notification to admins.
|
2020-03-08 14:57:41 +08:00
|
|
|
func (app *App) sendNotification(toEmails []string, subject, tplName string, data interface{}) error {
|
2021-09-24 21:58:32 +08:00
|
|
|
if len(toEmails) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-03-25 18:19:40 +08:00
|
|
|
var buf bytes.Buffer
|
|
|
|
if err := app.notifTpls.tpls.ExecuteTemplate(&buf, tplName, data); err != nil {
|
2020-03-08 02:33:22 +08:00
|
|
|
app.log.Printf("error compiling notification template '%s': %v", tplName, err)
|
2018-11-28 15:59:57 +08:00
|
|
|
return err
|
|
|
|
}
|
2024-03-25 18:19:40 +08:00
|
|
|
body := buf.Bytes()
|
|
|
|
|
|
|
|
subject, body = getTplSubject(subject, body)
|
2018-11-28 15:59:57 +08:00
|
|
|
|
2023-05-09 01:13:25 +08:00
|
|
|
m := models.Message{}
|
2021-10-28 22:39:06 +08:00
|
|
|
m.ContentType = app.notifTpls.contentType
|
2020-09-20 19:01:24 +08:00
|
|
|
m.From = app.constants.FromEmail
|
|
|
|
m.To = toEmails
|
|
|
|
m.Subject = subject
|
2024-03-25 18:19:40 +08:00
|
|
|
m.Body = body
|
2020-09-20 19:01:24 +08:00
|
|
|
m.Messenger = emailMsgr
|
|
|
|
if err := app.manager.PushMessage(m); err != nil {
|
2020-03-08 02:33:22 +08:00
|
|
|
app.log.Printf("error sending admin notification (%s): %v", subject, err)
|
2018-11-28 15:59:57 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2024-03-25 18:19:40 +08:00
|
|
|
|
|
|
|
// getTplSubject extrcts any custom i18n subject rendered in the given rendered
|
|
|
|
// template body. If it's not found, the incoming subject and body are returned.
|
|
|
|
func getTplSubject(subject string, body []byte) (string, []byte) {
|
|
|
|
m := reTitle.FindSubmatch(body)
|
|
|
|
if len(m) != 2 {
|
|
|
|
return subject, body
|
|
|
|
}
|
|
|
|
|
|
|
|
return strings.TrimSpace(string(m[1])), reTitle.ReplaceAll(body, []byte(""))
|
|
|
|
}
|