-
Notifications
You must be signed in to change notification settings - Fork 3
/
tdlib.go
354 lines (276 loc) · 7.29 KB
/
tdlib.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package tdlib
// #cgo linux CFLAGS: -I/usr/local/include
// #cgo linux LDFLAGS: -Wl,-rpath=/usr/local/lib -ltdjson
// #include <stdlib.h>
// #include "callbacks.h"
import "C"
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/rand"
"sync"
"time"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"github.com/aliforever/go-tdlib/config"
"github.com/aliforever/go-tdlib/incomingevents"
"github.com/aliforever/go-tdlib/outgoingevents"
)
type TDLib struct {
clientID int
updatesChan chan []byte
cfg config.Config
apiID int64
apiHash string
handlers *Handlers
responseQueueLocker sync.Mutex
responseQueue map[string]chan []byte
logger *logrus.Logger
}
func newClientV2(
clientID int,
updateChannel chan []byte,
apiID int64,
apiHash string,
handlers *Handlers,
cfg *config.Config,
logger *logrus.Logger,
) *TDLib {
rand.Seed(time.Now().Unix())
if cfg == nil {
cfg = &config.Config{
UseFileDatabase: true,
UseChatInfoDatabase: true,
UseMessageDatabase: true,
}
}
if cfg.SystemVersion == "" {
cfg.SystemVersion = "1.0.0"
}
if cfg.SystemLanguageCode == "" {
cfg.SystemLanguageCode = "en"
}
if cfg.DeviceModel == "" {
cfg.DeviceModel = "Server"
}
if cfg.ApplicationVersion == "" {
cfg.ApplicationVersion = "1.0.0"
}
return &TDLib{
clientID: clientID,
updatesChan: updateChannel,
apiID: apiID,
apiHash: apiHash,
handlers: handlers,
cfg: *cfg,
responseQueue: map[string]chan []byte{},
logger: logger,
}
}
func (t *TDLib) ReceiveUpdates(ctx context.Context) error {
return t.receiveUpdates(ctx)
}
func (t *TDLib) fireStringQuery(data string) error {
C.td_send(C.int(t.clientID), C.CString(data))
return nil
}
func (t *TDLib) receiveUpdates(ctx context.Context) error {
// This is to make sure that the client is ready to receive updates
go t.GetAuthorizationState()
for {
select {
case <-ctx.Done():
return nil
case updateBytes := <-t.updatesChan:
if err := t.handleUpdateBytes(updateBytes); err != nil {
return err
}
}
}
}
func (t *TDLib) handleUpdateBytes(updateBytes []byte) error {
if updateBytes == nil || len(updateBytes) == 0 {
return nil
}
if t.handlers != nil && t.handlers.rawIncomingEvent != nil {
go t.handlers.rawIncomingEvent(updateBytes)
}
ie, err := incomingevents.GenericFromBytes(updateBytes)
if err != nil {
return err
}
if ie.Type == "error" && ie.RequestID == "" {
if t.handlers != nil && t.handlers.onError != nil {
errEvent, err := incomingevents.ErrorFromBytes(updateBytes)
if err != nil {
return err
}
go t.handlers.onError(errEvent)
}
return nil
}
if ie.RequestID != "" {
go t.informResponse(ie.RequestID, updateBytes)
return nil
}
event, err := incomingevents.FromBytes(updateBytes)
if err != nil {
return err
}
if t.handlers != nil && t.handlers.incomingEvent != nil {
go t.handlers.incomingEvent(event)
}
if t.handlers.onUpdateConnectionState != nil && event.Type == "updateConnectionState" && event.State != nil {
go t.handlers.onUpdateConnectionState(event.State.Type)
}
if t.handlers.authorizationHandler != nil && isAuthorizationEvent(event) {
go t.handlers.authorizationHandler.Process(t, event.AuthorizationState.Type)
}
if t.handlers.onUpdateAuthorizationState != nil && event.Type == "updateAuthorizationState" && event.AuthorizationState != nil {
go t.handlers.onUpdateAuthorizationState(event.AuthorizationState.Type)
}
go t.handleEventType(event.Type, updateBytes)
return nil
}
func (t *TDLib) handleEventType(eventType string, data []byte) {
if handler := t.getEventTypeHandler(eventType); handler != nil {
err := handler.Handle(data)
if err != nil {
// TODO: Add Logs
return
}
}
if eventType == "updateNewMessage" {
for i := range t.handlers.onNewMessageHandlers {
handler := t.handlers.onNewMessageHandlers[i]
if err := NewEventHandlerWithFilter(handler.handler, handler.checkFilters).Handle(data); err != nil {
t.logger.Error(err)
}
}
}
if eventType == "updateMessageEdited" {
for i := range t.handlers.onMessageEditedHandlers {
handler := t.handlers.onMessageEditedHandlers[i]
if err := NewEventHandler[incomingevents.UpdateMessageEdited](handler).Handle(data); err != nil {
t.logger.Error(err)
}
}
}
if eventType == "updateMessageContent" {
for i := range t.handlers.onMessageContentHandlers {
handler := t.handlers.onMessageContentHandlers[i]
if err := NewEventHandler[incomingevents.UpdateMessageContent](handler).Handle(data); err != nil {
t.logger.Error(err)
}
}
}
}
func (t *TDLib) getEventTypeHandler(eventType string) event {
t.handlers.eventTypeHandlerLocker.Lock()
defer t.handlers.eventTypeHandlerLocker.Unlock()
if handler, ok := t.handlers.eventTypeHandlers[eventType]; ok && handler != nil {
return handler
}
return nil
}
func (t *TDLib) getResponseQueueByRequestID(requestID string) chan []byte {
t.responseQueueLocker.Lock()
defer t.responseQueueLocker.Unlock()
if ch, ok := t.responseQueue[requestID]; ok {
return ch
}
return nil
}
func (t *TDLib) newResponseChannel(requestID string) chan []byte {
ch := make(chan []byte)
t.responseQueueLocker.Lock()
defer t.responseQueueLocker.Unlock()
t.responseQueue[requestID] = ch
return ch
}
func (t *TDLib) removeResponseChannel(requestID string, ch chan []byte) {
t.responseQueueLocker.Lock()
defer t.responseQueueLocker.Unlock()
close(ch)
delete(t.responseQueue, requestID)
}
func (t *TDLib) informResponse(requestID string, data []byte) {
ch := t.getResponseQueueByRequestID(requestID)
if ch != nil {
ch <- data
}
}
func sendMap[ResponseType any](
t *TDLib,
requestType string,
data map[string]interface{},
sendOptions ...*SendOptions,
) (*ResponseType, error) {
requestID := uuid.NewString()
eventJS, err := outgoingevents.NewEventJSONFromMap(requestID, requestType, data)
if err != nil {
return nil, err
}
return _send[ResponseType](t, requestID, eventJS, sendOptions...)
}
func send[ResponseType any](
t *TDLib,
data outgoingevents.EventInterface,
sendOptions ...*SendOptions,
) (*ResponseType, error) {
requestID := uuid.NewString()
eventJS, err := outgoingevents.NewEventJSON(requestID, data)
if err != nil {
return nil, err
}
return _send[ResponseType](t, requestID, eventJS, sendOptions...)
}
func _send[ResponseType any](
t *TDLib,
requestID string,
str string,
sendOptions ...*SendOptions,
) (*ResponseType, error) {
ch := t.newResponseChannel(requestID)
if t.cfg.LogSentRequests {
t.logger.Debug(str)
}
err := t.fireStringQuery(str)
if err != nil {
return nil, err
}
var resp []byte
if len(sendOptions) == 0 || sendOptions[0].timeout == nil {
resp = <-ch
} else {
ticker := time.NewTicker(*sendOptions[0].timeout)
select {
case <-ticker.C:
return nil, errors.New("request_timed_out")
case resp = <-ch:
break
}
}
t.removeResponseChannel(requestID, ch)
var errEvent incomingevents.ErrorEvent
err = json.Unmarshal(resp, &errEvent)
if err != nil {
return nil, err
}
if errEvent.Type == "error" {
var str string
err = json.Unmarshal(errEvent.Message, &str)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("%d: %s", errEvent.Code, str)
}
var respObj *ResponseType
err = json.Unmarshal(resp, &respObj)
if err != nil {
return nil, err
}
return respObj, nil
}