-
Notifications
You must be signed in to change notification settings - Fork 2
/
telegram_provider.go
205 lines (161 loc) · 3.88 KB
/
telegram_provider.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package logger
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/net/proxy"
)
const PROVIDER_TELEGRAM = "telegram"
type TelegramProvider struct {
url string
chatIds []string
httplient *http.Client
debugMode bool
}
func NewTelegramProvider(conn string, chatIds []string) (*TelegramProvider, error) {
if len(conn) == 0 {
return nil, errors.New("Empty telegram connection string")
} else if len(chatIds) == 0 {
return nil, errors.New("Empty telegram chat ids")
}
var (
botUrl string
httplient = &http.Client{
Timeout: time.Second * 10,
}
)
connParts := strings.Split(conn, `|`)
switch len(connParts) {
case 1:
// example: 'https://api.telegram.org/bot<token>/sendMessage'
botUrl = connParts[0]
case 2:
// example: '<token>|<schema>://user:password@ip:port'
botToken := connParts[0]
proxyUrl := connParts[1]
botUrl = fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
transport, err := httpTransport(proxyUrl)
if err != nil {
return nil, err
}
httplient.Transport = transport
default:
return nil, errors.New("Invalid connection string format")
}
provider := &TelegramProvider{
url: botUrl,
chatIds: chatIds,
httplient: httplient,
}
return provider, nil
}
func (p TelegramProvider) GetID() string {
return PROVIDER_TELEGRAM
}
func (p TelegramProvider) Log(msg []byte) {
p.send("INFO:", msg)
}
func (p TelegramProvider) Error(msg []byte) {
p.send("ERROR:", msg)
}
func (p TelegramProvider) Fatal(msg []byte) {
p.send("FATAL:", msg)
}
func (p TelegramProvider) Debug(msg []byte) {
p.send("DEBUG:", msg)
}
func (p *TelegramProvider) send(subject string, body []byte) error {
buf := bytes.NewBuffer(nil)
err := json.NewEncoder(buf).Encode(map[string]interface{}{
"chat_id": "unknown",
"text": subject + "\n" + string(body),
})
if err != nil {
log.Println(err)
return err
}
chatIdTemplate := []byte(`"chat_id":"unknown"`)
for _, chatId := range p.chatIds {
js := bytes.Replace(buf.Bytes(), chatIdTemplate, []byte(`"chat_id":"`+chatId+`"`), 1)
req, err := http.NewRequest(http.MethodPost, p.url, bytes.NewBuffer(js))
if err != nil {
log.Println(err)
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := p.httplient.Do(req)
if err != nil {
errMsg := strings.Replace(err.Error(), req.URL.String(), "https://api.telegram.org/...", -1)
err = errors.New(errMsg)
log.Println(err)
return err
}
if p.debugMode {
type Answer struct {
Ok bool `json:"ok"`
}
answer := &Answer{}
err := json.NewDecoder(resp.Body).Decode(answer)
if err != nil {
return err
}
if !answer.Ok {
return errors.New("Invalid response data")
}
} else {
resp.Body.Close()
}
}
return nil
}
func httpTransport(uri string) (*http.Transport, error) {
proxyUrl, err := url.Parse(uri)
if err != nil {
return nil, err
}
var transport *http.Transport
switch {
case strings.HasPrefix(proxyUrl.Scheme, "http"):
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
}
transport = &http.Transport{
Proxy: http.ProxyURL(proxyUrl),
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSClientConfig: tlsConfig,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 2 * time.Second,
}
case proxyUrl.Scheme == "socks5":
var auth *proxy.Auth
if proxyUrl.User != nil {
pass, _ := proxyUrl.User.Password()
auth = &proxy.Auth{
User: proxyUrl.User.Username(),
Password: pass,
}
}
dialSocksProxy, err := proxy.SOCKS5("tcp", proxyUrl.Host, auth, proxy.Direct)
if err != nil {
return nil, err
}
transport = &http.Transport{
Dial: dialSocksProxy.Dial,
}
}
if transport == nil {
return nil, errors.New("Invalid proxy schema")
}
return transport, nil
}