|
|
|
@@ -38,6 +38,7 @@ type Settings struct {
|
|
|
|
|
Username string `json:"username"`
|
|
|
|
|
From string `json:"from"`
|
|
|
|
|
Recipients []string `json:"recipients"`
|
|
|
|
|
Cc []string `json:"cc_recipients"`
|
|
|
|
|
Weekday int `json:"weekday"`
|
|
|
|
|
Hour int `json:"hour"`
|
|
|
|
|
Enabled bool `json:"enabled"`
|
|
|
|
@@ -56,6 +57,7 @@ type SettingsInput struct {
|
|
|
|
|
ClearPassword bool `json:"clear_password"`
|
|
|
|
|
From string `json:"from"`
|
|
|
|
|
Recipients []string `json:"recipients"`
|
|
|
|
|
Cc []string `json:"cc_recipients"`
|
|
|
|
|
Weekday int `json:"weekday"`
|
|
|
|
|
Hour int `json:"hour"`
|
|
|
|
|
Enabled bool `json:"enabled"`
|
|
|
|
@@ -63,6 +65,7 @@ type SettingsInput struct {
|
|
|
|
|
|
|
|
|
|
type Confirmation struct {
|
|
|
|
|
Week string `json:"week"`
|
|
|
|
|
HasImage bool `json:"has_image"`
|
|
|
|
|
DraftRevision int64 `json:"draft_revision"`
|
|
|
|
|
BodySHA256 string `json:"body_sha256"`
|
|
|
|
|
ConfirmedBy string `json:"confirmed_by"`
|
|
|
|
@@ -79,12 +82,23 @@ type Send struct {
|
|
|
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// InlineImage is embedded with a Content-ID so clients show it inside the body
|
|
|
|
|
// instead of as a detached attachment.
|
|
|
|
|
type InlineImage struct {
|
|
|
|
|
Name string
|
|
|
|
|
ContentType string
|
|
|
|
|
CID string
|
|
|
|
|
Bytes []byte
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type Message struct {
|
|
|
|
|
To []string
|
|
|
|
|
Cc []string
|
|
|
|
|
From string
|
|
|
|
|
Subject string
|
|
|
|
|
HTML string
|
|
|
|
|
Text string
|
|
|
|
|
Images []InlineImage
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mailer is the only outbound dependency; tests substitute it to prove the exact wire payload.
|
|
|
|
@@ -193,6 +207,20 @@ func normalize(input SettingsInput) (SettingsInput, error) {
|
|
|
|
|
recipients = append(recipients, address)
|
|
|
|
|
}
|
|
|
|
|
input.Recipients = recipients
|
|
|
|
|
cc := make([]string, 0, len(input.Cc))
|
|
|
|
|
for _, raw := range input.Cc {
|
|
|
|
|
address := strings.TrimSpace(raw)
|
|
|
|
|
if address == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
// A copy that is also a primary recipient would receive the mail twice.
|
|
|
|
|
if !validAddress(address) || seen[strings.ToLower(address)] {
|
|
|
|
|
return input, ErrInvalid
|
|
|
|
|
}
|
|
|
|
|
seen[strings.ToLower(address)] = true
|
|
|
|
|
cc = append(cc, address)
|
|
|
|
|
}
|
|
|
|
|
input.Cc = cc
|
|
|
|
|
if input.Host != "" && !strings.Contains(input.Host, " ") && !strings.Contains(input.Host, "/") {
|
|
|
|
|
if _, err := net.LookupHost(input.Host); err != nil {
|
|
|
|
|
// A host that does not resolve yet stays a validation error, not a silent no-op.
|
|
|
|
@@ -217,13 +245,13 @@ func normalize(input SettingsInput) (SettingsInput, error) {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *Store) ReadSettings(ctx context.Context) (Settings, error) {
|
|
|
|
|
out := Settings{Port: 465, Weekday: 1, Hour: 9, Recipients: []string{}}
|
|
|
|
|
out := Settings{Port: 465, Weekday: 1, Hour: 9, Recipients: []string{}, Cc: []string{}}
|
|
|
|
|
if !s.valid() {
|
|
|
|
|
return out, ErrUnavailable
|
|
|
|
|
}
|
|
|
|
|
var sealed []byte
|
|
|
|
|
err := s.pool.QueryRow(ctx, `SELECT smtp_host,smtp_port,smtp_username,smtp_password_sealed,from_address,recipients,send_weekday,send_hour,enabled,revision,updated_by,updated_at FROM qa_weekly_email_settings WHERE tenant_key=$1`, s.tenant).
|
|
|
|
|
Scan(&out.Host, &out.Port, &out.Username, &sealed, &out.From, &out.Recipients, &out.Weekday, &out.Hour, &out.Enabled, &out.Revision, &out.UpdatedBy, &out.UpdatedAt)
|
|
|
|
|
err := s.pool.QueryRow(ctx, `SELECT smtp_host,smtp_port,smtp_username,smtp_password_sealed,from_address,recipients,cc_recipients,send_weekday,send_hour,enabled,revision,updated_by,updated_at FROM qa_weekly_email_settings WHERE tenant_key=$1`, s.tenant).
|
|
|
|
|
Scan(&out.Host, &out.Port, &out.Username, &sealed, &out.From, &out.Recipients, &out.Cc, &out.Weekday, &out.Hour, &out.Enabled, &out.Revision, &out.UpdatedBy, &out.UpdatedAt)
|
|
|
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
|
|
|
return out, nil
|
|
|
|
|
}
|
|
|
|
@@ -233,6 +261,9 @@ func (s *Store) ReadSettings(ctx context.Context) (Settings, error) {
|
|
|
|
|
if out.Recipients == nil {
|
|
|
|
|
out.Recipients = []string{}
|
|
|
|
|
}
|
|
|
|
|
if out.Cc == nil {
|
|
|
|
|
out.Cc = []string{}
|
|
|
|
|
}
|
|
|
|
|
out.HasPassword = len(sealed) > 0
|
|
|
|
|
return out, nil
|
|
|
|
|
}
|
|
|
|
@@ -273,10 +304,10 @@ func (s *Store) SaveSettings(ctx context.Context, actor string, input SettingsIn
|
|
|
|
|
return Settings{}, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if _, err = tx.Exec(ctx, `INSERT INTO qa_weekly_email_settings(tenant_key,smtp_host,smtp_port,smtp_username,smtp_password_sealed,from_address,recipients,send_weekday,send_hour,enabled,revision,updated_by,updated_at)
|
|
|
|
|
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,now())
|
|
|
|
|
ON CONFLICT (tenant_key) DO UPDATE SET smtp_host=excluded.smtp_host,smtp_port=excluded.smtp_port,smtp_username=excluded.smtp_username,smtp_password_sealed=excluded.smtp_password_sealed,from_address=excluded.from_address,recipients=excluded.recipients,send_weekday=excluded.send_weekday,send_hour=excluded.send_hour,enabled=excluded.enabled,revision=excluded.revision,updated_by=excluded.updated_by,updated_at=now()`,
|
|
|
|
|
s.tenant, normalized.Host, normalized.Port, normalized.Username, sealed, normalized.From, normalized.Recipients, normalized.Weekday, normalized.Hour, normalized.Enabled, next, actor); err != nil {
|
|
|
|
|
if _, err = tx.Exec(ctx, `INSERT INTO qa_weekly_email_settings(tenant_key,smtp_host,smtp_port,smtp_username,smtp_password_sealed,from_address,recipients,cc_recipients,send_weekday,send_hour,enabled,revision,updated_by,updated_at)
|
|
|
|
|
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,now())
|
|
|
|
|
ON CONFLICT (tenant_key) DO UPDATE SET smtp_host=excluded.smtp_host,smtp_port=excluded.smtp_port,smtp_username=excluded.smtp_username,smtp_password_sealed=excluded.smtp_password_sealed,from_address=excluded.from_address,recipients=excluded.recipients,cc_recipients=excluded.cc_recipients,send_weekday=excluded.send_weekday,send_hour=excluded.send_hour,enabled=excluded.enabled,revision=excluded.revision,updated_by=excluded.updated_by,updated_at=now()`,
|
|
|
|
|
s.tenant, normalized.Host, normalized.Port, normalized.Username, sealed, normalized.From, normalized.Recipients, normalized.Cc, normalized.Weekday, normalized.Hour, normalized.Enabled, next, actor); err != nil {
|
|
|
|
|
return Settings{}, ErrUnavailable
|
|
|
|
|
}
|
|
|
|
|
if err = tx.Commit(ctx); err != nil {
|
|
|
|
@@ -339,10 +370,10 @@ func (s *Store) ReadConfirmation(ctx context.Context, week string) (*Confirmatio
|
|
|
|
|
var out Confirmation
|
|
|
|
|
var currentRevision int64
|
|
|
|
|
var currentMarkdown string
|
|
|
|
|
err := s.pool.QueryRow(ctx, `SELECT c.week,c.draft_revision,c.body_sha256,c.confirmed_by,c.confirmed_at,d.revision,d.markdown
|
|
|
|
|
err := s.pool.QueryRow(ctx, `SELECT c.week,c.draft_revision,c.body_sha256,c.confirmed_by,c.confirmed_at,d.revision,d.markdown,c.dashboard_png IS NOT NULL
|
|
|
|
|
FROM qa_weekly_confirmations c LEFT JOIN qa_ops_weekly_drafts d ON d.tenant_key=c.tenant_key AND d.week=c.week
|
|
|
|
|
WHERE c.tenant_key=$1 AND c.week=$2`, s.tenant, week).
|
|
|
|
|
Scan(&out.Week, &out.DraftRevision, &out.BodySHA256, &out.ConfirmedBy, &out.ConfirmedAt, ¤tRevision, ¤tMarkdown)
|
|
|
|
|
Scan(&out.Week, &out.DraftRevision, &out.BodySHA256, &out.ConfirmedBy, &out.ConfirmedAt, ¤tRevision, ¤tMarkdown, &out.HasImage)
|
|
|
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
@@ -473,6 +504,39 @@ func (s *Store) SendDue(ctx context.Context, now time.Time) (DueResult, error) {
|
|
|
|
|
return DueResult{State: "nothing_confirmed", Reason: "没有已确认且已结束的周报"}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SaveDashboardImage stores the dashboard PNG that belongs to the currently confirmed revision,
|
|
|
|
|
// so a later body edit (which invalidates the confirmation) never mails a stale chart.
|
|
|
|
|
func (s *Store) SaveDashboardImage(ctx context.Context, week string, png []byte) error {
|
|
|
|
|
if !s.valid() || strings.TrimSpace(week) == "" || len(png) < 8 || len(png) > 8<<20 {
|
|
|
|
|
return ErrInvalid
|
|
|
|
|
}
|
|
|
|
|
if string(png[:8]) != "\x89PNG\r\n\x1a\n" {
|
|
|
|
|
return ErrInvalid
|
|
|
|
|
}
|
|
|
|
|
sum := sha256.Sum256(png)
|
|
|
|
|
tag, err := s.pool.Exec(ctx, `UPDATE qa_weekly_confirmations SET dashboard_png=$2,dashboard_sha256=$3,dashboard_saved_at=now()
|
|
|
|
|
WHERE tenant_key=$1 AND week=$4`, s.tenant, png, hex.EncodeToString(sum[:]), week)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return ErrUnavailable
|
|
|
|
|
}
|
|
|
|
|
if tag.RowsAffected() == 0 {
|
|
|
|
|
return ErrInvalid
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *Store) dashboardImage(ctx context.Context, week string) ([]byte, error) {
|
|
|
|
|
var png []byte
|
|
|
|
|
err := s.pool.QueryRow(ctx, `SELECT dashboard_png FROM qa_weekly_confirmations WHERE tenant_key=$1 AND week=$2`, s.tenant, week).Scan(&png)
|
|
|
|
|
if errors.Is(err, pgx.ErrNoRows) || len(png) == 0 {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, ErrUnavailable
|
|
|
|
|
}
|
|
|
|
|
return png, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestSend mails a saved weekly body right now so an operator can verify the mailbox
|
|
|
|
|
// before any scheduled run. It never writes a send receipt and never marks a week as sent.
|
|
|
|
|
func (s *Store) TestSend(ctx context.Context, week string) (string, error) {
|
|
|
|
@@ -501,8 +565,12 @@ func (s *Store) TestSend(ctx context.Context, week string) (string, error) {
|
|
|
|
|
return "", ErrInvalid
|
|
|
|
|
}
|
|
|
|
|
html, text := renderReport(markdown)
|
|
|
|
|
images, err := s.inlineImages(ctx, week, &html)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
return s.mailer.Send(ctx, SMTPConfig{Host: settings.Host, Port: settings.Port, Username: settings.Username, Password: password},
|
|
|
|
|
Message{To: settings.Recipients, From: settings.From, Subject: fmt.Sprintf("知识库周报 %s(测试发送)", week), HTML: html, Text: text})
|
|
|
|
|
Message{To: settings.Recipients, Cc: settings.Cc, From: settings.From, Subject: fmt.Sprintf("知识库周报 %s(测试发送)", week), HTML: html, Text: text, Images: images})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *Store) send(ctx context.Context, settings Settings, week string, revision int64, markdown string, now time.Time) (DueResult, error) {
|
|
|
|
@@ -511,6 +579,10 @@ func (s *Store) send(ctx context.Context, settings Settings, week string, revisi
|
|
|
|
|
return DueResult{State: "blocked", Week: week, Reason: "SMTP 密码未配置或无法解密"}, nil
|
|
|
|
|
}
|
|
|
|
|
html, text := renderReport(markdown)
|
|
|
|
|
images, err := s.inlineImages(ctx, week, &html)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return DueResult{}, err
|
|
|
|
|
}
|
|
|
|
|
subject := fmt.Sprintf("知识库周报 %s", week)
|
|
|
|
|
var sendID string
|
|
|
|
|
err = s.pool.QueryRow(ctx, `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,created_at,updated_at)
|
|
|
|
@@ -522,7 +594,7 @@ func (s *Store) send(ctx context.Context, settings Settings, week string, revisi
|
|
|
|
|
return DueResult{}, ErrUnavailable
|
|
|
|
|
}
|
|
|
|
|
messageID, sendErr := s.mailer.Send(ctx, SMTPConfig{Host: settings.Host, Port: settings.Port, Username: settings.Username, Password: password},
|
|
|
|
|
Message{To: settings.Recipients, From: settings.From, Subject: subject, HTML: html, Text: text})
|
|
|
|
|
Message{To: settings.Recipients, Cc: settings.Cc, From: settings.From, Subject: subject, HTML: html, Text: text, Images: images})
|
|
|
|
|
if sendErr != nil {
|
|
|
|
|
reason := sendErr.Error()
|
|
|
|
|
if len(reason) > 400 {
|
|
|
|
@@ -537,6 +609,20 @@ func (s *Store) send(ctx context.Context, settings Settings, week string, revisi
|
|
|
|
|
return DueResult{State: "sent", Week: week, SentAt: now}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const dashboardImageCID = "weekly-dashboard@knowledge-governance"
|
|
|
|
|
|
|
|
|
|
// inlineImages appends the confirmed dashboard chart to the end of the HTML body.
|
|
|
|
|
func (s *Store) inlineImages(ctx context.Context, week string, html *string) ([]InlineImage, error) {
|
|
|
|
|
png, err := s.dashboardImage(ctx, week)
|
|
|
|
|
if err != nil || len(png) == 0 {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
footer := `<h2 style="font-size:17px;margin-top:24px;color:#17324d">统计看板</h2>` +
|
|
|
|
|
`<p><img src="cid:` + dashboardImageCID + `" alt="问题统计看板" style="max-width:100%;height:auto;border:1px solid #e5e7eb;border-radius:8px"></p>`
|
|
|
|
|
*html = strings.Replace(*html, "</body>", footer+"</body>", 1)
|
|
|
|
|
return []InlineImage{{Name: "dashboard.png", ContentType: "image/png", CID: dashboardImageCID, Bytes: png}}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *Store) password(ctx context.Context, revision int64) (string, error) {
|
|
|
|
|
var sealed []byte
|
|
|
|
|
if err := s.pool.QueryRow(ctx, `SELECT smtp_password_sealed FROM qa_weekly_email_settings WHERE tenant_key=$1`, s.tenant).Scan(&sealed); err != nil {
|
|
|
|
@@ -600,7 +686,7 @@ func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string
|
|
|
|
|
if err := client.Mail(msg.From); err != nil {
|
|
|
|
|
return "", fmt.Errorf("smtp MAIL FROM 被拒: %w", err)
|
|
|
|
|
}
|
|
|
|
|
for _, to := range msg.To {
|
|
|
|
|
for _, to := range append(append([]string{}, msg.To...), msg.Cc...) {
|
|
|
|
|
if err := client.Rcpt(to); err != nil {
|
|
|
|
|
return "", fmt.Errorf("smtp RCPT 被拒: %w", err)
|
|
|
|
|
}
|
|
|
|
@@ -638,16 +724,39 @@ func buildMIME(msg Message, messageID, boundary string) string {
|
|
|
|
|
var body strings.Builder
|
|
|
|
|
body.WriteString("From: " + msg.From + "\r\n")
|
|
|
|
|
body.WriteString("To: " + strings.Join(msg.To, ", ") + "\r\n")
|
|
|
|
|
if len(msg.Cc) > 0 {
|
|
|
|
|
body.WriteString("Cc: " + strings.Join(msg.Cc, ", ") + "\r\n")
|
|
|
|
|
}
|
|
|
|
|
body.WriteString("Subject: " + mimeSubject(msg.Subject) + "\r\n")
|
|
|
|
|
body.WriteString("Date: " + time.Now().Format(time.RFC1123Z) + "\r\n")
|
|
|
|
|
body.WriteString("Message-ID: " + messageID + "\r\n")
|
|
|
|
|
body.WriteString("MIME-Version: 1.0\r\n")
|
|
|
|
|
body.WriteString("Content-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n\r\n")
|
|
|
|
|
body.WriteString("--" + boundary + "\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n")
|
|
|
|
|
body.WriteString(base64Lines(msg.Text))
|
|
|
|
|
body.WriteString("\r\n--" + boundary + "\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n")
|
|
|
|
|
body.WriteString(base64Lines(msg.HTML))
|
|
|
|
|
body.WriteString("\r\n--" + boundary + "--\r\n")
|
|
|
|
|
alternative := func(w *strings.Builder) {
|
|
|
|
|
w.WriteString("--" + boundary + "\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n")
|
|
|
|
|
w.WriteString(base64Lines(msg.Text))
|
|
|
|
|
w.WriteString("\r\n--" + boundary + "\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n")
|
|
|
|
|
w.WriteString(base64Lines(msg.HTML))
|
|
|
|
|
w.WriteString("\r\n--" + boundary + "--\r\n")
|
|
|
|
|
}
|
|
|
|
|
if len(msg.Images) == 0 {
|
|
|
|
|
body.WriteString("Content-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n\r\n")
|
|
|
|
|
alternative(&body)
|
|
|
|
|
return body.String()
|
|
|
|
|
}
|
|
|
|
|
// Images live in a multipart/related wrapper so "cid:" references render inline,
|
|
|
|
|
// after the text and HTML alternatives.
|
|
|
|
|
related := boundary + "-related"
|
|
|
|
|
body.WriteString("Content-Type: multipart/related; boundary=\"" + related + "\"; type=\"multipart/alternative\"\r\n\r\n")
|
|
|
|
|
body.WriteString("--" + related + "\r\nContent-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n\r\n")
|
|
|
|
|
alternative(&body)
|
|
|
|
|
for _, image := range msg.Images {
|
|
|
|
|
body.WriteString("--" + related + "\r\nContent-Type: " + image.ContentType + "; name=\"" + image.Name + "\"\r\n")
|
|
|
|
|
body.WriteString("Content-Transfer-Encoding: base64\r\nContent-ID: <" + image.CID + ">\r\n")
|
|
|
|
|
body.WriteString("Content-Disposition: inline; filename=\"" + image.Name + "\"\r\n\r\n")
|
|
|
|
|
body.WriteString(base64Lines(string(image.Bytes)))
|
|
|
|
|
body.WriteString("\r\n")
|
|
|
|
|
}
|
|
|
|
|
body.WriteString("--" + related + "--\r\n")
|
|
|
|
|
return body.String()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|