diff options
Diffstat (limited to 'backend/internal/alerts')
| -rw-r--r-- | backend/internal/alerts/alerts.go | 113 | ||||
| -rw-r--r-- | backend/internal/alerts/smtp.go | 85 |
2 files changed, 198 insertions, 0 deletions
diff --git a/backend/internal/alerts/alerts.go b/backend/internal/alerts/alerts.go new file mode 100644 index 0000000..44d4a50 --- /dev/null +++ b/backend/internal/alerts/alerts.go @@ -0,0 +1,113 @@ +package alerts + +import ( + "bytes" + "encoding/json" + "fmt" + "log" + "net/http" + "time" + + "yaum/internal/model" +) + +type SMTPConfig struct { + Host string + Port int + Username string + Password string + From string +} + +func SendDiscord(webhookURL string, svc model.Service, hb model.Heartbeat, wasUp bool) { + color := 15548997 + title := "🔴 Site Fora do Ar" + if hb.IsUp { + color = 5763719 + title = "🟢 Site Recuperado" + } + + desc := "o servico caiu" + fields := []map[string]any{ + {"name": "URL", "value": svc.URL, "inline": true}, + {"name": "Codigo", "value": fmt.Sprintf("`%d`", hb.StatusCode), "inline": true}, + {"name": "Tempo", "value": fmt.Sprintf("%dms", hb.ResponseTimeMs), "inline": true}, + } + if hb.ErrorMessage != "" { + fields = append(fields, map[string]any{"name": "Erro", "value": hb.ErrorMessage, "inline": false}) + } + if hb.IsUp { + desc = "o servico voltou" + } + + payload := map[string]any{ + "embeds": []map[string]any{ + { + "title": title + " | " + svc.Name, + "description": desc, + "color": color, + "fields": fields, + "footer": map[string]any{"text": "YAUM — Yet Another Uptime Monitor"}, + "timestamp": hb.TestedAt.Format(time.RFC3339), + }, + }, + "username": "YAUM", + } + + data, _ := json.Marshal(payload) + + client := &http.Client{Timeout: 10 * time.Second} + resp, err := client.Post(webhookURL, "application/json", bytes.NewReader(data)) + if err != nil { + log.Printf("[alerta:discord] erro ao enviar: %v", err) + return + } + resp.Body.Close() + if resp.StatusCode >= 400 { + log.Printf("[alerta:discord] webhook retornou %d", resp.StatusCode) + return + } + log.Printf("[alerta:discord] webhook enviado para '%s'", svc.Name) +} + +func SendEmail(svc model.Service, hb model.Heartbeat, wasUp bool, cfg *SMTPConfig) { + if cfg == nil || cfg.From == "" || cfg.Host == "" { + log.Println("[alerta:email] smtp nao configurado — pulando") + return + } + + statusEmoji := "🟢" + statusTxt := "UP" + subject := "[YAUM] Site Recuperado: " + svc.Name + if !hb.IsUp { + statusEmoji = "🔴" + statusTxt = "DOWN" + subject = "[YAUM] Site Fora do Ar: " + svc.Name + } + + body := fmt.Sprintf(`YAUM — Yet Another Uptime Monitor + +%s Status: %s + +Servico: %s +URL: %s +Status HTTP: %d +Tempo de Resposta: %dms +Mensagem: %s +Testado em: %s +`, + statusEmoji, statusTxt, + svc.Name, svc.URL, hb.StatusCode, hb.ResponseTimeMs, hb.ErrorMessage, + hb.TestedAt.Format("2006-01-02 15:04:05 MST"), + ) + + if err := sendMail(hostPort(cfg.Host, cfg.Port), cfg.Username, cfg.Password, cfg.From, []string{svc.AlertEmail}, subject, body); err != nil { + log.Printf("[alerta:email] erro: %v", err) + return + } + log.Printf("[alerta:email] email enviado para %s", svc.AlertEmail) +} + +func hostPort(host string, port int) string { + return fmt.Sprintf("%s:%d", host, port) +} diff --git a/backend/internal/alerts/smtp.go b/backend/internal/alerts/smtp.go new file mode 100644 index 0000000..5bb1ba8 --- /dev/null +++ b/backend/internal/alerts/smtp.go @@ -0,0 +1,85 @@ +package alerts + +import ( + "crypto/tls" + "fmt" + "net/smtp" + "strings" +) + +func sendMail(addr, user, pass, from string, to []string, subject, body string) error { + host := addr + for i, c := range addr { + if c == ':' { + host = addr[:i] + break + } + } + + msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n%s", + from, strings.Join(to, ", "), subject, body) + + auth := newLoginAuth(user, pass) + + c, err := smtp.Dial(addr) + if err != nil { + return fmt.Errorf("dial: %w", err) + } + defer c.Close() + + if err := c.StartTLS(&tls.Config{ServerName: host}); err != nil { + return fmt.Errorf("starttls: %w", err) + } + + if user != "" { + if err := c.Auth(auth); err != nil { + return fmt.Errorf("auth: %w", err) + } + } + + if err := c.Mail(from); err != nil { + return fmt.Errorf("mail from: %w", err) + } + for _, addr := range to { + if err := c.Rcpt(addr); err != nil { + return fmt.Errorf("rcpt %s: %w", addr, err) + } + } + + w, err := c.Data() + if err != nil { + return fmt.Errorf("data: %w", err) + } + if _, err := fmt.Fprint(w, msg); err != nil { + return fmt.Errorf("write: %w", err) + } + if err := w.Close(); err != nil { + return fmt.Errorf("close: %w", err) + } + return c.Quit() +} + +type loginAuth struct { + user, pass string +} + +func newLoginAuth(user, pass string) smtp.Auth { + return &loginAuth{user, pass} +} + +func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { + return "LOGIN", []byte(a.user), nil +} + +func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) { + if more { + msg := string(fromServer) + switch { + case strings.EqualFold(msg, "Username:"): + return []byte(a.user), nil + case strings.EqualFold(msg, "Password:"): + return []byte(a.pass), nil + } + } + return nil, nil +} |