High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
Refactor system notification callbacks into a new `notifs` package.
Kailash Nadhb3d46a8c85c4
diff --git a/cmd/campaigns.go b/cmd/campaigns.goindex c932b4e5..0c011d48 100644--- a/cmd/campaigns.go+++ b/cmd/campaigns.go@@ -638,7 +638,8 @@ func (h *Handlers) makeOptinCampaignMessage(o campReq) (campReq, error) {// Prepare sample opt-in message for the campaign.var b bytes.Buffer- if err := h.app.notifTpls.tpls.ExecuteTemplate(&b, "optin-campaign", struct {++ if err := h.app.notifs.Tpls.ExecuteTemplate(&b, "optin-campaign", struct {Lists []models.ListOptinURLAttr template.HTMLAttr}{lists, optinURLAttr}); err != nil {diff --git a/cmd/init.go b/cmd/init.goindex 8d7f2a28..673636ec 100644--- a/cmd/init.go+++ b/cmd/init.go@@ -43,6 +43,7 @@ import ("github.com/knadh/listmonk/internal/media/providers/s3""github.com/knadh/listmonk/internal/messenger/email""github.com/knadh/listmonk/internal/messenger/postback"+ "github.com/knadh/listmonk/internal/notifs""github.com/knadh/listmonk/internal/subimporter""github.com/knadh/listmonk/models""github.com/knadh/stuffbin"@@ -127,11 +128,6 @@ type constants struct {Permissions map[string]struct{}}-type notifTpls struct {- tpls *template.Template- contentType string-}-// initFlags initializes the commandline flags into the Koanf instance.func initFlags(ko *koanf.Koanf) {f := flag.NewFlagSet("config", flag.ContinueOnError)@@ -488,9 +484,9 @@ func initI18n(lang string, fs stuffbin.FileSystem) *i18n.I18n {}// initCampaignManager initializes the campaign manager.-func initCampaignManager(cb notifCB, q *models.Queries, cs *constants, co *core.Core, md media.Store, i *i18n.I18n) *manager.Manager {+func initCampaignManager(q *models.Queries, cs *constants, fnNotif notifs.FuncNotifSystem, co *core.Core, md media.Store, i *i18n.I18n) *manager.Manager {campNotifCB := func(subject string, data any) error {- return cb(cs.NotifyEmails, subject, notifTplCampaign, data, nil)+ return fnNotif(subject, notifTplCampaign, data, nil)}if ko.Bool("passive") {@@ -554,7 +550,7 @@ func initImporter(q *models.Queries, db *sqlx.DB, core *core.Core, app *App) *sucore.RefreshMatViews(true)// Send admin notification.- app.sendNotification(app.constants.NotifyEmails, subject, notifTplImport, data, nil)+ app.notifs.NotifySystem(subject, notifTplImport, data, nil)return nil},}, db.DB, app.i18n)@@ -680,39 +676,36 @@ func initMediaStore(ko *koanf.Koanf) media.Store {return nil}-// initNotifTemplates compiles and returns e-mail notification templates that are-// used for sending ad-hoc notifications to admins and subscribers.-func initNotifTemplates(fs stuffbin.FileSystem, i *i18n.I18n, cs *constants) *notifTpls {+// initNotifs initializes the notifier with the system e-mail templates.+func initNotifs(fs stuffbin.FileSystem, i *i18n.I18n, pushFn notifs.FuncPush, cs *constants, ko *koanf.Koanf) *notifs.Notifs {tpls, err := stuffbin.ParseTemplatesGlob(initTplFuncs(i, cs), fs, "/static/email-templates/*.html")if err != nil {lo.Fatalf("error parsing e-mail notif templates: %v", err)}+ // Read the notification templates.html, err := fs.Read("/static/email-templates/base.html")if err != nil {lo.Fatalf("error reading static/email-templates/base.html: %v", err)}- out := ¬ifTpls{- tpls: tpls,- contentType: models.CampaignContentTypeHTML,- }-// Determine whether the notification templates are HTML or plaintext.// Copy the first few (arbitrary) bytes of the template and check if has the <!doctype html> tag.- ln := 256- if len(html) < ln {- ln = len(html)- }+ ln := min(len(html), 256)h := make([]byte, ln)copy(h, html[0:ln])+ contentType := models.CampaignContentTypeHTMLif !bytes.Contains(bytes.ToLower(h), []byte("<!doctype html")) {- out.contentType = models.CampaignContentTypePlain+ contentType = models.CampaignContentTypePlainlo.Println("system e-mail templates are plaintext")}- return out+ return notifs.NewNotifs(notifs.Opt{+ FromEmail: ko.MustString("app.from_email"),+ SystemEmails: ko.MustStrings("app.notify_emails"),+ ContentType: contentType,+ }, tpls, pushFn, lo)}// initBounceManager initializes the bounce manager that scans mailboxes and listens to webhooksdiff --git a/cmd/main.go b/cmd/main.goindex 1a9312ca..9accc062 100644--- a/cmd/main.go+++ b/cmd/main.go@@ -24,6 +24,7 @@ import ("github.com/knadh/listmonk/internal/i18n""github.com/knadh/listmonk/internal/manager""github.com/knadh/listmonk/internal/media"+ notifs "github.com/knadh/listmonk/internal/notifs""github.com/knadh/listmonk/internal/subimporter""github.com/knadh/listmonk/models""github.com/knadh/paginator"@@ -52,7 +53,7 @@ type App struct {paginator *paginator.Paginatorcaptcha *captcha.Captchaevents *events.Events- notifTpls *notifTpls+ notifs *notifs.Notifsabout aboutlog *log.LoggerbufLog *buflog.BufLog@@ -211,11 +212,11 @@ func main() {// Initialize the CRUD core.app.core = core.New(cOpt, &core.Hooks{- SendOptinConfirmation: optinConfirmHook(app),+ SendOptinConfirmation: app.optinConfirmNotify(),})app.queries = queries- app.manager = initCampaignManager(app.sendNotification, app.queries, app.constants, app.core, app.media, app.i18n)+ app.manager = initCampaignManager(app.queries, app.constants, app.notifs.NotifySystem, app.core, app.media, app.i18n)app.importer = initImporter(app.queries, db, app.core, app)hasUsers, auth := initAuth(app.core, db.DB, ko)@@ -226,7 +227,7 @@ func main() {app.needsUserSetup = !hasUsers// Initialize admin email notification templates.- app.notifTpls = initNotifTemplates(fs, app.i18n, app.constants)+ app.notifs = initNotifs(app.fs, app.i18n, app.manager.PushMessage, app.constants, ko)initTxTemplates(app.manager, app.core)// Initialize the bounce manager that processes bounces from webhooks anddiff --git a/cmd/notifications.go b/cmd/notifications.goindex 933f2ce2..db612711 100644--- a/cmd/notifications.go+++ b/cmd/notifications.go@@ -1,16 +1,10 @@package mainimport (- "bytes"- "net/textproto""regexp""strings"-- "github.com/knadh/listmonk/models")-type notifCB func(toEmails []string, subject, tplName string, data any, headers textproto.MIMEHeader) error-const (notifTplImport = "import-status"notifTplCampaign = "campaign-status"@@ -22,36 +16,6 @@ var (reTitle = regexp.MustCompile(`(?s)<title\s*data-i18n\s*>(.+?)</title>`))-// sendNotification sends out an e-mail notification to admins.-func (app *App) sendNotification(toEmails []string, subject, tplName string, data any, headers textproto.MIMEHeader) error {- if len(toEmails) == 0 {- return nil- }-- var buf bytes.Buffer- if err := app.notifTpls.tpls.ExecuteTemplate(&buf, tplName, data); err != nil {- app.log.Printf("error compiling notification template '%s': %v", tplName, err)- return err- }- body := buf.Bytes()-- subject, body = getTplSubject(subject, body)-- m := models.Message{}- m.ContentType = app.notifTpls.contentType- m.From = app.constants.FromEmail- m.To = toEmails- m.Subject = subject- m.Body = body- m.Messenger = emailMsgr- m.Headers = headers- if err := app.manager.PushMessage(m); err != nil {- app.log.Printf("error sending admin notification (%s): %v", subject, err)- return err- }- return nil-}-// 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) {diff --git a/cmd/public.go b/cmd/public.goindex 7ab296b6..ba43aa06 100644--- a/cmd/public.go+++ b/cmd/public.go@@ -563,26 +563,21 @@ func (h *Handlers) SelfExportSubscriberData(c echo.Context) error {// Prepare the attachment e-mail.var msg bytes.Buffer- if err := h.app.notifTpls.tpls.ExecuteTemplate(&msg, notifSubscriberData, data); err != nil {+ if err := h.app.notifs.Tpls.ExecuteTemplate(&msg, notifSubscriberData, data); err != nil {h.app.log.Printf("error compiling notification template '%s': %v", notifSubscriberData, err)return c.Render(http.StatusInternalServerError, tplMessage,makeMsgTpl(h.app.i18n.T("public.errorTitle"), "", h.app.i18n.Ts("public.errorProcessingRequest")))}- var (- subject = h.app.i18n.Ts("email.data.title")- body = msg.Bytes()- )- subject, body = getTplSubject(subject, body)+ subject, body := getTplSubject(h.app.i18n.Ts("email.data.title"), msg.Bytes())// E-mail the data as a JSON attachment to the subscriber.const fname = "data.json"if err := h.app.emailMessenger.Push(models.Message{- ContentType: h.app.notifTpls.contentType,- From: h.app.constants.FromEmail,- To: []string{data.Email},- Subject: subject,- Body: body,+ From: h.app.constants.FromEmail,+ To: []string{data.Email},+ Subject: subject,+ Body: body,Attachments: []models.Attachment{{Name: fname,diff --git a/cmd/settings.go b/cmd/settings.goindex 30183d64..62741111 100644--- a/cmd/settings.go+++ b/cmd/settings.go@@ -323,13 +323,12 @@ func (h *Handlers) TestSMTPSettings(c echo.Context) error {// Render the test email template body.var b bytes.Buffer- if err := h.app.notifTpls.tpls.ExecuteTemplate(&b, "smtp-test", nil); err != nil {+ if err := h.app.notifs.Tpls.ExecuteTemplate(&b, "smtp-test", nil); err != nil {h.app.log.Printf("error compiling notification template '%s': %v", "smtp-test", err)return err}m := models.Message{}- m.ContentType = h.app.notifTpls.contentTypem.From = h.app.constants.FromEmailm.To = []string{to}m.Subject = h.app.i18n.T("settings.smtp.testConnection")diff --git a/cmd/subscribers.go b/cmd/subscribers.goindex 91b74c86..a5d78ae2 100644--- a/cmd/subscribers.go+++ b/cmd/subscribers.go@@ -261,7 +261,7 @@ func (h *Handlers) SubscriberSendOptin(c echo.Context) error {}// Trigger the opt-in confirmation e-mail hook.- if _, err := optinConfirmHook(h.app)(out, nil); err != nil {+ if _, err := h.app.optinConfirmNotify()(out, nil); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, h.app.i18n.T("subscribers.errorSendingOptin"))}@@ -556,10 +556,10 @@ func (h *Handlers) exportSubscriberData(id int, subUUID string, exportables map[return data, b, nil}-// optinConfirmHook returns an enclosed callback that sends optin confirmation e-mails.+// optinConfirmNotify returns an enclosed callback that sends optin confirmation e-mails.// This is plugged into the 'core' package to send optin confirmations when a new subscriber is// created via `core.CreateSubscriber()`.-func optinConfirmHook(app *App) func(sub models.Subscriber, listIDs []int) (int, error) {+func (app *App) optinConfirmNotify() func(sub models.Subscriber, listIDs []int) (int, error) {return func(sub models.Subscriber, listIDs []int) (int, error) {lists, err := app.core.GetSubscriberLists(sub.ID, "", listIDs, nil, models.SubscriptionStatusUnconfirmed, models.ListOptinDouble)if err != nil {@@ -595,7 +595,7 @@ func optinConfirmHook(app *App) func(sub models.Subscriber, listIDs []int) (int,}// Send the e-mail.- if err := app.sendNotification([]string{sub.Email}, app.i18n.T("subscribers.optinSubject"), notifSubscriberOptin, out, hdr); err != nil {+ if err := app.notifs.Notify([]string{sub.Email}, app.i18n.T("subscribers.optinSubject"), notifSubscriberOptin, out, hdr); err != nil {app.log.Printf("error sending opt-in e-mail for subscriber %d (%s): %s", sub.ID, sub.UUID, err)return 0, err}diff --git a/internal/manager/manager.go b/internal/manager/manager.goindex f40c665c..435ea93e 100644--- a/internal/manager/manager.go+++ b/internal/manager/manager.go@@ -64,7 +64,7 @@ type Manager struct {store Storei18n *i18n.I18nmessengers map[string]Messenger- notifCB models.AdminNotifCallback+ notifCB models.NotifCallbacklog *log.Logger// Campaigns that are currently running.@@ -145,7 +145,7 @@ type Config struct {var pushTimeout = time.Second * 3// New returns a new instance of Mailer.-func New(cfg Config, store Store, notifCB models.AdminNotifCallback, i *i18n.I18n, l *log.Logger) *Manager {+func New(cfg Config, store Store, notifCB models.NotifCallback, i *i18n.I18n, l *log.Logger) *Manager {if cfg.BatchSize < 1 {cfg.BatchSize = 1000}diff --git a/internal/notifs/notifs.go b/internal/notifs/notifs.gonew file mode 100644index 00000000..06e44f9c--- /dev/null+++ b/internal/notifs/notifs.go@@ -0,0 +1,94 @@+package notifs++import (+ "bytes"+ "html/template"+ "log"+ "net/textproto"+ "regexp"+ "strings"++ "github.com/knadh/listmonk/models"+)++type FuncPush func(msg models.Message) error+type FuncNotif func(toEmails []string, subject, tplName string, data any, headers textproto.MIMEHeader) error+type FuncNotifSystem func(subject, tplName string, data any, headers textproto.MIMEHeader) error++type Opt struct {+ FromEmail string+ SystemEmails []string+ ContentType string+}++var (+ reTitle = regexp.MustCompile(`(?s)<title\s*data-i18n\s*>(.+?)</title>`)+)++type Notifs struct {+ Tpls *template.Template+ pushFn FuncPush+ lo *log.Logger++ opt Opt+}++// NewNotifs returns a new Notifs instance.+func NewNotifs(opt Opt, tpls *template.Template, pushFn FuncPush, lo *log.Logger) *Notifs {+ return &Notifs{+ opt: opt,+ Tpls: tpls,+ pushFn: pushFn,+ lo: lo,+ }+}++// NotifySystem sends out an e-mail notification to the admin emails.+func (n *Notifs) NotifySystem(subject, tplName string, data any, hdr textproto.MIMEHeader) error {+ return n.Notify(n.opt.SystemEmails, subject, tplName, data, hdr)+}++// Notify sends out an e-mail notification.+func (n *Notifs) Notify(toEmails []string, subject, tplName string, data any, hdr textproto.MIMEHeader) error {+ if len(toEmails) == 0 {+ return nil+ }++ var buf bytes.Buffer+ if err := n.Tpls.ExecuteTemplate(&buf, tplName, data); err != nil {+ n.lo.Printf("error compiling notification template '%s': %v", tplName, err)+ return err+ }+ body := buf.Bytes()++ subject, body = getTplSubject(subject, body)++ m := models.Message{+ Messenger: "email",+ ContentType: n.opt.ContentType,+ From: n.opt.FromEmail,+ To: toEmails,+ Subject: subject,+ Body: body,+ Headers: hdr,+ }++ // Send the message.+ if err := n.pushFn(m); err != nil {+ n.lo.Printf("error sending admin notification (%s): %v", subject, err)+ return err+ }++ return nil+}++// getTplSubject extracts 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(""))+}diff --git a/internal/subimporter/importer.go b/internal/subimporter/importer.goindex 542dec2e..f4a61acf 100644--- a/internal/subimporter/importer.go+++ b/internal/subimporter/importer.go@@ -71,7 +71,7 @@ type Options struct {UpsertStmt *sql.StmtBlocklistStmt *sql.StmtUpdateListDateStmt *sql.Stmt- NotifCB models.AdminNotifCallback+ NotifCB models.NotifCallbackDomainBlocklist []stringDomainAllowlist []string@@ -253,9 +253,7 @@ func (im *Importer) sendNotif(status string) error {Imported: s.Imported,Total: s.Total,}- subject = fmt.Sprintf("%s: %s import",- cases.Title(language.Und).String(status),- s.Name)+ subject = fmt.Sprintf("%s: %s import", cases.Title(language.Und).String(status), s.Name))return im.opt.NotifCB(subject, out)}diff --git a/models/models.go b/models/models.goindex f0cfaa73..0babe29d 100644--- a/models/models.go+++ b/models/models.go@@ -119,9 +119,8 @@ var regTplFuncs = []regTplFunc{},}-// AdminNotifCallback is a callback function that's called-// when a campaign's status changes.-type AdminNotifCallback func(subject string, data any) error+// NotifCallback is a callback function that triggers a notification.+type NotifCallback func(subject string, data any) error// PageResults is a generic HTTP response container for paginated results of list of items.type PageResults struct {