worker/clients/mailclient/utils.go

82 lines
1.6 KiB
Go
Raw Normal View History

2024-02-19 18:20:09 +00:00
package mailclient
import (
"crypto/rand"
2024-03-27 15:29:50 +00:00
"encoding/json"
2024-02-19 18:20:09 +00:00
"fmt"
2024-03-27 15:29:50 +00:00
"html/template"
2024-02-19 18:20:09 +00:00
"io"
2024-03-27 15:29:50 +00:00
"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/model"
2024-02-19 18:20:09 +00:00
)
type LineWriter struct {
w io.Writer
length int
}
func NewLineWriter(w io.Writer, length int) *LineWriter {
return &LineWriter{
w: w,
length: length,
}
}
func (r *LineWriter) Write(p []byte) (n int, err error) {
for i := 0; i < len(p); i += r.length {
end := i + r.length
if end > len(p) {
end = len(p) - 1
}
var chunk []byte
chunk = append(chunk, p[i:end]...)
if len(p) >= end+r.length {
chunk = append(chunk, []byte("\r\n")...)
}
addN, err := r.w.Write(chunk)
if err != nil {
return n, err
}
n += addN
}
return n, nil
}
func (r *LineWriter) WriteString(s string) (n int, err error) {
p := []byte(s)
return r.Write(p)
}
func (r *LineWriter) WriteFormatString(format string, a ...any) (n int, err error) {
p := []byte(fmt.Sprintf(format, a...))
return r.Write(p)
}
func randomBoundary() string {
var buf [30]byte
_, err := io.ReadFull(rand.Reader, buf[:])
if err != nil {
panic(err)
}
return fmt.Sprintf("%x", buf[:])
}
2024-03-27 15:29:50 +00:00
var tmplFuncs = template.FuncMap{
"renderImage": RenderImage,
}
func RenderImage(content string) template.HTML {
var res model.ImageContent
err := json.Unmarshal([]byte(content), &res)
if err != nil {
return template.HTML(fmt.Sprintf("%s", template.HTMLEscapeString(content)))
}
tpl := template.HTML(fmt.Sprintf("<td>%s<br><img class=\"image\" style=\"width:100%%; max-width:250px; max-height:250px\" src=\"%s\"/></td>", res.Description, res.Image))
fmt.Println(tpl)
return tpl
}