LamerAlert/sinks/pushover.go

82 lines
1.9 KiB
Go
Raw Normal View History

2019-12-24 12:20:27 +00:00
package sinks
import (
"bytes"
"fmt"
"text/template"
"time"
pubsub "github.com/alash3al/go-pubsub"
"github.com/gregdel/pushover"
"github.com/rs/zerolog/log"
"code.chrissexton.org/cws/lameralert/config"
)
type Pushover struct {
c *config.Config
sub *pubsub.Subscriber
cfgRoot string
name string
p *pushover.Pushover
}
func NewPushover(config *config.Config, name string) (*Pushover, error) {
token := config.GetString("pushover.token", "")
if token == "" {
err := fmt.Errorf("token is empty")
log.Error().Msgf("Could not create pushover for %s: %s.", name, err)
return nil, err
}
p := &Pushover{
c: config,
name: name,
cfgRoot: fmt.Sprintf("pushover.%s", name),
p: pushover.New(token),
}
go p.serve()
return p, nil
}
func (p *Pushover) Subscribe(broker *pubsub.Broker, topic string) error {
var err error
p.sub, err = broker.Attach()
if err != nil {
log.Error().Err(err).Msg("Error attaching to broker")
return err
}
broker.Subscribe(p.sub, topic)
return nil
}
func (p *Pushover) serve() {
wait := 1
for p.sub == nil {
t := time.NewTimer(time.Duration(wait) * time.Second)
<-t.C
wait *= 2
}
for {
select {
case ev := <-p.sub.GetMessages():
tpl := p.c.GetString(p.cfgRoot+".tpl", "{{.}}")
t := template.Must(template.New(p.cfgRoot).Parse(tpl))
buf := bytes.Buffer{}
if err := t.Execute(&buf, ev.GetPayload()); err != nil {
fmt.Printf("%s could not execute template: %s", p.name, err)
}
recipients := p.c.GetStringSlice(p.cfgRoot+".recipients", []string{})
log.Debug().Msgf("%s got a message, pushing to %v", p.name, recipients)
msg := pushover.NewMessage(buf.String())
for _, r := range recipients {
to := pushover.NewRecipient(r)
_, err := p.p.SendMessage(msg, to)
if err != nil {
log.Error().Msgf("Error pushing %s to %s: %s", p.name, r, err)
}
log.Info().Msgf("%s sent pushover to %s", p.name, r)
}
}
}
}