2023-09-24 18:24:16 +01:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
2023-10-09 20:31:41 +01:00
|
|
|
"errors"
|
|
|
|
"github.com/1f349/overlapfs"
|
2024-05-13 20:06:17 +01:00
|
|
|
"github.com/1f349/tulip/logger"
|
2023-10-09 20:31:41 +01:00
|
|
|
htmlTemplate "html/template"
|
2023-09-24 18:24:16 +01:00
|
|
|
"io"
|
2023-10-09 20:31:41 +01:00
|
|
|
"io/fs"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"sync"
|
|
|
|
textTemplate "text/template"
|
2023-09-24 18:24:16 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2023-10-09 20:31:41 +01:00
|
|
|
//go:embed *.go.html *.go.txt
|
2023-09-24 18:24:16 +01:00
|
|
|
embeddedTemplates embed.FS
|
2023-10-09 20:31:41 +01:00
|
|
|
mailHtmlTemplates *htmlTemplate.Template
|
|
|
|
mailTextTemplates *textTemplate.Template
|
|
|
|
loadOnce sync.Once
|
2023-09-24 18:24:16 +01:00
|
|
|
)
|
|
|
|
|
2023-10-09 20:31:41 +01:00
|
|
|
func LoadMailTemplates(wd string) (err error) {
|
|
|
|
loadOnce.Do(func() {
|
|
|
|
var o fs.FS = embeddedTemplates
|
|
|
|
if wd != "" {
|
|
|
|
mailDir := filepath.Join(wd, "mail-templates")
|
|
|
|
err = os.Mkdir(mailDir, os.ModePerm)
|
|
|
|
if err != nil && !errors.Is(err, os.ErrExist) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
wdFs := os.DirFS(mailDir)
|
|
|
|
o = overlapfs.OverlapFS{A: embeddedTemplates, B: wdFs}
|
|
|
|
}
|
|
|
|
mailHtmlTemplates, err = htmlTemplate.New("mail").ParseFS(o, "*.go.html")
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
mailTextTemplates, err = textTemplate.New("mail").ParseFS(o, "*.go.txt")
|
|
|
|
})
|
2023-09-24 18:24:16 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-10-09 20:31:41 +01:00
|
|
|
func RenderMailTemplate(wrHtml, wrTxt io.Writer, name string, data any) {
|
|
|
|
err := mailHtmlTemplates.ExecuteTemplate(wrHtml, name+".go.html", data)
|
|
|
|
if err != nil {
|
2024-05-13 20:06:17 +01:00
|
|
|
logger.Logger.Warn("Failed to render mail html", "name", name, "err", err)
|
2023-10-09 20:31:41 +01:00
|
|
|
}
|
|
|
|
err = mailTextTemplates.ExecuteTemplate(wrTxt, name+".go.txt", data)
|
2023-09-24 18:24:16 +01:00
|
|
|
if err != nil {
|
2024-05-13 20:06:17 +01:00
|
|
|
logger.Logger.Warn("Failed to render mail text", "name", name, "err", err)
|
2023-09-24 18:24:16 +01:00
|
|
|
}
|
|
|
|
}
|