-
Notifications
You must be signed in to change notification settings - Fork 11
/
client.go
333 lines (264 loc) · 6.95 KB
/
client.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package tg
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"sync"
)
type Doer interface {
Do(r *http.Request) (*http.Response, error)
}
// Client is Telegram Bot API client structure.
// Create new client with NewClient function.
type Client struct {
// bot api token
token string
// bot api server base url,
// default values is https://api.telegram.org
server string
callURL string
downloadURL string
// http client,
// default values is http.DefaultClient
doer Doer
// contains cached bot info
me *User
meLock sync.Mutex
interceptors []Interceptor
invoker InterceptorInvoker
}
// ClientOption is a function that sets some option for Client.
type ClientOption func(*Client)
// WithClientServerURL sets custom server url for Client.
func WithClientServerURL(server string) ClientOption {
return func(c *Client) {
c.server = server
}
}
// WithClientDoer sets custom http client for Client.
func WithClientDoer(doer Doer) ClientOption {
return func(c *Client) {
c.doer = doer
}
}
// WithClientTestEnv switches bot to test environment.
// See https://core.telegram.org/bots/webapps#using-bots-in-the-test-environment
func WithClientTestEnv() ClientOption {
return func(c *Client) {
c.callURL = "%s/bot%s/test/%s"
}
}
// WithClientInterceptor adds interceptor to client.
func WithClientInterceptors(ints ...Interceptor) ClientOption {
return func(c *Client) {
c.interceptors = append(c.interceptors, ints...)
}
}
// New creates new Client with given token and options.
func New(token string, options ...ClientOption) *Client {
c := &Client{
token: token,
server: "https://api.telegram.org",
callURL: "%s/bot%s/%s",
downloadURL: "%s/file/bot%s/%s",
doer: http.DefaultClient,
}
for _, option := range options {
option(c)
}
c.invoker = c.buildInvoker()
return c
}
func (client *Client) buildInvoker() InterceptorInvoker {
invoker := client.invoke
for i := len(client.interceptors) - 1; i >= 0; i-- {
invoker = func(next InterceptorInvoker, interceptor Interceptor) InterceptorInvoker {
return func(ctx context.Context, req *Request, dst any) error {
return interceptor(ctx, req, dst, next)
}
}(invoker, client.interceptors[i])
}
return invoker
}
func (client *Client) Token() string {
return client.token
}
// Execute request at low-level
func (client *Client) execute(ctx context.Context, r *Request) (*Response, error) {
if len(r.files) > 0 {
return client.executeStreaming(
ctx,
func(w io.Writer) httpEncoder { return newMultipartEncoder(w) },
r,
)
}
return client.executeSimple(
ctx,
func(w io.Writer) httpEncoder { return newURLEncodedEncoder(w) },
r,
)
}
func (client *Client) buildCallURL(token, method string) string {
return fmt.Sprintf(client.callURL, client.server, token, method)
}
func (client *Client) buildDownloadURL(token, path string) string {
return fmt.Sprintf(client.downloadURL, client.server, token, path)
}
func (client *Client) buildHTTPRequest(
r *Request,
body io.Reader,
contentType string,
) (*http.Request, error) {
url := client.buildCallURL(client.token, r.Method)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, fmt.Errorf("new request: %w", err)
}
// set content type
req.Header.Set("Content-Type", contentType)
return req, nil
}
func (client *Client) executeSimple(
ctx context.Context,
newEncoder func(io.Writer) httpEncoder,
r *Request,
) (*Response, error) {
buf := &bytes.Buffer{}
encoder := newEncoder(buf)
if err := r.Encode(encoder); err != nil {
return nil, fmt.Errorf("encode: %w", err)
}
if err := encoder.Close(); err != nil {
return nil, fmt.Errorf("encoder close: %w", err)
}
req, err := client.buildHTTPRequest(
r,
buf,
encoder.ContentType(),
)
if err != nil {
return nil, fmt.Errorf("build http request: %w", err)
}
res, err := client.executeHTTPRequest(ctx, req)
if err != nil {
return nil, fmt.Errorf("execute http request: %w", err)
}
return res, nil
}
func (client *Client) executeHTTPRequest(ctx context.Context, r *http.Request) (*Response, error) {
r = r.WithContext(ctx)
// execute request
res, err := client.doer.Do(r)
if err != nil {
return nil, fmt.Errorf("do request: %w", err)
}
defer res.Body.Close()
// TODO: handle status and content type
// read content
content, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("read response body: %w", err)
}
response := &Response{
StatusCode: res.StatusCode,
}
// unmarshal content
if err := json.Unmarshal(content, &response); err != nil {
return nil, fmt.Errorf("unmarshal response: %w", err)
}
return response, nil
}
func (client *Client) executeStreaming(
ctx context.Context,
newEncoder func(io.Writer) httpEncoder,
r *Request,
) (*Response, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
pr, pw := io.Pipe()
encoder := newEncoder(pw)
resChan := make(chan *Response)
errChan := make(chan error)
// upload
go func() {
defer pw.Close()
defer encoder.Close()
if err := r.Encode(encoder); err != nil {
errChan <- err
}
}()
// send
go func() {
req, err := client.buildHTTPRequest(r, pr, encoder.ContentType())
if err != nil {
errChan <- fmt.Errorf("build http request: %w", err)
return
}
res, err := client.executeHTTPRequest(ctx, req)
if err != nil {
errChan <- fmt.Errorf("execute http request: %w", err)
return
}
resChan <- res
}()
select {
case err := <-errChan:
return nil, err
case res := <-resChan:
return res, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (client *Client) invoke(ctx context.Context, req *Request, dst any) error {
res, err := client.execute(ctx, req)
if err != nil {
return fmt.Errorf("execute: %w", err)
}
if !res.Ok {
return &Error{
Code: res.ErrorCode,
Message: res.Description,
Parameters: res.Parameters,
}
}
if dst != nil {
if err := json.Unmarshal(res.Result, dst); err != nil {
return fmt.Errorf("unmarshal: %w", err)
}
}
return nil
}
func (client *Client) Do(ctx context.Context, req *Request, dst interface{}) error {
return client.invoker(ctx, req, dst)
}
// Download file by path from Client.GetFile method.
// Don't forget to close ReadCloser.
func (client *Client) Download(ctx context.Context, path string) (io.ReadCloser, error) {
url := client.buildDownloadURL(client.token, path)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("new request: %w", err)
}
res, err := client.doer.Do(req)
if err != nil {
return nil, fmt.Errorf("do request: %w", err)
}
if res.StatusCode != http.StatusOK {
defer res.Body.Close()
tgResponse := &Response{}
if err := json.NewDecoder(res.Body).Decode(tgResponse); err != nil {
return nil, fmt.Errorf("unmarshal: %w", err)
}
return nil, &Error{
Code: tgResponse.ErrorCode,
Message: tgResponse.Description,
Parameters: tgResponse.Parameters,
}
}
return res.Body, nil
}