/
notifier.go
100 lines (87 loc) · 2.25 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
95
96
97
98
99
100
package notification
import (
"fmt"
"github.com/pkg/errors"
"github.com/spf13/viper"
"net/http"
"time"
)
type Notifier interface {
SendNotification(notification *Notification) error
}
func CreateAndSendNotification(sendData *Notification, notify *NotificationReceiver) (Notifier, error) {
switch notify.Method {
case "pushover":
push, err := NewPushover(PushoverConfig{
AppToken: notify.AppToken,
Receiver: notify.Receiver,
})
if err != nil {
return nil, err
}
err = push.SendNotification(sendData)
if err != nil {
return nil, err
}
return push, nil
case "telegram":
tele, err := NewTelegram(TelegramConfig{
Token: notify.Token,
Channel: notify.Channel,
})
if err != nil {
return nil, err
}
err = tele.SendNotification(sendData)
if err != nil {
return nil, err
}
return tele, nil
case "email":
email, err := NewEmail(EmailConfig{
SmtpHost: notify.SmtpHost,
SmtpPort: notify.SmtpPort,
AllowSelfSigned: notify.AllowSelfSigned,
FromAddress: notify.FromAddress,
FromPassword: notify.FromPassword,
RecAddress: notify.RecAddress,
})
if err != nil {
return nil, err
}
err = email.SendNotification(sendData)
if err != nil {
return nil, err
}
return email, nil
default:
return nil, errors.New(fmt.Sprintf("unknown notification Method in config: %s", notify.Method))
}
}
type NotificationMethod string
const (
NOTIFICATION_EMAIL = "email"
NOTIFICATION_PUSHOVER = "pushover"
NOTIFICATION_TELEGRAM = "telegram"
)
type NotificationReceiver struct {
Method NotificationMethod `mapstructure:"Method"`
// Email
SmtpHost string `mapstructure:"SmtpHost"`
SmtpPort int `mapstructure:"SmtpPort"`
AllowSelfSigned bool `mapstructure:"AllowSelfSigned"`
FromAddress string `mapstructure:"FromAddress"`
FromPassword string `mapstructure:"FromPassword"`
RecAddress string `mapstructure:"RecAddress"`
// Pushover
AppToken string `mapstructure:"AppToken"`
Receiver string `mapstructure:"Receiver"`
// Telegram
Token string `mapstructure:"Token"`
Channel string `mapstructure:"Channel"`
}
func getHttpAgent() *http.Client {
return &http.Client{
Timeout: time.Duration(viper.GetInt("HTTP.RequestTimeoutSec")) * time.Second,
}
}