forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
178 lines (151 loc) · 3.97 KB
/
service.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package telegram
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"path"
"sync/atomic"
"github.com/pkg/errors"
)
type Service struct {
configValue atomic.Value
logger *log.Logger
}
func NewService(c Config, l *log.Logger) *Service {
s := &Service{
logger: l,
}
s.configValue.Store(c)
return s
}
func (s *Service) Open() error {
return nil
}
func (s *Service) Close() error {
return nil
}
func (s *Service) config() Config {
return s.configValue.Load().(Config)
}
func (s *Service) Update(newConfig []interface{}) error {
if l := len(newConfig); l != 1 {
return fmt.Errorf("expected only one new config object, got %d", l)
}
if c, ok := newConfig[0].(Config); !ok {
return fmt.Errorf("expected config object to be of type %T, got %T", c, newConfig[0])
} else {
s.configValue.Store(c)
}
return nil
}
func (s *Service) Global() bool {
c := s.config()
return c.Global
}
func (s *Service) StateChangesOnly() bool {
c := s.config()
return c.StateChangesOnly
}
type testOptions struct {
ChatId string `json:"chat-id"`
ParseMode string `json:"parse-mode"`
Message string `json:"message"`
DisableWebPagePreview bool `json:"disable-web-page-preview"`
DisableNotification bool `json:"disable-notification"`
}
func (s *Service) TestOptions() interface{} {
c := s.config()
return &testOptions{
ChatId: c.ChatId,
ParseMode: c.ParseMode,
Message: "test telegram message",
DisableWebPagePreview: c.DisableWebPagePreview,
DisableNotification: c.DisableNotification,
}
}
func (s *Service) Test(options interface{}) error {
o, ok := options.(*testOptions)
if !ok {
return fmt.Errorf("unexpected options type %T", options)
}
return s.Alert(
o.ChatId,
o.ParseMode,
o.Message,
o.DisableWebPagePreview,
o.DisableNotification,
)
}
func (s *Service) Alert(chatId, parseMode, message string, disableWebPagePreview, disableNotification bool) error {
url, post, err := s.preparePost(chatId, parseMode, message, disableWebPagePreview, disableNotification)
if err != nil {
return err
}
resp, err := http.Post(url, "application/json", post)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
type response struct {
Description string `json:"description"`
ErrorCode int `json:"error_code"`
Ok bool `json:"ok"`
}
res := &response{}
err = json.Unmarshal(body, res)
if err != nil {
return fmt.Errorf("failed to understand Telegram response (err: %s). code: %d content: %s", err.Error(), resp.StatusCode, string(body))
}
return fmt.Errorf("sendMessage error (%d) description: %s", res.ErrorCode, res.Description)
}
return nil
}
func (s *Service) preparePost(chatId, parseMode, message string, disableWebPagePreview, disableNotification bool) (string, io.Reader, error) {
c := s.config()
if !c.Enabled {
return "", nil, errors.New("service is not enabled")
}
if chatId == "" {
chatId = c.ChatId
}
if parseMode == "" {
parseMode = c.ParseMode
}
if parseMode != "" && parseMode != "Markdown" && parseMode != "HTML" {
return "", nil, fmt.Errorf("parseMode %s is not valid, please use 'Markdown' or 'HTML'", parseMode)
}
postData := make(map[string]interface{})
postData["chat_id"] = chatId
postData["text"] = message
if parseMode != "" {
postData["parse_mode"] = parseMode
}
if disableWebPagePreview || c.DisableWebPagePreview {
postData["disable_web_page_preview"] = true
}
if disableNotification || c.DisableNotification {
postData["disable_notification"] = true
}
var post bytes.Buffer
enc := json.NewEncoder(&post)
err := enc.Encode(postData)
if err != nil {
return "", nil, err
}
u, err := url.Parse(c.URL)
if err != nil {
return "", nil, errors.Wrap(err, "invalid URL")
}
u.Path = path.Join(u.Path+c.Token, "sendMessage")
return u.String(), &post, nil
}