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) }