diff options
Diffstat (limited to 'internal/notifier')
| -rw-r--r-- | internal/notifier/email.go | 41 | ||||
| -rw-r--r-- | internal/notifier/notifier.go | 60 |
2 files changed, 101 insertions, 0 deletions
diff --git a/internal/notifier/email.go b/internal/notifier/email.go new file mode 100644 index 0000000..4ce8d69 --- /dev/null +++ b/internal/notifier/email.go @@ -0,0 +1,41 @@ +package notifier + +import ( + "fmt" + "log" + "net/smtp" + + "codeberg.org/snonux/gorum/internal/config" +) + +func emailNotify(conf config.Config, subject, body string) error { + if !conf.EmailNotifycationEnabled() { + 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 emailNotifyError(conf config.Config, err error) { + if err := emailNotify(conf, fmt.Sprintf("GORUM: An error occured: %v", err), err.Error()); err != nil { + log.Println("error:", err) + } +} diff --git a/internal/notifier/notifier.go b/internal/notifier/notifier.go new file mode 100644 index 0000000..24447a9 --- /dev/null +++ b/internal/notifier/notifier.go @@ -0,0 +1,60 @@ +package notifier + +import ( + "context" + "fmt" + "os" + + "codeberg.org/snonux/gorum/internal/config" +) + +type Notifier struct{} + +func New() Notifier { + return Notifier{} +} + +func (notifier Notifier) Start(ctx context.Context, conf config.Config, scoreCh <-chan string) { + go func() { + for scoresStr := range scoreCh { + if err := notifier.persist(conf, scoresStr); err != nil { + emailNotifyError(conf, err) + } + } + }() +} + +func (notifier Notifier) persist(conf config.Config, scoresStr string) error { + if err := emailNotify(conf, "GORUM: Quorum changed", scoresStr); err != nil { + return err + } + + if _, err := os.Stat(conf.StateDir); os.IsNotExist(err) { + if err := os.MkdirAll(conf.StateDir, 0755); err != nil { + return err + } + } + + return writeFileViaTmp(fmt.Sprintf("%s/%s", conf.StateDir, conf.ScoreFile), scoresStr) +} + +// Create tmp file first, and then, once written, rename it. +func writeFileViaTmp(filePath, content string) error { + tmpFilePath := fmt.Sprintf("%s.tmp", filePath) + + fd, err := os.Create(tmpFilePath) + if err != nil { + return err + } + defer fd.Close() + + if _, err := fd.WriteString(content); err != nil { + return err + } + + if err := fd.Sync(); err != nil { + return err + } + + return os.Rename(tmpFilePath, filePath) +} |
