From 938523c18b1c4959dc0e7af6fd0c5e5dfdd462e7 Mon Sep 17 00:00:00 2001 From: Harvey Tindall Date: Sat, 20 Feb 2021 01:03:11 +0000 Subject: [PATCH] fix urls in custom email/announcements Uses a nasty algorithm found in stripmd.go to change all occurrences of '[linktext](link)' to just 'link' before passing to a decent markdown stripper. --- email.go | 3 +-- stripmd.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 stripmd.go diff --git a/email.go b/email.go index 90a8d21..6fd1873 100644 --- a/email.go +++ b/email.go @@ -18,7 +18,6 @@ import ( jEmail "github.com/jordan-wright/email" "github.com/knz/strtime" "github.com/mailgun/mailgun-go/v4" - stripmd "github.com/writeas/go-strip-markdown" ) // implements email sending, right now via smtp or mailgun. @@ -260,7 +259,7 @@ func (emailer *Emailer) constructTemplate(subject, md string, app *appContext) ( email := &Email{subject: subject} renderer := html.NewRenderer(html.RendererOptions{Flags: html.Smartypants}) html := markdown.ToHTML([]byte(md), nil, renderer) - text := strings.TrimPrefix(strings.TrimSuffix(stripmd.Strip(md), "

"), "

") + text := stripMarkdown(md) message := app.config.Section("email").Key("message").String() var err error email.html, email.text, err = emailer.construct(app, "template_email", "email_", map[string]interface{}{ diff --git a/stripmd.go b/stripmd.go new file mode 100644 index 0000000..c016cfa --- /dev/null +++ b/stripmd.go @@ -0,0 +1,53 @@ +package main + +import ( + "strings" + + stripmd "github.com/writeas/go-strip-markdown" +) + +func stripMarkdown(md string) string { + // Search for markdown-formatted urls, and replace them with just the url, then use a library to strip any traces of markdown. You'll need some eyebleach after this. + foundOpenSquare := false + openSquare := -1 + openBracket := -1 + closeBracket := -1 + openSquares := []int{} + closeBrackets := []int{} + links := []string{} + foundOpen := false + for i, c := range md { + if !foundOpenSquare && !foundOpen && c != '[' && c != ']' { + continue + } + if c == '[' { + foundOpenSquare = true + openSquare = i + } else if c == ']' { + if md[i+1] == '(' { + foundOpenSquare = false + foundOpen = true + openBracket = i + 1 + continue + } + } else if c == ')' { + closeBracket = i + openSquares = append(openSquares, openSquare) + closeBrackets = append(closeBrackets, closeBracket) + links = append(links, md[openBracket+1:closeBracket]) + openBracket = -1 + closeBracket = -1 + openSquare = -1 + foundOpenSquare = false + foundOpen = false + } + } + fullLinks := make([]string, len(openSquares)) + for i := range openSquares { + fullLinks[i] = md[openSquares[i] : closeBrackets[i]+1] + } + for i, _ := range openSquares { + md = strings.Replace(md, fullLinks[i], links[i], 1) + } + return strings.TrimPrefix(strings.TrimSuffix(stripmd.Strip(md), "

"), "

") +}