forked from max-messenger/max-bot-api-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
462 lines (395 loc) · 13.3 KB
/
api.go
File metadata and controls
462 lines (395 loc) · 13.3 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// Package maxbot implements MAX Bot API.
// Official documentation: https://dev.max.ru/
package maxbot
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/max-messenger/max-bot-api-client-go/schemes"
)
type UpdateHandler func(schemes.UpdateInterface)
// Api represents the MAX Bot API client.
type Api struct {
Bots *bots
Chats *chats
Debugs *debugs
Messages *messages
Subscriptions *subscriptions
Uploads *uploads
updateHandler UpdateHandler
client *client
timeout time.Duration
pause time.Duration
debug bool
}
// New creates a new Max Bot API client with the provided token.
func New(token string, opts ...Option) (*Api, error) {
if token == "" {
return nil, ErrEmptyToken
}
u, err := url.Parse(defaultAPIURL)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrInvalidURL, err)
}
cl := newClient(token, Version, u, &http.Client{Timeout: defaultTimeout})
api := &Api{
Bots: newBots(cl),
Chats: newChats(cl),
Debugs: newDebugs(cl, 0),
Messages: newMessages(cl),
Subscriptions: newSubscriptions(cl),
Uploads: newUploads(cl),
client: cl,
timeout: defaultTimeout,
pause: defaultPause,
debug: false,
}
for _, o := range opts {
o(api)
}
return api, nil
}
func (a *Api) getUpdateType(updateType schemes.UpdateType) func(debugRaw string) schemes.UpdateInterface {
switch updateType {
case schemes.TypeMessageCallback:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.MessageCallbackUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeMessageCreated:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.MessageCreatedUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeMessageRemoved:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.MessageRemovedUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeMessageEdited:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.MessageEditedUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeBotAdded:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.BotAddedToChatUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeBotRemoved:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.BotRemovedFromChatUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeBotStoped:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.BotStopedFromChatUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeDialogRemoved:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.DialogRemovedFromChatUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeDialogCleared:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.DialogClearedFromChatUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeUserAdded:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.UserAddedToChatUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeUserRemoved:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.UserRemovedFromChatUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeBotStarted:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.BotStartedUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
case schemes.TypeChatTitleChanged:
return func(debugRaw string) schemes.UpdateInterface {
return &schemes.ChatTitleChangedUpdate{Update: schemes.Update{DebugRaw: debugRaw}}
}
}
return nil
}
func (a *Api) getAttachmentType(attachmentType schemes.AttachmentType) func() schemes.AttachmentInterface {
switch attachmentType {
case schemes.AttachmentAudio:
return func() schemes.AttachmentInterface { return new(schemes.AudioAttachment) }
case schemes.AttachmentContact:
return func() schemes.AttachmentInterface { return new(schemes.ContactAttachment) }
case schemes.AttachmentFile:
return func() schemes.AttachmentInterface { return new(schemes.FileAttachment) }
case schemes.AttachmentImage:
return func() schemes.AttachmentInterface { return new(schemes.PhotoAttachment) }
case schemes.AttachmentKeyboard:
return func() schemes.AttachmentInterface { return new(schemes.InlineKeyboardAttachment) }
case schemes.AttachmentLocation:
return func() schemes.AttachmentInterface { return new(schemes.LocationAttachment) }
case schemes.AttachmentShare:
return func() schemes.AttachmentInterface { return new(schemes.ShareAttachment) }
case schemes.AttachmentSticker:
return func() schemes.AttachmentInterface { return new(schemes.StickerAttachment) }
case schemes.AttachmentVideo:
return func() schemes.AttachmentInterface { return new(schemes.VideoAttachment) }
}
return nil
}
// bytesToProperUpdate converts raw JSON bytes to the appropriate update type.
func (a *Api) bytesToProperUpdate(data []byte) (schemes.UpdateInterface, error) {
baseUpdate := &schemes.Update{}
if err := jsoniter.Unmarshal(data, baseUpdate); err != nil {
return nil, fmt.Errorf("failed to unmarshal base update: %w", err)
}
debugRaw := ""
if a.debug {
debugRaw = string(data)
}
updateType := baseUpdate.GetUpdateType()
constructor := a.getUpdateType(updateType)
if constructor == nil {
return nil, fmt.Errorf("unknown update type: %s", updateType)
}
update := constructor(debugRaw)
if err := jsoniter.Unmarshal(data, update); err != nil {
return nil, fmt.Errorf("failed to unmarshal update of type %s: %w", updateType, err)
}
if err := a.processMessageAttachments(update); err != nil {
return nil, fmt.Errorf("failed to process message attachments: %w", err)
}
return update, nil
}
// processMessageAttachments processes attachments for message-type updates.
func (a *Api) processMessageAttachments(update schemes.UpdateInterface) error {
switch u := update.(type) {
case *schemes.MessageCreatedUpdate:
if u.Message.Body.RawAttachments != nil {
attachments, err := a.convertRawAttachments(u.Message.Body.RawAttachments)
if err != nil {
return err
}
u.Message.Body.Attachments = append(u.Message.Body.Attachments, attachments...)
} else if u.Message.Link != nil && u.Message.Link.Message.RawAttachments != nil {
attachments, err := a.convertRawAttachments(u.Message.Link.Message.RawAttachments)
if err != nil {
return err
}
u.Message.Link.Message.Attachments = append(u.Message.Link.Message.Attachments, attachments...)
}
case *schemes.MessageEditedUpdate:
if u.Message.Body.RawAttachments != nil {
attachments, err := a.convertRawAttachments(u.Message.Body.RawAttachments)
if err != nil {
return err
}
u.Message.Body.Attachments = append(u.Message.Body.Attachments, attachments...)
} else if u.Message.Link != nil && u.Message.Link.Message.RawAttachments != nil {
attachments, err := a.convertRawAttachments(u.Message.Link.Message.RawAttachments)
if err != nil {
return err
}
u.Message.Link.Message.Attachments = append(u.Message.Link.Message.Attachments, attachments...)
}
default:
return nil // No attachments to process
}
return nil
}
// bytesToProperAttachment converts raw JSON bytes to the appropriate attachment type.
func (a *Api) bytesToProperAttachment(data []byte) (schemes.AttachmentInterface, error) {
baseAttachment := &schemes.Attachment{}
if err := jsoniter.Unmarshal(data, baseAttachment); err != nil {
return nil, fmt.Errorf("failed to unmarshal base attachment: %w", err)
}
attachmentType := baseAttachment.GetAttachmentType()
constructor := a.getAttachmentType(attachmentType)
if constructor == nil {
// Return base attachment for unknown types
return baseAttachment, nil
}
attachment := constructor()
if err := jsoniter.Unmarshal(data, attachment); err != nil {
return nil, fmt.Errorf("failed to unmarshal attachment of type %s: %w", attachmentType, err)
}
return attachment, nil
}
func (a *Api) convertRawAttachments(rawAttachments []json.RawMessage) ([]any, error) {
result := make([]any, 0, len(rawAttachments))
for _, rawAttachment := range rawAttachments {
attachment, err := a.bytesToProperAttachment([]byte(rawAttachment))
if err != nil {
return nil, fmt.Errorf("failed to process attachment: %w", err)
}
result = append(result, attachment)
}
return result, nil
}
func (a *Api) closer(name string, c io.Closer) {
if c == nil {
return
}
if err := c.Close(); err != nil {
a.client.notifyError(fmt.Errorf("failed to close %s: %w", name, err))
}
}
// UpdatesParams holds parameters for getting updates.
type UpdatesParams struct {
Limit int
Timeout time.Duration
Marker int64
Types []string
}
// getUpdates fetches updates from the API.
func (a *Api) getUpdates(ctx context.Context, params *UpdatesParams) (*schemes.UpdateList, error) {
if params == nil {
params = &UpdatesParams{}
}
values := url.Values{}
if params.Limit > 0 {
values.Set(paramLimit, strconv.Itoa(params.Limit))
}
if params.Timeout > 0 {
values.Set(paramTimeout, strconv.Itoa(int(params.Timeout.Seconds())))
}
if params.Marker > 0 {
values.Set(paramMarker, strconv.FormatInt(params.Marker, 10))
}
for _, t := range params.Types {
values.Add(paramTypes, t)
}
body, err := a.client.request(ctx, http.MethodGet, pathUpdates, values, false, nil)
if err != nil {
var te *TimeoutError
// Обрабатывать timeout как пустую страницу (ожидается при длительном опросе)
if errors.As(err, &te) {
return &schemes.UpdateList{}, nil
}
// Учитывать отмену контекста/истечение срока
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, ctx.Err()
}
return nil, fmt.Errorf("failed to get updates: %w", err)
}
defer a.closer("failed to close response body", body)
data, err := io.ReadAll(body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
result := &schemes.UpdateList{}
if err = jsoniter.Unmarshal(data, result); err != nil {
return nil, fmt.Errorf("failed to unmarshal updates: %w", err)
}
return result, nil
}
func (a *Api) getUpdatesWithRetry(ctx context.Context, params *UpdatesParams) (*schemes.UpdateList, error) {
if params == nil {
params = &UpdatesParams{}
}
var result *schemes.UpdateList
var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ {
result, lastErr = a.getUpdates(ctx, params)
if lastErr == nil {
return result, nil
}
// Остановить retry если context отменен/истек
if errors.Is(lastErr, context.Canceled) || errors.Is(lastErr, context.DeadlineExceeded) {
return nil, lastErr
}
if attempt < maxRetries-1 {
retryWait := time.Duration(1<<uint(attempt)) * time.Second
a.client.notifyError(fmt.Errorf("attempt %d failed, retrying in %v: %v", attempt+1, retryWait, lastErr))
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(retryWait):
}
}
}
return nil, fmt.Errorf("failed after %d attempts: %w", maxRetries, lastErr)
}
func (a *Api) GetErrors() <-chan error {
return a.client.errors
}
// GetUpdates returns a channel that delivers updates from the API.
func (a *Api) GetUpdates(ctx context.Context) <-chan schemes.UpdateInterface {
ch := make(chan schemes.UpdateInterface, 100)
go func() {
defer close(ch)
var marker int64
ticker := time.NewTicker(a.pause)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
for {
params := &UpdatesParams{
Limit: maxUpdatesLimit,
Timeout: a.timeout,
Marker: marker,
}
updateList, err := a.getUpdatesWithRetry(ctx, params)
if err != nil {
a.client.notifyError(fmt.Errorf("failed to get updates: %v", err))
break
}
if len(updateList.Updates) == 0 {
break
}
for _, rawUpdate := range updateList.Updates {
update, err := a.bytesToProperUpdate(rawUpdate)
if err != nil {
a.client.notifyError(fmt.Errorf("---> Attention!!! Failed to process update: %v", err))
continue
}
if a.updateHandler != nil {
a.updateHandler(update)
continue
}
select {
case ch <- update:
case <-ctx.Done():
return
}
}
if updateList.Marker != nil {
marker = *updateList.Marker
}
}
}
}
}()
return ch
}
// GetHandler returns an http.HandlerFunc for webhook handling.
func (a *Api) GetHandler(updates chan<- schemes.UpdateInterface) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
update, err := a.bytesToProperUpdate(body)
if err != nil {
http.Error(w, "Failed to parse update", http.StatusBadRequest)
return
}
if a.updateHandler != nil {
a.updateHandler(update)
return
}
select {
case updates <- update:
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "Updates channel is full", http.StatusServiceUnavailable)
}
}
}