- default.htm ports WinterCMS's default layout: wrapper, header row with the Branding logo (or the site name), the inner-body card and a copyright footer; its text wrapper ends with the footer - built-in header and footer partials (logo/body/url, body) - layouts get siteName (Branding site name, else the display name of mail.from) and year; Brand.SiteName and migration 202611130002_mail_brand_site_name - cabana Branding form gets site_name (trimmed, max 255), mapped into the Branding preview draft; en/pl copy; img.logo brand CSS - 35-06 Task 1 (G-35-8)
355 lines
10 KiB
Go
355 lines
10 KiB
Go
package postcard
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
netmail "net/mail"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
"git.golem15.com/golem15/summercms/modules/compass"
|
|
"git.golem15.com/golem15/summercms/modules/diary"
|
|
"git.golem15.com/golem15/summercms/modules/pact"
|
|
)
|
|
|
|
// moduleLog is postcard's logger: records carry component=postcard and follow
|
|
// log.components.postcard (diary).
|
|
var moduleLog = diary.For("postcard")
|
|
|
|
// Message is the Send contract for plugin callers.
|
|
type Message struct {
|
|
Template string
|
|
To []string
|
|
Cc []string
|
|
Bcc []string
|
|
ReplyTo string
|
|
Vars map[string]any
|
|
Subject string
|
|
}
|
|
|
|
// Mailer sends a registered template through the configured driver.
|
|
type Mailer interface {
|
|
Send(ctx context.Context, msg Message) error
|
|
}
|
|
|
|
// Options configure an app-scoped mailer.
|
|
type Options struct {
|
|
From string
|
|
CSS string
|
|
BrandCSS string
|
|
// Overrides, when set, is asked once per Send for the database
|
|
// overrides of the template being sent. Nil sends the file versions.
|
|
Overrides OverrideSource
|
|
}
|
|
|
|
type mailer struct {
|
|
catalog *Catalog
|
|
driver Driver
|
|
opts Options
|
|
// source supplies database overrides; nil means files only.
|
|
source OverrideSource
|
|
// log receives override warnings and failures; nil means moduleLog.
|
|
log *slog.Logger
|
|
warned warnGate
|
|
}
|
|
|
|
// NewMailer returns a mailer that renders from cat and delivers through
|
|
// driver. opts.Overrides, when set, supplies database overrides per send.
|
|
func NewMailer(cat *Catalog, driver Driver, opts Options) Mailer {
|
|
if cat == nil {
|
|
cat = NewCatalog()
|
|
}
|
|
return &mailer{catalog: cat, driver: driver, opts: opts, source: opts.Overrides}
|
|
}
|
|
|
|
// Send renders msg.Template and delivers it. It picks no locale: the caller
|
|
// passes the full dotted name, including any -en suffix. A <template>-<locale>
|
|
// name whose locale ships no file resolves to the default-locale version:
|
|
// that name's customized row when there is one, else the base template's
|
|
// customized row, else the base template's file. A database override of the
|
|
// template is applied when the mailer has an OverrideSource; an override
|
|
// that cannot be read or does not render is logged and the file version is
|
|
// sent instead.
|
|
func (m *mailer) Send(ctx context.Context, msg Message) error {
|
|
if m == nil {
|
|
return fmt.Errorf("postcard: mailer is nil")
|
|
}
|
|
if m.driver == nil {
|
|
return fmt.Errorf("postcard: driver is nil")
|
|
}
|
|
if msg.Template == "" {
|
|
return fmt.Errorf("postcard: template is empty")
|
|
}
|
|
if len(msg.To) == 0 && len(msg.Cc) == 0 && len(msg.Bcc) == 0 {
|
|
return fmt.Errorf("postcard: no recipients")
|
|
}
|
|
rendered, err := m.render(ctx, msg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rendered.From = m.opts.From
|
|
_, smtp := m.driver.(*SMTPDriver)
|
|
if err := validateRendered(rendered, smtp); err != nil {
|
|
return err
|
|
}
|
|
if err := m.driver.Send(ctx, rendered); err != nil {
|
|
return fmt.Errorf("postcard: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// render renders msg with its database overrides applied. With no source, no
|
|
// overrides, or overrides that fail to render or to pass the safety checks,
|
|
// it renders the file version.
|
|
func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, error) {
|
|
t, err := m.catalog.resolveTemplate(msg.Template)
|
|
if err != nil {
|
|
return RenderedMessage{}, err
|
|
}
|
|
ov := m.overrides(ctx, msg.Template)
|
|
if t.name != msg.Template && ov.Template == nil {
|
|
// A fallback-locale name with no customization of its own sends the
|
|
// base's. Layouts, partials and Branding are the same in both
|
|
// answers; only the template override is taken.
|
|
ov.Template = m.overrides(ctx, t.name).Template
|
|
}
|
|
// The file version carries the Branding too: it is not an override of a
|
|
// file, and a failing override must not change how the mail looks.
|
|
file := m.options(ov.Brand)
|
|
if ov.empty() {
|
|
return m.catalog.render(msg, file)
|
|
}
|
|
with := file
|
|
with.overrides = ov
|
|
with.warn = m.warn
|
|
rendered, err := m.catalog.render(msg, with)
|
|
if err == nil {
|
|
return rendered, nil
|
|
}
|
|
// The override is at fault only when the file version renders; a
|
|
// failure of both is the caller's (a bad subject, a missing variable)
|
|
// and is returned as before.
|
|
rendered, fileErr := m.catalog.render(msg, file)
|
|
if fileErr != nil {
|
|
return RenderedMessage{}, fileErr
|
|
}
|
|
m.logger().Error("postcard: override failed, sending the file version",
|
|
slog.String("template", msg.Template),
|
|
slog.String("error", err.Error()),
|
|
)
|
|
return rendered, nil
|
|
}
|
|
|
|
// options returns the render options of the file version: mail.css, and
|
|
// either the saved Branding (its compiled CSS and its logo) or, while none
|
|
// has been saved, mail.brandCss. A Branding whose colours do not compile
|
|
// keeps mail.brandCss. The site name is the Branding's, else the display
|
|
// name of mail.from.
|
|
func (m *mailer) options(brand *Brand) renderOptions {
|
|
opts := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year()}
|
|
if brand == nil {
|
|
return opts
|
|
}
|
|
opts.logoURL = brand.LogoURL
|
|
css, err := CompileBrandCSS(*brand)
|
|
if err != nil {
|
|
m.warn(err.Error(), "postcard: mail branding is not valid, using mail.brandCss",
|
|
slog.String("error", err.Error()))
|
|
return opts
|
|
}
|
|
opts.brandCSS = css
|
|
return opts
|
|
}
|
|
|
|
// siteName returns the name the built-in layouts show: the Branding's site
|
|
// name, trimmed, else the display name of the sender address from, else
|
|
// empty.
|
|
func siteName(brand *Brand, from string) string {
|
|
if brand != nil {
|
|
if name := strings.TrimSpace(brand.SiteName); name != "" {
|
|
return name
|
|
}
|
|
}
|
|
addr, err := netmail.ParseAddress(from)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(addr.Name)
|
|
}
|
|
|
|
// overrides asks the source once. A failed lookup (no connection, tables not
|
|
// migrated yet) is a warning, not a send failure: the file version is sent.
|
|
func (m *mailer) overrides(ctx context.Context, template string) Overrides {
|
|
if m.source == nil {
|
|
return Overrides{}
|
|
}
|
|
ov, err := m.source.MailOverrides(ctx, template)
|
|
if err != nil {
|
|
m.warn(err.Error(), "postcard: mail overrides unavailable, sending the file version",
|
|
slog.String("template", template),
|
|
slog.String("error", err.Error()),
|
|
)
|
|
return Overrides{}
|
|
}
|
|
for _, warning := range ov.warnings {
|
|
m.warn(warning, "postcard: "+warning, slog.String("template", template))
|
|
}
|
|
return ov
|
|
}
|
|
|
|
func (m *mailer) logger() *slog.Logger {
|
|
if m.log != nil {
|
|
return m.log
|
|
}
|
|
return moduleLog
|
|
}
|
|
|
|
// warn logs at warning level, at most once per warnInterval per key.
|
|
func (m *mailer) warn(key, msg string, args ...any) {
|
|
if !m.warned.allow(key, time.Now()) {
|
|
return
|
|
}
|
|
m.logger().Warn(msg, args...)
|
|
}
|
|
|
|
const (
|
|
// warnInterval is how often the same override warning is repeated.
|
|
warnInterval = time.Minute
|
|
// warnGateSize bounds the keys a warnGate remembers.
|
|
warnGateSize = 64
|
|
)
|
|
|
|
// warnGate rate-limits warnings by key. The zero value is ready to use.
|
|
type warnGate struct {
|
|
mu sync.Mutex
|
|
last map[string]time.Time
|
|
}
|
|
|
|
func (g *warnGate) allow(key string, now time.Time) bool {
|
|
g.mu.Lock()
|
|
defer g.mu.Unlock()
|
|
if last, ok := g.last[key]; ok && now.Sub(last) < warnInterval {
|
|
return false
|
|
}
|
|
if g.last == nil || len(g.last) >= warnGateSize {
|
|
g.last = make(map[string]time.Time)
|
|
}
|
|
g.last[key] = now
|
|
return true
|
|
}
|
|
|
|
// Activate publishes an app-scoped Mailer before plugin Boot. Catalog files
|
|
// are validated later at each plugin's Boot transition. The mailer reads
|
|
// database overrides through NewDBSource, so they apply in every process
|
|
// that publishes a *gorm.DB on app.
|
|
func Activate[P interface{ ID() string }](app *backpack.App, _ []P) error {
|
|
if app == nil {
|
|
return fmt.Errorf("postcard: app is nil")
|
|
}
|
|
driver, opts, err := driverFromApp(app)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
opts.Overrides = NewDBSource(app)
|
|
m := &mailer{
|
|
catalog: NewCatalog(),
|
|
driver: driver,
|
|
opts: opts,
|
|
source: opts.Overrides,
|
|
}
|
|
if err := app.Publish[Mailer](m); err != nil {
|
|
return fmt.Errorf("postcard: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func driverFromApp(app *backpack.App) (Driver, Options, error) {
|
|
opts := Options{}
|
|
name := "memory"
|
|
smtp := SMTPConfig{Port: 587, Timeout: 10 * time.Second}
|
|
if app != nil && app.Config != nil {
|
|
c := app.Config
|
|
if v := strings.TrimSpace(c.String("mail.driver")); v != "" {
|
|
name = strings.ToLower(v)
|
|
}
|
|
opts.From = strings.TrimSpace(c.String("mail.from"))
|
|
opts.CSS = c.String("mail.css")
|
|
opts.BrandCSS = c.String("mail.brandCss")
|
|
smtp = smtpFromConfig(c)
|
|
}
|
|
switch name {
|
|
case "memory":
|
|
return NewMemoryDriver(), opts, nil
|
|
case "log":
|
|
return NewLogDriver(loggerFromApp(app)), opts, nil
|
|
case "smtp":
|
|
d, err := NewSMTPDriver(smtp)
|
|
if err != nil {
|
|
return nil, opts, err
|
|
}
|
|
return d, opts, nil
|
|
default:
|
|
return nil, opts, fmt.Errorf("postcard: unknown mail.driver %q (use memory, log, or smtp)", name)
|
|
}
|
|
}
|
|
|
|
func smtpFromConfig(c *compass.Config) SMTPConfig {
|
|
cfg := SMTPConfig{
|
|
Host: strings.TrimSpace(c.String("mail.smtp.host")),
|
|
Port: c.Int("mail.smtp.port"),
|
|
Username: c.String("mail.smtp.username"),
|
|
Password: c.String("mail.smtp.password"),
|
|
TLS: strings.TrimSpace(c.String("mail.smtp.tls")),
|
|
Timeout: 10 * time.Second,
|
|
}
|
|
if raw := strings.TrimSpace(c.String("mail.smtp.timeout")); raw != "" {
|
|
if d, err := time.ParseDuration(raw); err == nil {
|
|
cfg.Timeout = d
|
|
} else if n := c.Int("mail.smtp.timeout"); n > 0 {
|
|
cfg.Timeout = time.Duration(n) * time.Second
|
|
}
|
|
}
|
|
return cfg
|
|
}
|
|
|
|
func loggerFromApp(app *backpack.App) *slog.Logger {
|
|
if app != nil {
|
|
if log, ok := app.Lookup[*slog.Logger](); ok && log != nil {
|
|
return log
|
|
}
|
|
}
|
|
return moduleLog
|
|
}
|
|
|
|
// BootPlugin registers a plugin's declared mail partials (pact.HasMailPartials)
|
|
// and its templates and layouts (pact.HasMailTemplates). Either capability is
|
|
// optional. Missing files, duplicates, names outside the plugin's namespace
|
|
// and unknown layout aliases fail with the dotted name.
|
|
func BootPlugin[P interface{ ID() string }](app *backpack.App, p P) error {
|
|
hm, hasTemplates := any(p).(pact.HasMailTemplates)
|
|
hp, hasPartials := any(p).(pact.HasMailPartials)
|
|
if !hasTemplates && !hasPartials {
|
|
return nil
|
|
}
|
|
got, ok := app.Lookup[Mailer]()
|
|
if !ok {
|
|
return fmt.Errorf("postcard: mailer not published")
|
|
}
|
|
m, ok := got.(*mailer)
|
|
if !ok || m == nil || m.catalog == nil {
|
|
return fmt.Errorf("postcard: mailer not published")
|
|
}
|
|
if hasPartials {
|
|
if err := m.catalog.RegisterPartials(p.ID(), hp.MailPartialsFS(), hp.MailPartials()); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if hasTemplates {
|
|
return m.catalog.Register(p.ID(), hm.MailTemplatesFS(), hm.MailTemplates(), hm.MailLayouts())
|
|
}
|
|
return nil
|
|
}
|