You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
osem_notify/core/notifier_xmpp.go

88 lines
2.2 KiB
Go

5 years ago
package core
import (
"errors"
"fmt"
xmpp "github.com/mattn/go-xmpp"
"github.com/spf13/viper"
5 years ago
)
// box config required for the XmppNotifier (TransportConfig.Options)
5 years ago
type XmppNotifier struct {
Recipients []string
}
func (n XmppNotifier) New(config TransportConfig) (AbstractNotifier, error) {
// validate transport configuration
// :TransportConfSourceHack
requiredConf := []string{"xmpp.user", "xmpp.pass", "xmpp.host", "xmpp.starttls"}
for _, key := range requiredConf {
if viper.GetString(key) == "" {
return nil, fmt.Errorf("Missing configuration key %s", key)
}
}
5 years ago
// assign configuration to the notifier after ensuring the correct type.
// lesson of this project: golang requires us to fuck around with type
// assertions, instead of providing us with proper inheritance.
asserted, ok := config.Options.(XmppNotifier)
5 years ago
if !ok || asserted.Recipients == nil {
// config did not contain valid options.
// first try fallback: parse result of viper is a map[string]interface{},
// which requires a different assertion change
asserted2, ok := config.Options.(map[string]interface{})
5 years ago
if ok {
asserted3, ok := asserted2["recipients"].([]interface{})
if ok {
asserted = XmppNotifier{Recipients: []string{}}
for _, rec := range asserted3 {
asserted.Recipients = append(asserted.Recipients, rec.(string))
}
}
}
if asserted.Recipients == nil {
return nil, errors.New("Invalid XmppNotifier options")
}
}
return XmppNotifier{
Recipients: asserted.Recipients,
}, nil
}
func (n XmppNotifier) Submit(notification Notification) error {
// :TransportConfSourceHack
5 years ago
xmppOpts := xmpp.Options{
Host: viper.GetString("xmpp.host"),
User: viper.GetString("xmpp.user"),
Password: viper.GetString("xmpp.pass"),
Resource: "osem_notify",
}
if viper.GetBool("xmpp.starttls") {
xmppOpts.NoTLS = true
xmppOpts.StartTLS = true
}
client, err := xmppOpts.NewClient()
if err != nil {
return err
}
for _, recipient := range n.Recipients {
_, err = client.Send(xmpp.Chat{
Remote: recipient,
5 years ago
Subject: notification.Subject,
Text: fmt.Sprintf("%s\n\n%s", notification.Subject, notification.Body),
5 years ago
})
if err != nil {
return err
}
}
return err
}