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) 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 }