From 38f59c283a72668f7802bb3086233e187f29ecf1 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Thu, 29 Jun 2023 09:38:08 +0300 Subject: add notify.go --- internal/config/config.go | 3 +++ internal/quorum/notify.go | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 internal/quorum/notify.go (limited to 'internal') diff --git a/internal/config/config.go b/internal/config/config.go index 2f8c62b..cb144f3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -19,6 +19,9 @@ type Config struct { MyID string `json:"MyID,omitempty"` RelaxedMode bool `json:"RelaxedMode,omitempty"` nodeNumberCache map[string]int + EmailTo string `json:"EmailTo,omitempty"` + EmailFrom string `json:"EmailFrom,omitempty"` + SMTPServer string `json:"SMTPServer,omitempty"` } func New(configFile string) (Config, error) { diff --git a/internal/quorum/notify.go b/internal/quorum/notify.go new file mode 100644 index 0000000..b6e6b5d --- /dev/null +++ b/internal/quorum/notify.go @@ -0,0 +1,50 @@ +package quorum + +import ( + "fmt" + "log" + "net/smtp" + + "codeberg.org/snonux/gorum/internal/config" +) + +func notifyEnabled(conf config.Config) bool { + return conf.EmailFrom != "" && conf.EmailTo != "" && conf.SMTPServer != "" +} + +func notify(conf config.Config, subject, body string) error { + if !notifyEnabled(conf) { + return nil + } + + log.Println("notify", subject, body) + + headers := map[string]string{ + "From": conf.EmailFrom, + "To": conf.EmailTo, + "Subject": subject, + "MIME-Version": "1.0", + "Content-Type": "text/plain; charset=\"utf-8\"", + } + + header := "" + for k, v := range headers { + header += fmt.Sprintf("%s: %s\r\n", k, v) + } + + message := header + "\r\n" + body + log.Println("Using SMTP server", conf.SMTPServer) + + return smtp.SendMail(conf.SMTPServer, nil, conf.EmailFrom, + []string{conf.EmailTo}, []byte(message)) +} + +func notifyError(conf config.Config, err error) { + if !notifyEnabled(conf) { + return + } + + if err := notify(conf, fmt.Sprintf("GORUM: An error occured: %v", err), err.Error()); err != nil { + log.Println("error: ", err) + } +} -- cgit v1.2.3