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 // DisableAutoInlineCSS is a layout draft's opt-out of CSS inlining. DisableAutoInlineCSS bool // Brand is a branding draft. Nil is the default brand. Brand *Brand } // The rules a DraftError reports. const ( ruleParse = "parse" ruleRender = "render" ruleUnsafe = "unsafe" ruleSubjectLine = "subject_line" ruleLayout = "layout" rulePartial = "partial" ruleNoContent = "no_content" ruleColour = "colour" ) // 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, the colour's column such as button_primary_bg for Branding. Field string // Rule is what failed: parse, render, unsafe, subject_line, layout, // partial, no_content or colour. 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, Branding as the sample message in the // default layout. Layouts, partials, Branding 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 := m.options(ov.Brand) switch d.Kind { case KindBrand: return e.renderBrand(d, ov, opts) 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 // A fallback-locale name renders the base file with its samples. t, err := cat.resolveTemplate(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)" + 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, DisableAutoInlineCSS: d.DisableAutoInlineCSS} 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 } // renderBrand renders the sample message in the default layout with the // draft's colours, logo and site name in place of the saved Branding. func (e *Editor) renderBrand(d Draft, ov Overrides, opts renderOptions) (RenderedMessage, error) { brand := DefaultBrand() if d.Brand != nil { brand = *d.Brand } css, err := CompileBrandCSS(brand) if err != nil { return RenderedMessage{}, err } opts.brandCSS, opts.logoURL = css, brand.LogoURL // An unsafe draft name is left out as a send would leave it out; the // Branding save is what refuses it. opts.siteName = e.m.layoutSiteName(&brand) 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}, opts) } // 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 } var colour *brandColourError if errors.As(err, &colour) { return &DraftError{Field: colour.column, Rule: ruleColour} } 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 }