forked from bittersweet/notifilter-receive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotifier.go
94 lines (78 loc) · 2.08 KB
/
notifier.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"bytes"
"log"
"text/template"
"github.com/jmoiron/sqlx/types"
)
type NotifierResponse struct {
response *slackResponse
error error
}
// Every notifier we create needs to adhere to this interface, so we can
// substitute another one when testing
type MessageNotifier interface {
sendMessage(string, []byte) NotifierResponse
}
type Notifier struct {
Id int `db:"id"`
NotificationType string `db:"notification_type"`
EventName string `db:"event_name"`
Template string `db:"template"`
Rules types.JsonText `db:"rules"`
// type slack/email/direct to phone
// email address, slack channel, phone number, how to store?
}
func (n *Notifier) newNotifier() MessageNotifier {
switch n.NotificationType {
case "email":
return &emailNotifier{}
case "slack":
return &slackNotifier{}
}
return &slackNotifier{}
}
func (n *Notifier) getRules() []*Rule {
rules := []*Rule{}
n.Rules.Unmarshal(&rules)
return rules
}
func (n *Notifier) checkRules(e *Event) bool {
rules := n.getRules()
rules_met := true
for _, rule := range rules {
if !rule.Met(e) {
log.Printf("Rule not met -- Key: %s, Type: %s, Setting %s, Value %s, Received Value %v\n", rule.Key, rule.Type, rule.Setting, rule.Value, e.toMap()[rule.Key])
rules_met = false
}
}
if !rules_met {
log.Printf("Stopping notification of id: %d, rules not met\n", n.Id)
return false
}
return true
}
func (n *Notifier) renderTemplate(s *Event) []byte {
var err error
var doc bytes.Buffer
t := template.New("notificationTemplate")
t, err = t.Parse(n.Template)
if err != nil {
log.Fatal("t.Parse of n.Template", err)
}
err = t.Execute(&doc, s.toMap())
if err != nil {
log.Fatal("t.Execute ", err)
}
return doc.Bytes()
}
func (n *Notifier) notify(s *Event, mn MessageNotifier) {
nt := n.NotificationType
log.Printf("Notifying notifier id: %d type: %s\n", n.Id, nt)
if !n.checkRules(s) {
return
}
message := n.renderTemplate(s)
mn.sendMessage(s.Identifier, message)
log.Printf("Notifying notifier id: %d done\n", n.Id)
}