1
0
mirror of https://github.com/axllent/mailpit.git synced 2025-03-19 21:28:07 +02:00
mailpit/internal/tools/snippets.go

45 lines
900 B
Go
Raw Normal View History

2023-10-05 17:01:13 +13:00
package tools
import (
"regexp"
"strings"
"github.com/axllent/mailpit/internal/html2text"
2023-10-05 17:01:13 +13:00
)
// CreateSnippet returns a message snippet. It will use the HTML version (if it exists)
// otherwise the text version.
2023-10-05 17:01:13 +13:00
func CreateSnippet(text, html string) string {
text = strings.TrimSpace(text)
html = strings.TrimSpace(html)
limit := 200
2023-10-05 17:01:13 +13:00
spaceRe := regexp.MustCompile(`\s+`)
if text == "" && html == "" {
return ""
}
if html != "" {
data := html2text.Strip(html, false)
2023-10-05 17:01:13 +13:00
if len(data) <= limit {
2023-10-05 17:01:13 +13:00
return data
}
return data[0:limit] + "..."
2023-10-05 17:01:13 +13:00
}
if text != "" {
// replace \uFEFF with space, see https://github.com/golang/go/issues/42274#issuecomment-1017258184
text = strings.ReplaceAll(text, string('\uFEFF'), " ")
text = strings.TrimSpace(spaceRe.ReplaceAllString(text, " "))
if len(text) <= limit {
2023-10-05 17:01:13 +13:00
return text
}
return text[0:limit] + "..."
2023-10-05 17:01:13 +13:00
}
return ""
}