feat(notify): chat, push and paging providers
Slack, Discord, Microsoft Teams, Google Chat, Mattermost, Rocket.Chat, Telegram, Matrix, ntfy, Gotify, Pushover, Pushbullet, Signal (signal-cli REST API), PagerDuty and Opsgenie natively, and every service Apprise supports through an Apprise API server. Each provider declares its settings and how it sends; PagerDuty and Opsgenie pair trigger and resolve by incident. Requests go through the network guard, and errors name only the host, since URLs may carry tokens. Refs #92 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
b3e34613a3
commit
a0a67ec5f8
2 files changed
+481
No files matched your search
@@ -0,0 +1,347 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
||||
)
|
||||
|
||||
// Message is an incident event rendered for chat and push services.
|
||||
type Message struct {
|
||||
// Event is Opened, Resolved or Test.
|
||||
Event string
|
||||
Title string
|
||||
Body string
|
||||
// URL links to the monitor in the console.
|
||||
URL string
|
||||
// Key identifies the incident across its events, for services that
|
||||
// pair "opened" with "resolved" such as PagerDuty.
|
||||
Key uuid.UUID
|
||||
}
|
||||
|
||||
// Field is a setting of a provider. Secret fields are stored sealed and
|
||||
// never shown again.
|
||||
type Field struct {
|
||||
Name string
|
||||
Required bool
|
||||
Secret bool
|
||||
// Kind is "url", "text", "number" or "select".
|
||||
Kind string
|
||||
Options []string
|
||||
Default string
|
||||
}
|
||||
|
||||
// Provider delivers messages to one kind of service.
|
||||
type Provider struct {
|
||||
Type string
|
||||
Fields []Field
|
||||
send func(ctx context.Context, c *client, cfg map[string]string, m Message) error
|
||||
}
|
||||
|
||||
// Send delivers m with the settings in cfg. allowPrivate permits services
|
||||
// on private networks, which self-hosted installations may use.
|
||||
func (p Provider) Send(ctx context.Context, cfg map[string]string, m Message, allowPrivate bool) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
return p.send(ctx, newClient(allowPrivate), cfg, m)
|
||||
}
|
||||
|
||||
// Lookup returns the provider of type t.
|
||||
func Lookup(t string) (Provider, bool) {
|
||||
for _, p := range Providers {
|
||||
if p.Type == t {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return Provider{}, false
|
||||
}
|
||||
|
||||
type client struct{ hc *http.Client }
|
||||
|
||||
func newClient(allowPrivate bool) *client {
|
||||
d := netguard.Dialer(allowPrivate, 5*time.Second)
|
||||
return &client{hc: &http.Client{
|
||||
Transport: &http.Transport{DialContext: d.DialContext, DisableKeepAlives: true},
|
||||
// Redirects would bypass the address the customer configured.
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}}
|
||||
}
|
||||
|
||||
// do sends a request and turns non-2xx answers into errors that quote the
|
||||
// start of the service's reply, which usually says what is wrong.
|
||||
func (c *client) do(ctx context.Context, method, rawURL string, header http.Header, body io.Reader) error {
|
||||
req, err := http.NewRequestWithContext(ctx, method, rawURL, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for k, vs := range header {
|
||||
req.Header[k] = vs
|
||||
}
|
||||
req.Header.Set("User-Agent", "uptimesebi-notify")
|
||||
resp, err := c.hc.Do(req)
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) {
|
||||
// The URL may carry a secret, as Telegram's bot token in the path:
|
||||
// name only the host.
|
||||
return fmt.Errorf("%s: %w", req.URL.Host, uerr.Err)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
reply, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return fmt.Errorf("%s answered %d: %s", req.URL.Host, resp.StatusCode, strings.TrimSpace(string(reply)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) json(ctx context.Context, method, rawURL string, header http.Header, v any) error {
|
||||
body, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if header == nil {
|
||||
header = http.Header{}
|
||||
}
|
||||
header.Set("Content-Type", "application/json")
|
||||
return c.do(ctx, method, rawURL, header, bytes.NewReader(body))
|
||||
}
|
||||
|
||||
// text joins title, body and link for services that take plain text.
|
||||
func (m Message) text() string {
|
||||
s := m.Title
|
||||
if m.Body != "" {
|
||||
s += "\n" + m.Body
|
||||
}
|
||||
if m.URL != "" {
|
||||
s += "\n" + m.URL
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func trimURL(s string) string { return strings.TrimSuffix(strings.TrimSpace(s), "/") }
|
||||
|
||||
var webhookField = Field{Name: "webhook_url", Required: true, Secret: true, Kind: "url"}
|
||||
|
||||
// Providers lists the supported services. Webhook and email are handled by
|
||||
// their own types; Apprise reaches the services not listed here.
|
||||
var Providers = []Provider{
|
||||
{Type: "slack", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"text": m.text()})
|
||||
}},
|
||||
{Type: "discord", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"content": m.text(), "username": "UptimeSebi"})
|
||||
}},
|
||||
{Type: "teams", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
// Teams workflows take Adaptive Cards.
|
||||
blocks := []map[string]any{{"type": "TextBlock", "text": m.Title, "weight": "Bolder", "size": "Medium", "wrap": true}}
|
||||
if m.Body != "" {
|
||||
blocks = append(blocks, map[string]any{"type": "TextBlock", "text": m.Body, "wrap": true})
|
||||
}
|
||||
card := map[string]any{"type": "AdaptiveCard", "version": "1.4", "body": blocks,
|
||||
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json"}
|
||||
if m.URL != "" {
|
||||
card["actions"] = []map[string]any{{"type": "Action.OpenUrl", "title": "UptimeSebi", "url": m.URL}}
|
||||
}
|
||||
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{
|
||||
"type": "message", "attachments": []map[string]any{{"contentType": "application/vnd.microsoft.card.adaptive", "content": card}},
|
||||
})
|
||||
}},
|
||||
{Type: "googlechat", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"text": m.text()})
|
||||
}},
|
||||
{Type: "mattermost", Fields: []Field{webhookField, {Name: "channel", Kind: "text"}}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
body := map[string]any{"text": m.text(), "username": "UptimeSebi"}
|
||||
if cfg["channel"] != "" {
|
||||
body["channel"] = cfg["channel"]
|
||||
}
|
||||
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, body)
|
||||
}},
|
||||
{Type: "rocketchat", Fields: []Field{webhookField}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"text": m.text()})
|
||||
}},
|
||||
{Type: "telegram", Fields: []Field{
|
||||
{Name: "bot_token", Required: true, Secret: true, Kind: "text"},
|
||||
{Name: "chat_id", Required: true, Kind: "text"},
|
||||
{Name: "thread_id", Kind: "number"},
|
||||
{Name: "api_url", Kind: "url", Default: "https://api.telegram.org"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
body := map[string]any{"chat_id": cfg["chat_id"], "text": m.text(), "link_preview_options": map[string]any{"is_disabled": true}}
|
||||
if id, err := strconv.Atoi(cfg["thread_id"]); err == nil && id > 0 {
|
||||
body["message_thread_id"] = id
|
||||
}
|
||||
api := trimURL(cfg["api_url"])
|
||||
if api == "" {
|
||||
api = "https://api.telegram.org"
|
||||
}
|
||||
return c.json(ctx, http.MethodPost, api+"/bot"+cfg["bot_token"]+"/sendMessage", nil, body)
|
||||
}},
|
||||
{Type: "matrix", Fields: []Field{
|
||||
{Name: "homeserver_url", Required: true, Kind: "url"},
|
||||
{Name: "access_token", Required: true, Secret: true, Kind: "text"},
|
||||
{Name: "room_id", Required: true, Kind: "text"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
u := trimURL(cfg["homeserver_url"]) + "/_matrix/client/v3/rooms/" + url.PathEscape(cfg["room_id"]) +
|
||||
"/send/m.room.message/" + uuid.NewString()
|
||||
h := http.Header{"Authorization": {"Bearer " + cfg["access_token"]}}
|
||||
return c.json(ctx, http.MethodPut, u, h, map[string]any{"msgtype": "m.text", "body": m.text()})
|
||||
}},
|
||||
{Type: "ntfy", Fields: []Field{
|
||||
{Name: "server_url", Kind: "url", Default: "https://ntfy.sh"},
|
||||
{Name: "topic", Required: true, Kind: "text"},
|
||||
{Name: "priority", Kind: "select", Options: []string{"3", "1", "2", "4", "5"}, Default: "4"},
|
||||
{Name: "access_token", Secret: true, Kind: "text"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
server := trimURL(cfg["server_url"])
|
||||
if server == "" {
|
||||
server = "https://ntfy.sh"
|
||||
}
|
||||
h := http.Header{"Title": {m.Title}, "Priority": {cfg["priority"]}}
|
||||
if m.Event == Resolved {
|
||||
h.Set("Priority", "3")
|
||||
}
|
||||
if m.URL != "" {
|
||||
h.Set("Click", m.URL)
|
||||
}
|
||||
if cfg["access_token"] != "" {
|
||||
h.Set("Authorization", "Bearer "+cfg["access_token"])
|
||||
}
|
||||
return c.do(ctx, http.MethodPost, server+"/"+url.PathEscape(cfg["topic"]), h, strings.NewReader(m.Body))
|
||||
}},
|
||||
{Type: "gotify", Fields: []Field{
|
||||
{Name: "server_url", Required: true, Kind: "url"},
|
||||
{Name: "app_token", Required: true, Secret: true, Kind: "text"},
|
||||
{Name: "priority", Kind: "number", Default: "8"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
prio, _ := strconv.Atoi(cfg["priority"])
|
||||
h := http.Header{"X-Gotify-Key": {cfg["app_token"]}}
|
||||
return c.json(ctx, http.MethodPost, trimURL(cfg["server_url"])+"/message", h,
|
||||
map[string]any{"title": m.Title, "message": m.Body + "\n" + m.URL, "priority": prio})
|
||||
}},
|
||||
{Type: "pushover", Fields: []Field{
|
||||
{Name: "user_key", Required: true, Secret: true, Kind: "text"},
|
||||
{Name: "app_token", Required: true, Secret: true, Kind: "text"},
|
||||
{Name: "priority", Kind: "select", Options: []string{"0", "-1", "1"}, Default: "1"},
|
||||
{Name: "device", Kind: "text"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
form := url.Values{"token": {cfg["app_token"]}, "user": {cfg["user_key"]}, "title": {m.Title}, "message": {m.Body}, "priority": {cfg["priority"]}}
|
||||
if m.URL != "" {
|
||||
form.Set("url", m.URL)
|
||||
}
|
||||
if cfg["device"] != "" {
|
||||
form.Set("device", cfg["device"])
|
||||
}
|
||||
h := http.Header{"Content-Type": {"application/x-www-form-urlencoded"}}
|
||||
return c.do(ctx, http.MethodPost, pushoverURL, h, strings.NewReader(form.Encode()))
|
||||
}},
|
||||
{Type: "pushbullet", Fields: []Field{{Name: "access_token", Required: true, Secret: true, Kind: "text"}},
|
||||
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
h := http.Header{"Access-Token": {cfg["access_token"]}}
|
||||
return c.json(ctx, http.MethodPost, pushbulletURL, h,
|
||||
map[string]any{"type": "note", "title": m.Title, "body": m.Body + "\n" + m.URL})
|
||||
}},
|
||||
{Type: "signal", Fields: []Field{
|
||||
{Name: "api_url", Required: true, Kind: "url"},
|
||||
{Name: "number", Required: true, Kind: "text"},
|
||||
{Name: "recipients", Required: true, Kind: "text"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
// signal-cli-rest-api: recipients are comma-separated numbers or
|
||||
// group IDs.
|
||||
var recipients []string
|
||||
for _, r := range strings.Split(cfg["recipients"], ",") {
|
||||
if r = strings.TrimSpace(r); r != "" {
|
||||
recipients = append(recipients, r)
|
||||
}
|
||||
}
|
||||
return c.json(ctx, http.MethodPost, trimURL(cfg["api_url"])+"/v2/send", nil,
|
||||
map[string]any{"message": m.text(), "number": cfg["number"], "recipients": recipients})
|
||||
}},
|
||||
{Type: "pagerduty", Fields: []Field{
|
||||
{Name: "routing_key", Required: true, Secret: true, Kind: "text"},
|
||||
{Name: "severity", Kind: "select", Options: []string{"critical", "error", "warning", "info"}, Default: "critical"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
// Events API v2: the incident ID pairs trigger and resolve.
|
||||
action := "trigger"
|
||||
if m.Event == Resolved {
|
||||
action = "resolve"
|
||||
}
|
||||
body := map[string]any{"routing_key": cfg["routing_key"], "event_action": action, "dedup_key": m.Key.String()}
|
||||
if action == "trigger" {
|
||||
body["payload"] = map[string]any{"summary": m.Title, "source": "UptimeSebi", "severity": cfg["severity"],
|
||||
"custom_details": map[string]any{"details": m.Body}}
|
||||
if m.URL != "" {
|
||||
body["links"] = []map[string]any{{"href": m.URL, "text": "UptimeSebi"}}
|
||||
}
|
||||
}
|
||||
return c.json(ctx, http.MethodPost, pagerdutyURL, nil, body)
|
||||
}},
|
||||
{Type: "opsgenie", Fields: []Field{
|
||||
{Name: "api_key", Required: true, Secret: true, Kind: "text"},
|
||||
{Name: "region", Kind: "select", Options: []string{"us", "eu"}, Default: "us"},
|
||||
{Name: "priority", Kind: "select", Options: []string{"P1", "P2", "P3", "P4", "P5"}, Default: "P2"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
base := opsgenieURL["us"]
|
||||
if cfg["region"] == "eu" {
|
||||
base = opsgenieURL["eu"]
|
||||
}
|
||||
h := http.Header{"Authorization": {"GenieKey " + cfg["api_key"]}}
|
||||
alias := m.Key.String()
|
||||
if m.Event == Resolved {
|
||||
return c.json(ctx, http.MethodPost, base+"/"+alias+"/close?identifierType=alias", h, map[string]any{"source": "UptimeSebi"})
|
||||
}
|
||||
return c.json(ctx, http.MethodPost, base, h, map[string]any{
|
||||
"message": truncate(m.Title, 130), "alias": alias, "description": m.Body + "\n" + m.URL,
|
||||
"priority": cfg["priority"], "source": "UptimeSebi",
|
||||
})
|
||||
}},
|
||||
{Type: "apprise", Fields: []Field{
|
||||
{Name: "api_url", Required: true, Kind: "url"},
|
||||
{Name: "urls", Secret: true, Kind: "text"},
|
||||
{Name: "config_key", Kind: "text"},
|
||||
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
|
||||
// An Apprise API server reaches over a hundred services: either
|
||||
// stateless with Apprise URLs, or through a configuration stored
|
||||
// on the server under a key.
|
||||
typ := map[string]string{Opened: "failure", Resolved: "success"}[m.Event]
|
||||
if typ == "" {
|
||||
typ = "info"
|
||||
}
|
||||
body := map[string]any{"title": m.Title, "body": m.Body + "\n" + m.URL, "type": typ}
|
||||
api := trimURL(cfg["api_url"])
|
||||
if key := strings.TrimSpace(cfg["config_key"]); key != "" {
|
||||
return c.json(ctx, http.MethodPost, api+"/notify/"+url.PathEscape(key), nil, body)
|
||||
}
|
||||
body["urls"] = cfg["urls"]
|
||||
return c.json(ctx, http.MethodPost, api+"/notify", nil, body)
|
||||
}},
|
||||
}
|
||||
|
||||
// truncate shortens s to n characters.
|
||||
func truncate(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
return s
|
||||
}
|
||||
return string(r[:n-1]) + "…"
|
||||
}
|
||||
|
||||
// Fixed service addresses, replaced in tests.
|
||||
var (
|
||||
pushoverURL = "https://api.pushover.net/1/messages.json"
|
||||
pushbulletURL = "https://api.pushbullet.com/v2/pushes"
|
||||
pagerdutyURL = "https://events.pagerduty.com/v2/enqueue"
|
||||
opsgenieURL = map[string]string{"us": "https://api.opsgenie.com/v2/alerts", "eu": "https://api.eu.opsgenie.com/v2/alerts"}
|
||||
)
|
||||
Reference in new issue
Block a user