- sample.<path> header keys and a parse-tree walker that fills every other variable with a visible [path] placeholder, nested fields and range targets included - every file entry carries the sha256 of its CRLF-normalized text; the catalog lists its files (Templates, Layouts, Partials) for admin code - SyncIndex upserts one index row per file and never touches the override columns of a customized row; ResetOverride returns a row to its file - Editor validates, previews and test-sends a template, layout or partial draft through the render path of Send and reports field and rule - pact.RowStateCustomized and pact.RowStateOutdated Plan 35-01, task 4.
474 lines
14 KiB
Go
474 lines
14 KiB
Go
package postcard
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"text/template/parse"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
)
|
|
|
|
// Kind names what a Draft or an index row is.
|
|
type Kind string
|
|
|
|
// The kinds of mail content an administrator edits.
|
|
const (
|
|
KindTemplate Kind = "template"
|
|
KindLayout Kind = "layout"
|
|
KindPartial Kind = "partial"
|
|
KindBrand Kind = "brand"
|
|
)
|
|
|
|
// Draft is edited mail content that has not been saved: what Validate
|
|
// checks and Preview and SendDraft render.
|
|
type Draft struct {
|
|
Kind Kind
|
|
// Name is the template's full name, the layout's code or the partial's
|
|
// full name.
|
|
Name string
|
|
|
|
// Subject, Body and Layout are a template draft. Layout is a layout
|
|
// code; empty keeps the file's layout.
|
|
Subject string
|
|
Body string
|
|
Layout string
|
|
|
|
// HTML and Text are a layout's wrappers or a partial's sections; CSS is
|
|
// a layout's own CSS.
|
|
HTML string
|
|
Text string
|
|
CSS string
|
|
}
|
|
|
|
// The rules a DraftError reports.
|
|
const (
|
|
ruleParse = "parse"
|
|
ruleRender = "render"
|
|
ruleUnsafe = "unsafe"
|
|
ruleSubjectLine = "subject_line"
|
|
ruleLayout = "layout"
|
|
rulePartial = "partial"
|
|
ruleNoContent = "no_content"
|
|
)
|
|
|
|
// The fields a DraftError names: the columns an admin form binds.
|
|
const (
|
|
fieldSubject = "subject"
|
|
fieldLayout = "layout"
|
|
fieldBody = "body"
|
|
fieldContentHTML = "content_html"
|
|
fieldContentText = "content_text"
|
|
fieldContentCSS = "content_css"
|
|
)
|
|
|
|
// DraftError is a draft that cannot be saved as it is.
|
|
type DraftError struct {
|
|
// Field is the form field at fault: subject, layout or body for a
|
|
// template, content_html, content_text or content_css for a layout or a
|
|
// partial.
|
|
Field string
|
|
// Rule is what failed: parse, render, unsafe, subject_line, layout,
|
|
// partial or no_content.
|
|
Rule string
|
|
// Message is the parser's, renderer's or safety check's own text, and
|
|
// for the unsafe rule the text that matched. It carries nothing else.
|
|
Message string
|
|
// Name is the partial an unknown-partial failure refers to.
|
|
Name string
|
|
}
|
|
|
|
func (e *DraftError) Error() string {
|
|
out := "postcard: draft " + e.Field + ": " + e.Rule
|
|
if e.Name != "" {
|
|
out += " " + e.Name
|
|
}
|
|
if e.Message != "" {
|
|
out += ": " + e.Message
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Preview is a rendered draft.
|
|
type Preview struct {
|
|
Subject string
|
|
HTML string
|
|
Text string
|
|
}
|
|
|
|
// Editor validates, previews and test-sends drafts with the mailer's own
|
|
// catalog, configuration, override source and driver, so a draft renders as
|
|
// the saved content would be sent.
|
|
type Editor struct {
|
|
m *mailer
|
|
}
|
|
|
|
// EditorFrom returns the editor of the mailer postcard.Activate published
|
|
// on app.
|
|
func EditorFrom(app *backpack.App) (*Editor, bool) {
|
|
if app == nil {
|
|
return nil, false
|
|
}
|
|
got, ok := app.Lookup[Mailer]()
|
|
if !ok {
|
|
return nil, false
|
|
}
|
|
m, ok := got.(*mailer)
|
|
if !ok || m == nil || m.catalog == nil {
|
|
return nil, false
|
|
}
|
|
return &Editor{m: m}, true
|
|
}
|
|
|
|
// Catalog returns the mailer's catalog of file templates, layouts and
|
|
// partials.
|
|
func (e *Editor) Catalog() *Catalog {
|
|
return e.m.catalog
|
|
}
|
|
|
|
// Validate checks a draft the way a send would treat it: it parses it,
|
|
// renders it with sample values and placeholders and runs the safety checks.
|
|
// It returns nil for a draft that can be saved.
|
|
func (e *Editor) Validate(ctx context.Context, d Draft) *DraftError {
|
|
_, err := e.render(ctx, d)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
return draftErrorFor(d, err)
|
|
}
|
|
|
|
// Preview renders a draft: a template with its sample values and visible
|
|
// [name] placeholders, a layout around postcard's sample message, a partial
|
|
// called with placeholder arguments. Layouts, partials and other pieces the
|
|
// draft does not carry come from the mailer's override source, as in a send.
|
|
// A problem with the draft is returned as a *DraftError.
|
|
func (e *Editor) Preview(ctx context.Context, d Draft) (Preview, error) {
|
|
msg, err := e.render(ctx, d)
|
|
if err != nil {
|
|
return Preview{}, draftErrorFor(d, err)
|
|
}
|
|
return Preview{Subject: msg.Subject, HTML: msg.HTML, Text: msg.Text}, nil
|
|
}
|
|
|
|
// SendDraft renders a draft as Preview does and delivers it to the one
|
|
// address to, through the mailer's driver and from its sender address. A
|
|
// problem with the draft is returned as a *DraftError.
|
|
func (e *Editor) SendDraft(ctx context.Context, d Draft, to string) error {
|
|
m := e.m
|
|
if m.driver == nil {
|
|
return fmt.Errorf("postcard: driver is nil")
|
|
}
|
|
msg, err := e.render(ctx, d)
|
|
if err != nil {
|
|
return draftErrorFor(d, err)
|
|
}
|
|
msg.To, msg.Cc, msg.Bcc, msg.ReplyTo = []string{to}, nil, nil, ""
|
|
msg.From = m.opts.From
|
|
_, smtp := m.driver.(*SMTPDriver)
|
|
if err := validateRendered(msg, smtp); err != nil {
|
|
return err
|
|
}
|
|
if err := m.driver.Send(ctx, msg); err != nil {
|
|
return fmt.Errorf("postcard: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// render renders a draft through the catalog's render path, with the other
|
|
// overrides of the mailer's source applied.
|
|
func (e *Editor) render(ctx context.Context, d Draft) (RenderedMessage, error) {
|
|
m := e.m
|
|
// An empty template name: everything except a template override. The
|
|
// stored override of a template being edited is replaced by the draft.
|
|
ov := m.overrides(ctx, "")
|
|
ov.Template = nil
|
|
opts := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS}
|
|
switch d.Kind {
|
|
case KindTemplate:
|
|
return e.renderTemplate(d, ov, opts)
|
|
case KindLayout:
|
|
return e.renderLayout(d, ov, opts)
|
|
case KindPartial:
|
|
return e.renderPartial(d, ov, opts)
|
|
}
|
|
return RenderedMessage{}, fmt.Errorf("postcard: unsupported draft kind %q", d.Kind)
|
|
}
|
|
|
|
func (e *Editor) renderTemplate(d Draft, ov Overrides, opts renderOptions) (RenderedMessage, error) {
|
|
cat := e.m.catalog
|
|
t, err := cat.lookupTemplate(d.Name)
|
|
if err != nil {
|
|
return RenderedMessage{}, err
|
|
}
|
|
// Markdown drops raw HTML from a body, so such a tag would vanish from
|
|
// the mail without a word; say so when the draft is saved.
|
|
if loc := rawUnsafeTag.FindStringIndex(d.Body); loc != nil {
|
|
return RenderedMessage{}, &DraftError{Field: fieldBody, Rule: ruleUnsafe, Message: snippetAt(d.Body, loc)}
|
|
}
|
|
if d.Layout != "" {
|
|
if _, ok, _ := cat.layoutByCode(d.Layout, ov.Layouts); !ok {
|
|
return RenderedMessage{}, &DraftError{Field: fieldLayout, Rule: ruleLayout}
|
|
}
|
|
}
|
|
ov.Template = &TemplateOverride{Subject: d.Subject, Body: d.Body, Layout: d.Layout}
|
|
opts.overrides = ov
|
|
return cat.render(Message{
|
|
Template: d.Name,
|
|
Vars: placeholderVars(t.samples, d.Subject, d.Body),
|
|
}, opts)
|
|
}
|
|
|
|
// closingStyle matches what would end the style block a layout's CSS is
|
|
// placed in.
|
|
var closingStyle = regexp.MustCompile(`(?i)</\s*style`)
|
|
|
|
// draftLayoutCode is the code a layout draft without one is rendered under.
|
|
const draftLayoutCode = "draft"
|
|
|
|
func (e *Editor) renderLayout(d Draft, ov Overrides, opts renderOptions) (RenderedMessage, error) {
|
|
if loc := closingStyle.FindStringIndex(d.CSS); loc != nil {
|
|
return RenderedMessage{}, &DraftError{Field: fieldContentCSS, Rule: ruleUnsafe, Message: snippetAt(d.CSS, loc)}
|
|
}
|
|
var unsafe *unsafeError
|
|
if err := validateHTML(d.CSS); errors.As(err, &unsafe) {
|
|
return RenderedMessage{}, &DraftError{Field: fieldContentCSS, Rule: ruleUnsafe, Message: unsafe.snippet}
|
|
}
|
|
// A wrapper that does not parse is reported by the render below.
|
|
if uses, parsed := usesContent(d.HTML); parsed && !uses {
|
|
return RenderedMessage{}, &DraftError{Field: fieldContentHTML, Rule: ruleNoContent}
|
|
}
|
|
if uses, parsed := usesContent(d.Text); parsed && !uses {
|
|
return RenderedMessage{}, &DraftError{Field: fieldContentText, Rule: ruleNoContent}
|
|
}
|
|
code := d.Name
|
|
if code == "" {
|
|
code = draftLayoutCode
|
|
}
|
|
layouts := make(map[string]LayoutOverride, len(ov.Layouts)+1)
|
|
for k, v := range ov.Layouts {
|
|
layouts[k] = v
|
|
}
|
|
layouts[code] = LayoutOverride{Name: code, HTML: d.HTML, Text: d.Text, CSS: d.CSS}
|
|
ov.Layouts = layouts
|
|
opts.overrides = ov
|
|
sample := sampleMessage()
|
|
return e.m.catalog.renderFrom(Message{
|
|
Vars: placeholderVars(sample.samples, sample.subject, sample.body),
|
|
}, renderSource{name: sample.name, subject: sample.subject, body: sample.body, layout: code, layoutFromOverride: true}, opts)
|
|
}
|
|
|
|
func (e *Editor) renderPartial(d Draft, ov Overrides, opts renderOptions) (RenderedMessage, error) {
|
|
cat := e.m.catalog
|
|
p, ok := cat.lookupPartial(d.Name)
|
|
if !ok {
|
|
return RenderedMessage{}, &partialError{name: d.Name, msg: "unknown partial", unknown: true}
|
|
}
|
|
partials := make(map[string]PartialOverride, len(ov.Partials)+1)
|
|
for k, v := range ov.Partials {
|
|
partials[k] = v
|
|
}
|
|
partials[d.Name] = PartialOverride{HTML: d.HTML, Text: d.Text}
|
|
ov.Partials = partials
|
|
opts.overrides = ov
|
|
|
|
// A message that is one call of the partial, with a placeholder for
|
|
// every argument its sections read.
|
|
args := placeholderVars(nil, d.HTML, d.Text)
|
|
keys := make([]string, 0, len(args))
|
|
for key := range args {
|
|
keys = append(keys, key)
|
|
}
|
|
sort.Strings(keys)
|
|
var body strings.Builder
|
|
body.WriteString("{{ partial " + strconv.Quote(d.Name))
|
|
for _, key := range keys {
|
|
body.WriteString(" " + strconv.Quote(key) + " (index . " + strconv.Quote(key) + ")")
|
|
}
|
|
body.WriteString(" }}")
|
|
msg, err := cat.renderFrom(Message{Vars: args}, renderSource{name: d.Name + ".preview", body: body.String()}, opts)
|
|
if err != nil {
|
|
return RenderedMessage{}, err
|
|
}
|
|
msg.Subject = p.headerName
|
|
if msg.Subject == "" {
|
|
msg.Subject = p.name
|
|
}
|
|
return msg, nil
|
|
}
|
|
|
|
// usesContent reports whether a layout wrapper reads .Content, and whether
|
|
// the wrapper parsed at all.
|
|
func usesContent(src string) (uses, parsed bool) {
|
|
tree := parse.New("content")
|
|
tree.Mode = parse.SkipFuncCheck
|
|
if _, err := tree.Parse(src, "", "", map[string]*parse.Tree{}); err != nil || tree.Root == nil {
|
|
return false, false
|
|
}
|
|
return nodeUsesContent(tree.Root), true
|
|
}
|
|
|
|
func nodeUsesContent(node parse.Node) bool {
|
|
switch n := node.(type) {
|
|
case *parse.ListNode:
|
|
if n == nil {
|
|
return false
|
|
}
|
|
for _, child := range n.Nodes {
|
|
if nodeUsesContent(child) {
|
|
return true
|
|
}
|
|
}
|
|
case *parse.ActionNode:
|
|
return nodeUsesContent(n.Pipe)
|
|
case *parse.PipeNode:
|
|
if n == nil {
|
|
return false
|
|
}
|
|
for _, cmd := range n.Cmds {
|
|
if nodeUsesContent(cmd) {
|
|
return true
|
|
}
|
|
}
|
|
case *parse.CommandNode:
|
|
for _, arg := range n.Args {
|
|
if nodeUsesContent(arg) {
|
|
return true
|
|
}
|
|
}
|
|
case *parse.FieldNode:
|
|
return len(n.Ident) > 0 && n.Ident[0] == "Content"
|
|
case *parse.VariableNode:
|
|
return len(n.Ident) > 1 && n.Ident[0] == "$" && n.Ident[1] == "Content"
|
|
case *parse.ChainNode:
|
|
return nodeUsesContent(n.Node)
|
|
case *parse.IfNode:
|
|
return nodeUsesContent(n.Pipe) || nodeUsesContent(n.List) || nodeUsesContent(n.ElseList)
|
|
case *parse.WithNode:
|
|
return nodeUsesContent(n.Pipe) || nodeUsesContent(n.List) || nodeUsesContent(n.ElseList)
|
|
case *parse.RangeNode:
|
|
return nodeUsesContent(n.Pipe) || nodeUsesContent(n.List) || nodeUsesContent(n.ElseList)
|
|
case *parse.TemplateNode:
|
|
return nodeUsesContent(n.Pipe)
|
|
}
|
|
return false
|
|
}
|
|
|
|
// draftErrorFor turns a failed render of d into the field and the rule an
|
|
// admin form shows. The message keeps only what the template parser, the
|
|
// renderer or the safety check said.
|
|
func draftErrorFor(d Draft, err error) *DraftError {
|
|
var de *DraftError
|
|
if errors.As(err, &de) {
|
|
return de
|
|
}
|
|
part := ""
|
|
var re *renderError
|
|
if errors.As(err, &re) {
|
|
part = re.part
|
|
}
|
|
// The innermost template error names the template that failed: a
|
|
// partial's section inside a body, for example.
|
|
var inner *tmplError
|
|
for cur := err; cur != nil; cur = errors.Unwrap(cur) {
|
|
if te, ok := cur.(*tmplError); ok {
|
|
inner = te
|
|
}
|
|
}
|
|
out := &DraftError{Field: draftField(d, part, inner)}
|
|
var pe *partialError
|
|
var ue *unsafeError
|
|
switch {
|
|
case errors.Is(err, errSubjectLine):
|
|
out.Field, out.Rule = fieldSubject, ruleSubjectLine
|
|
case errors.As(err, &pe) && pe.unknown:
|
|
out.Rule, out.Name = rulePartial, pe.name
|
|
case errors.As(err, &ue):
|
|
out.Rule, out.Message = ruleUnsafe, ue.snippet
|
|
case inner != nil:
|
|
out.Rule = ruleRender
|
|
if inner.parse {
|
|
out.Rule = ruleParse
|
|
}
|
|
out.Message = templateMessage(inner)
|
|
default:
|
|
out.Rule, out.Message = ruleRender, scrubMessage(err.Error())
|
|
}
|
|
return out
|
|
}
|
|
|
|
// draftField returns the form field a failure in part of the message
|
|
// belongs to for a draft of d's kind.
|
|
func draftField(d Draft, part string, inner *tmplError) string {
|
|
switch d.Kind {
|
|
case KindTemplate:
|
|
switch part {
|
|
case partSubject:
|
|
return fieldSubject
|
|
case partLayout, partLayoutText, partLayoutHTML:
|
|
return fieldLayout
|
|
}
|
|
return fieldBody
|
|
case KindLayout:
|
|
if part == partLayoutText {
|
|
return fieldContentText
|
|
}
|
|
return fieldContentHTML
|
|
case KindPartial:
|
|
if inner != nil && inner.name == d.Name+".text" {
|
|
return fieldContentText
|
|
}
|
|
return fieldContentHTML
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// templateMessage is a template error without the template's name: the
|
|
// line, then what the template package reported.
|
|
func templateMessage(te *tmplError) string {
|
|
msg := te.err.Error()
|
|
for _, prefix := range []string{"template: ", "html/template:"} {
|
|
msg = strings.TrimPrefix(msg, prefix)
|
|
}
|
|
if rest, ok := strings.CutPrefix(msg, te.name+":"); ok {
|
|
msg = strings.TrimSpace(rest)
|
|
if msg != "" && msg[0] >= '0' && msg[0] <= '9' {
|
|
msg = "line " + msg
|
|
}
|
|
}
|
|
msg = strings.Replace(msg, `executing "`+te.name+`" `, "", 1)
|
|
return scrubMessage(msg)
|
|
}
|
|
|
|
// scrubMessage drops the package prefixes from an error text.
|
|
func scrubMessage(msg string) string {
|
|
msg = strings.ReplaceAll(msg, "postcard: ", "")
|
|
msg = strings.ReplaceAll(msg, "html/template:", "")
|
|
return strings.TrimSpace(strings.ReplaceAll(msg, "template: ", ""))
|
|
}
|
|
|
|
var (
|
|
sampleOnce sync.Once
|
|
sampleParsed *parsedTemplate
|
|
)
|
|
|
|
// sampleMessage is the message a layout draft is previewed around. It is
|
|
// not a registered template: nothing can send it.
|
|
func sampleMessage() *parsedTemplate {
|
|
sampleOnce.Do(func() {
|
|
raw, err := builtinAssets.ReadFile("assets/sample.htm")
|
|
if err != nil {
|
|
panic("postcard: sample message: " + err.Error())
|
|
}
|
|
sampleParsed, err = parseTemplateFile("postcard::mail.sample", builtinPluginID, string(raw))
|
|
if err != nil {
|
|
panic("postcard: sample message: " + err.Error())
|
|
}
|
|
})
|
|
return sampleParsed
|
|
}
|