2020-03-04 10:29:00 +00:00
|
|
|
package notifiers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2020-03-04 14:20:47 +00:00
|
|
|
"github.com/google/martian/log"
|
2020-03-04 10:29:00 +00:00
|
|
|
"github.com/hunterlong/statping/types/notifications"
|
|
|
|
"github.com/hunterlong/statping/utils"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
allowedVars = []string{"host", "username", "password", "port", "api_key", "api_secret", "var1", "var2"}
|
|
|
|
)
|
|
|
|
|
2020-03-09 15:15:15 +00:00
|
|
|
func checkNotifierForm(n *notifications.Notification) error {
|
|
|
|
for _, f := range n.Form {
|
2020-03-04 10:29:00 +00:00
|
|
|
contains := contains(f.DbField, allowedVars)
|
|
|
|
if !contains {
|
|
|
|
return fmt.Errorf("the DbField '%v' is not allowed, allowed vars: %v", f.DbField, allowedVars)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func contains(s string, arr []string) bool {
|
|
|
|
for _, v := range arr {
|
|
|
|
if strings.ToLower(s) == v {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddNotifier accept a Notifier interface to be added into the array
|
|
|
|
func AddNotifiers(notifiers ...notifications.Notifier) error {
|
2020-03-09 15:15:15 +00:00
|
|
|
log.Infof("Initiating %d Notifiers\n", len(notifiers))
|
|
|
|
|
2020-03-04 10:29:00 +00:00
|
|
|
for _, n := range notifiers {
|
2020-03-09 15:15:15 +00:00
|
|
|
notif := n.Select()
|
|
|
|
log.Infof("Initiating %s Notifier\n", notif.Method)
|
|
|
|
|
|
|
|
if err := checkNotifierForm(notif); err != nil {
|
|
|
|
log.Errorf(err.Error())
|
|
|
|
return err
|
2020-03-04 10:29:00 +00:00
|
|
|
}
|
2020-03-09 15:15:15 +00:00
|
|
|
|
|
|
|
log.Infof("Creating %s Notifier\n", notif.Method)
|
|
|
|
if err := notif.Create(); err != nil {
|
|
|
|
return err
|
2020-03-04 10:29:00 +00:00
|
|
|
}
|
2020-03-09 15:15:15 +00:00
|
|
|
|
|
|
|
notifications.Append(notif)
|
|
|
|
|
|
|
|
if notif.Enabled.Bool {
|
|
|
|
notif.Close()
|
|
|
|
notif.Start()
|
|
|
|
go notifications.Queue(notif)
|
|
|
|
}
|
|
|
|
|
2020-03-04 10:29:00 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// startAllNotifiers will start the go routine for each loaded notifier
|
|
|
|
func startAllNotifiers() {
|
2020-03-09 15:15:15 +00:00
|
|
|
for _, notify := range notifications.All() {
|
|
|
|
n := notify.Select()
|
|
|
|
log.Infof("Initiating %s Notifier\n", n.Method)
|
|
|
|
if utils.IsType(notify, new(notifications.Notifier)) {
|
|
|
|
if n.Enabled.Bool {
|
|
|
|
n.Close()
|
|
|
|
n.Start()
|
2020-03-04 10:29:00 +00:00
|
|
|
go notifications.Queue(notify)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-09 15:15:15 +00:00
|
|
|
func Migrate() error {
|
2020-03-04 10:29:00 +00:00
|
|
|
return AddNotifiers(
|
|
|
|
Command,
|
|
|
|
Discorder,
|
|
|
|
Emailer,
|
|
|
|
LineNotify,
|
|
|
|
Mobile,
|
|
|
|
Slacker,
|
|
|
|
Telegram,
|
|
|
|
Twilio,
|
|
|
|
Webhook,
|
|
|
|
)
|
|
|
|
}
|