diff --git a/alert/matrix.go b/alert/matrix.go new file mode 100644 index 0000000..93d6b01 --- /dev/null +++ b/alert/matrix.go @@ -0,0 +1,56 @@ +package alert + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/url" + "time" + + blackfriday "gopkg.in/russross/blackfriday.v2" +) + +// Matrix alert container. +type Matrix struct { + client *http.Client + token string + room string +} + +// NewMatrix returns a Matrix alerter from the private token +// and the room identifier, both available in the Riot web UI. +func NewMatrix(token string, room string) *Matrix { + return &Matrix{ + client: &http.Client{}, + token: token, + room: room, + } +} + +// Alert sends a message to the matrix room. +func (p *Matrix) Alert(title, body string) { + data := "☢️ **" + title + "**: " + body + markdownBody := blackfriday.Run( + []byte(data), + blackfriday.WithExtensions(blackfriday.HardLineBreak|blackfriday.NoEmptyLineBeforeBlock), + ) + raw, _ := json.Marshal(map[string]string{ + "msgtype": "m.text", + "format": "org.matrix.custom.html", + "formatted_body": string(markdownBody), + "body": data, + }) + + url := fmt.Sprintf( + "https://matrix.org/_matrix/client/r0/rooms/%s/send/m.room.message/%d?access_token=%s", + url.PathEscape(p.room), + time.Now().UnixNano(), + p.token, + ) + + req, _ := http.NewRequest("PUT", url, bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + + _, _ = p.client.Do(req) +} diff --git a/config.go b/config.go index 44b45d9..b202791 100644 --- a/config.go +++ b/config.go @@ -6,7 +6,6 @@ import ( "github.com/Lesterpig/board/alert" "github.com/Lesterpig/board/probe" - "github.com/spf13/viper" ) @@ -20,6 +19,7 @@ type serviceConfig struct { type alertConfig struct { Type string Token string + Dest string } var probeConstructors = map[string](func() probe.Prober){ @@ -34,6 +34,9 @@ var alertConstructors = map[string](func(c alertConfig) alert.Alerter){ "pushbullet": func(c alertConfig) alert.Alerter { return alert.NewPushbullet(c.Token) }, + "matrix": func(c alertConfig) alert.Alerter { + return alert.NewMatrix(c.Token, c.Dest) + }, } var alerters []alert.Alerter diff --git a/example.yaml b/example.yaml index e14ac36..1adae99 100644 --- a/example.yaml +++ b/example.yaml @@ -18,4 +18,7 @@ services: alerts: - type: pushbullet token: + - type: matrix + token: + dest: # ...