-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
executable file
·198 lines (165 loc) · 5.65 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
// AUTOGENERATED - DO NOT EDIT
package tdlib
import (
"encoding/json"
"fmt"
"math/rand"
"reflect"
"sync"
"time"
)
//go:generate mockgen -source client.go --aux_files=github.com/wh3r3areyou/go-tdlib=auth.go,github.com/wh3r3areyou/go-tdlib=events.go,github.com/wh3r3areyou/go-tdlib=tl_methods.go -destination=./mocks/client.go
// Client is the Telegram TdLib contract
type Client interface {
SendAndCatch(jsonQuery interface{}) (UpdateMsg, error)
GetConfig() *Config
AuthFunctions
EventFunctions
TDLibFunctions
}
// ClientImpl is the Telegram TdLib client
type ClientImpl struct {
receiverLock *sync.Mutex
waitersLock *sync.RWMutex
tdlibClient tdlibClient
Config *Config
rawUpdates chan UpdateMsg
receivers []EventReceiver
waiters map[string]chan UpdateMsg
}
// NewClient Creates a new instance of TDLib.
// Has two public fields:
// Client itself and RawUpdates channel
func NewClient(config Config) *ClientImpl {
// Seed rand with time
rand.Seed(time.Now().UnixNano())
// setting the default value for timeout in seconds
if config.Timeout == 0 {
config.Timeout = 10
}
client := ClientImpl{
tdlibClient: newTDLibClient(),
receivers: make([]EventReceiver, 0, 1),
receiverLock: &sync.Mutex{},
waitersLock: &sync.RWMutex{},
Config: &config,
waiters: make(map[string]chan UpdateMsg),
}
go func() {
for {
// get update
updateBytes := client.tdlibClient.receive(float64(config.Timeout))
var updateData UpdateData
json.Unmarshal(updateBytes, &updateData)
// does new update has @extra field?
if extra, hasExtra := updateData["@extra"].(string); hasExtra {
client.waitersLock.RLock()
waiter, found := client.waiters[extra]
client.waitersLock.RUnlock()
// trying to load update with this salt
if found {
// found? send it to waiter channel
waiter <- UpdateMsg{Data: updateData, Raw: updateBytes}
// trying to prevent memory leak
close(waiter)
}
} else {
// does new updates has @type field?
if msgType, hasType := updateData["@type"]; hasType {
if client.rawUpdates != nil {
// if rawUpdates is initialized, send the update in rawUpdates channel
client.rawUpdates <- UpdateMsg{Data: updateData, Raw: updateBytes}
}
client.receiverLock.Lock()
for _, receiver := range client.receivers {
if msgType == receiver.Instance.MessageType() {
var newMsg TdMessage
newMsg = reflect.New(reflect.ValueOf(receiver.Instance).Elem().Type()).Interface().(TdMessage)
err := json.Unmarshal(updateBytes, &newMsg)
if err != nil {
fmt.Printf("Error unmarhaling to type %!v(MISSING)", err)
continue
}
if receiver.FilterFunc(&newMsg) {
receiver.Chan <- newMsg
}
}
}
client.receiverLock.Unlock()
}
}
}
}()
return &client
}
// SendAndCatch Sends request to the TDLib client and catches the result in updates channel.
// You can provide string or UpdateData.
func (client *ClientImpl) SendAndCatch(jsonQuery interface{}) (UpdateMsg, error) {
var update UpdateData
switch jsonQuery.(type) {
case string:
// unmarshal JSON into map, we don't have @extra field, if user don't set it
json.Unmarshal([]byte(jsonQuery.(string)), &update)
case UpdateData:
update = jsonQuery.(UpdateData)
}
// letters for generating random string
letterBytes := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// generate random string for @extra field
b := make([]byte, 32)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
randomString := string(b)
// set @extra field
update["@extra"] = randomString
// create waiter chan and save it in Waiters
waiter := make(chan UpdateMsg, 1)
client.waitersLock.Lock()
client.waiters[randomString] = waiter
client.waitersLock.Unlock()
// send it through already implemented method
client.tdlibClient.send(update)
select {
// wait response from main loop in NewClient()
case response := <-waiter:
client.waitersLock.Lock()
delete(client.waiters, randomString)
client.waitersLock.Unlock()
return response, nil
// or timeout
case <-time.After(time.Duration(client.Config.Timeout) * time.Second):
client.waitersLock.Lock()
delete(client.waiters, randomString)
client.waitersLock.Unlock()
return UpdateMsg{}, ErrTimeout
}
}
func (client *ClientImpl) sendTdLibParams() {
if len(client.Config.APIID) == 0 || len(client.Config.APIHash) == 0 {
panic("Input required params: APIID AND APIHASH")
}
client.tdlibClient.send(UpdateData{
"@type": "setTdlibParameters",
"use_test_dc": client.Config.UseTestDataCenter,
"database_directory": client.Config.DatabaseDirectory,
"files_directory": client.Config.FileDirectory,
"use_file_database": client.Config.UseFileDatabase,
"use_chat_info_database": client.Config.UseChatInfoDatabase,
"use_message_database": client.Config.UseMessageDatabase,
"use_secret_chats": client.Config.UseSecretChats,
"api_id": client.Config.APIID,
"api_hash": client.Config.APIHash,
"system_language_code": client.Config.SystemLanguageCode,
"device_model": client.Config.DeviceModel,
"system_version": client.Config.SystemVersion,
"application_version": client.Config.ApplicationVersion,
"enable_storage_optimizer": client.Config.EnableStorageOptimizer,
"ignore_file_names": client.Config.IgnoreFileNames,
})
}
// DestroyInstance Destroys the TDLib client instance.
// After this is called the client instance shouldn't be used anymore.
func (client *ClientImpl) DestroyInstance() {
client.tdlibClient.destroyInstance()
}