-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtdlua.cpp
More file actions
304 lines (262 loc) · 6.88 KB
/
Copy pathtdlua.cpp
File metadata and controls
304 lines (262 loc) · 6.88 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
/**
* @author Giuseppe Marino
* ©Giuseppe Marino 2018 - 2018
* This file is under GPLv3 license see LICENCE
*/
#include "tdlua.h"
#include <chrono>
#include <iostream>
#include <fstream>
#include <map>
#include <mutex>
#include <queue>
#include <td/telegram/td_json_client.h>
namespace {
using json = nlohmann::json;
class JsonRuntime {
public:
static JsonRuntime &instance()
{
static JsonRuntime runtime;
return runtime;
}
std::int32_t createClient()
{
return td_create_client_id();
}
void send(const std::int32_t client_id, const json &request)
{
const std::string serialized = request.dump();
td_send(client_id, serialized.c_str());
}
json execute(const json &request)
{
const std::string serialized = request.dump();
return parse(td_execute(serialized.c_str()), "execute");
}
json receive(const std::int32_t client_id, const double timeout)
{
std::lock_guard<std::mutex> lock(receive_mutex);
std::queue<json> &client_queue = pending[client_id];
if (!client_queue.empty()) {
json result = client_queue.front();
client_queue.pop();
return result;
}
const auto started = std::chrono::steady_clock::now();
while (true) {
const std::chrono::duration<double> elapsed =
std::chrono::steady_clock::now() - started;
const double remaining = timeout - elapsed.count();
if (remaining <= 0.0) {
return nullptr;
}
json result = parse(td_receive(remaining), "receive");
if (!result.is_object()) {
return nullptr;
}
const auto client_field = result.find("@client_id");
if (client_field == result.end() || !client_field->is_number_integer()) {
return result;
}
const std::int32_t result_client_id = client_field->get<std::int32_t>();
result.erase("@client_id");
if (result_client_id == client_id) {
return result;
}
pending[result_client_id].push(result);
}
}
void forget(const std::int32_t client_id)
{
std::lock_guard<std::mutex> lock(receive_mutex);
pending.erase(client_id);
}
private:
static json parse(const char *serialized, const char *operation)
{
if (!serialized) {
return nullptr;
}
try {
return json::parse(serialized);
} catch (const json::parse_error &error) {
std::cerr << "[TDCLIENT " << operation << "] JSON parse error "
<< error.what() << "\n";
return nullptr;
}
}
std::mutex receive_mutex;
std::map<std::int32_t, std::queue<json> > pending;
};
}
TDLua::TDLua(lua_State *lua)
: client_id(JsonRuntime::instance().createClient()),
next_request_id(1), updates(), dbpath(), _ready(false),
state(ClientState::Running), dispatcher_(lua)
{
}
TDLua::~TDLua()
{
close();
}
nlohmann::json TDLua::pop()
{
nlohmann::json res = updates.front();
updates.pop();
return res;
}
void TDLua::setDB(const std::string &path)
{
dbpath = path;
if (dbpath.empty()) {
return;
}
if (dbpath.back() != '/')
dbpath += "/";
dbpath += "tdlua.json";
}
void TDLua::send(const nlohmann::json &json)
{
JsonRuntime::instance().send(client_id, json);
}
nlohmann::json TDLua::execute(const nlohmann::json &json)
{
return JsonRuntime::instance().execute(json);
}
nlohmann::json TDLua::receive(const double timeout)
{
return JsonRuntime::instance().receive(client_id, timeout);
}
void TDLua::close()
{
if (state == ClientState::Closed) {
JsonRuntime::instance().forget(client_id);
state = ClientState::Closed;
return;
}
if (state == ClientState::Running) {
send({{"@type", "close"}});
state = ClientState::Closing;
}
while (state != ClientState::Closed) {
nlohmann::json update = receive(1.0);
if (update.is_object()) {
checkAuthState(update);
}
}
JsonRuntime::instance().forget(client_id);
}
bool TDLua::closed() const
{
return state == ClientState::Closed;
}
std::uint64_t TDLua::nextRequestId()
{
return next_request_id++;
}
LuaDispatcher &TDLua::dispatcher()
{
return dispatcher_;
}
void TDLua::push(const nlohmann::json &update)
{
updates.push(update);
}
bool TDLua::empty() const
{
return updates.empty();
}
#ifdef TDLUA_CALLS
void TDLua::setCall(const int32_t id, const Call* call)
{
calls[id] = (Call*) call;
}
void TDLua::delCall(const int32_t id)
{
calls.erase(id);
}
Call* TDLua::getCall(const int32_t id) const
{
return calls.at(id);
}
void TDLua::deinitAllCalls()
{
for (auto call : calls)
{
call.second->closeCall();
}
}
uint64_t TDLua::runningCalls()
{
return calls.size();
}
#endif
void TDLua::saveUpdatesBuffer()
{
if (!_ready || dbpath.empty()) return;
nlohmann::json jupdates = nlohmann::json::array();
while(updates.size()) {
jupdates[updates.size()] = this->pop();
}
std::ofstream out(dbpath);
out << jupdates.dump();
out.close();
}
void TDLua::loadUpdatesBuffer()
{
if (dbpath.empty() || _ready || !updates.empty()) return;
std::ifstream in(dbpath);
if (in && in.is_open()) {
std::string buf;
in.seekg(0, std::ios::end);
const std::streamoff size = in.tellg();
if (size <= 0) {
in.close();
_ready = true;
return;
}
buf.resize(static_cast<std::size_t>(size));
in.seekg(0, std::ios::beg);
in.read(&buf[0], buf.size());
in.close();
try {
nlohmann::json j = nlohmann::json::parse(buf);
if (j.is_array() && !j.empty()) {
for (auto &elem : j) {
updates.push(elem);
}
}
} catch (nlohmann::json::parse_error &e){
std::cerr << "[TDCLIENT LOAD BUFFER] JSON Parse error " << e.what() << "\n";
_ready = true;
emptyUpdatesBuffer();
saveUpdatesBuffer();
return;
}
}
_ready = true;
}
void TDLua::emptyUpdatesBuffer()
{
while (!updates.empty()) {
updates.pop();
}
}
void TDLua::checkAuthState(const nlohmann::json &update)
{
if (update["@type"] == "updateAuthorizationState") {
if (!ready() && update["authorization_state"]["@type"] == "authorizationStateReady") {
loadUpdatesBuffer();
} else if (update["authorization_state"]["@type"] == "authorizationStateClosed") {
saveUpdatesBuffer();
emptyUpdatesBuffer();
_ready = false;
state = ClientState::Closed;
}
}
}
bool TDLua::ready() const
{
return _ready;
}