-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpropa_rank.cpp
More file actions
426 lines (401 loc) · 14.5 KB
/
Copy pathpropa_rank.cpp
File metadata and controls
426 lines (401 loc) · 14.5 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
/*
Propeller Arena game server.
Copyright 2026 Flyinghead <flyinghead.github@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "propa_rank.h"
#include "kage.h"
#include <dcserver/json.hpp>
using namespace std::chrono_literals;
using namespace nlohmann;
constexpr int RankPoints[] {
5000, 4250, 3500, 2875,
2300, 1800, 1375, 1000,
700, 475, 300, 175,
75, 0
};
void RankConnection::send(const std::vector<uint32_t>& data)
{
memcpy(&sendBuffer[sendIdx], data.data(), data.size() * sizeof(uint32_t));
sendIdx += data.size() * sizeof(uint32_t);
send();
}
void RankConnection::send()
{
if (sending)
return;
sending = true;
asio::async_write(socket, asio::buffer(sendBuffer, sendIdx),
std::bind(&RankConnection::onSent, shared_from_this(),
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
void RankConnection::onSent(const std::error_code& ec, size_t len)
{
if (ec)
ERROR_LOG(Game::PropellerA, "Send error: %s", ec.message().c_str());
else
DEBUG_LOG(Game::PropellerA, "sent %zd bytes", len);
sendIdx = 0;
sending = false;
}
void RankConnection::receive()
{
startTimer();
socket.async_read_some(asio::buffer(recvBuffer),
std::bind(&RankConnection::onReceive, shared_from_this(), asio::placeholders::error, asio::placeholders::bytes_transferred));
}
void RankConnection::onReceive(const std::error_code& ec, size_t len)
{
if (ec || len == 0)
{
if (ec && ec != asio::error::eof)
ERROR_LOG(Game::PropellerA, "rank: %s", ec.message().c_str());
std::error_code ignored;
socket.shutdown(asio::socket_base::shutdown_both, ignored);
return;
}
if (len < 0x34) {
ERROR_LOG(Game::PropellerA, "Packet too short: %zx", len);
}
else
{
uint32_t op = read32(recvBuffer.data(), 0);
if (op == 1)
{
// Get online ranking
std::string username = (const char *)&recvBuffer[0x14];
Statement stmt(database, "SELECT kills, wins, games, flightTime, flightDistance, shotDown, points, rank from ranking where user_id = ?");
stmt.bind(1, username);
// total kills, number of wins, number of games, total flight time, total flight distance,
// number of times shot down, total points, rank
// ranks: 0: none, 1:general, 2:lieutenant general, 3:major general, 4:colonel
// 5:lieutenant colonel, 6:major, 7:captain, 8:first lieutenant, 9:second lieutenant,
// 10:sergeant, 11:senior airman, 12:airman first class, 13:airman, 14:airman basic, 15:none...
// after game: 1st: 10 pts, 2nd: 5 pts, 3rd: 2 pts
std::vector<uint32_t> data(8);
if (!stmt.step()) {
data[7] = ntohl(14);
}
else {
for (int i = 0; i < 8; i++)
data[i] = ntohl(stmt.getIntColumn(i));
}
send(data);
}
else if (op == 5)
{
// Update training data
std::string username = (const char *)&recvBuffer[0x14];
uint32_t size = read32(recvBuffer.data(), 0x38);
if (size != 3 * (8 + 2 + 1) * sizeof(uint32_t)) {
std::vector<uint32_t> data(1);
send(data);
}
else
{
// 3 categories (Stunt, Challenge, Agility)
// 8 scores
// 2 bonus scores(?)
// total score
uint32_t scores[3][8];
uint32_t bonuses[3][2];
uint32_t totals[3];
unsigned offset = 0x3c;
for (unsigned cat = 0; cat < 3; cat++)
{
for (unsigned score = 0; score < 8; score++, offset += 4)
scores[cat][score] = read32(recvBuffer.data(), offset);
for (unsigned bonus = 0; bonus < 2; bonus++, offset += 4)
bonuses[cat][bonus] = read32(recvBuffer.data(), offset);
totals[cat] = read32(recvBuffer.data(), offset);
offset += 4;
}
uint32_t resp = 0x10;
Statement stmt(database, "SELECT cat1total, cat2total, cat3total from training where user_id = ?");
stmt.bind(1, username);
const char *sqlString;
if (stmt.step())
{
if ((int)totals[0] > stmt.getIntColumn(0))
resp |= 1;
if ((int)totals[1] < stmt.getIntColumn(1))
resp |= 2;
if ((int)totals[2] < stmt.getIntColumn(2))
resp |= 4;
sqlString = "UPDATE training SET "
"cat1score1=?, cat1score2=?, cat1score3=?, cat1score4=?, cat1score5=?, cat1score6=?, cat1score7=?, cat1score8=?, "
"cat1bonus1=?, cat1bonus2=?, cat1total=?, "
"cat2score1=?, cat2score2=?, cat2score3=?, cat2score4=?, cat2score5=?, cat2score6=?, cat2score7=?, cat2score8=?, "
"cat2bonus1=?, cat2bonus2=?, cat2total=?, "
"cat3score1=?, cat3score2=?, cat3score3=?, cat3score4=?, cat3score5=?, cat3score6=?, cat3score7=?, cat3score8=?, "
"cat3bonus1=?, cat3bonus2=?, cat3total=? WHERE user_id=?";
}
else
{
resp |= 7;
sqlString = "INSERT INTO training ("
"cat1score1, cat1score2, cat1score3, cat1score4, cat1score5, cat1score6, cat1score7, cat1score8,"
"cat1bonus1, cat1bonus2, cat1total,"
"cat2score1, cat2score2, cat2score3, cat2score4, cat2score5, cat2score6, cat2score7, cat2score8,"
"cat2bonus1, cat2bonus2, cat2total,"
"cat3score1, cat3score2, cat3score3, cat3score4, cat3score5, cat3score6, cat3score7, cat3score8,"
"cat3bonus1, cat3bonus2, cat3total,"
"user_id) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
}
{
Statement stmt(database, sqlString);
int column = 1;
for (unsigned cat = 0; cat < 3; cat++)
{
for (unsigned score = 0; score < 8; score++, offset += 4)
stmt.bind(column++, scores[cat][score]);
for (unsigned bonus = 0; bonus < 2; bonus++, offset += 4)
stmt.bind(column++, bonuses[cat][bonus]);
stmt.bind(column++, totals[cat]);
}
stmt.bind(column++, username);
stmt.step();
}
std::vector<uint32_t> data(4);
write32((uint8_t *)data.data(), 0, resp);
write32((uint8_t *)data.data(), 4, totals[0]);
write32((uint8_t *)data.data(), 8, totals[1]);
write32((uint8_t *)data.data(), 12, totals[2]);
send(data);
}
}
}
receive();
}
void RankConnection::startTimer()
{
timer.expires_after(30s);
timer.async_wait([this](const std::error_code& ec) {
if (ec)
return;
std::error_code ignored;
socket.shutdown(asio::socket_base::shutdown_both, ignored);
});
}
RankAcceptor *RankAcceptor::Instance;
RankAcceptor::RankAcceptor(uint16_t httpPort, asio::io_context& io_context, const std::string& dbpath)
: io_context(io_context),
acceptor(asio::ip::tcp::acceptor(io_context,
asio::ip::tcp::endpoint(asio::ip::tcp::v4(), 10100))),
http(io_context, "0.0.0.0", httpPort)
{
asio::socket_base::reuse_address option(true);
acceptor.set_option(option);
database.open(dbpath);
{
Statement stmt(database, "SELECT name FROM sqlite_master WHERE type='table' AND name='ranking'");
if (!stmt.step())
{
WARN_LOG(Game::PropellerA, "Table 'ranking' doesn't exist. Creating it");
database.exec("CREATE TABLE ranking (id INTEGER PRIMARY KEY AUTOINCREMENT, "
"user_id VARCHAR(32) UNIQUE, "
"kills INTEGER DEFAULT 0, "
"wins INTEGER DEFAULT 0, "
"games INTEGER DEFAULT 0, "
"flightTime INTEGER DEFAULT 0, "
"flightDistance INTEGER DEFAULT 0, "
"shotDown INTEGER DEFAULT 0, "
"points INTEGER DEFAULT 0, "
"rank INTEGER DEFAULT 14)");
}
}
{
Statement stmt(database, "SELECT name FROM sqlite_master WHERE type='table' AND name='training'");
if (!stmt.step())
{
WARN_LOG(Game::PropellerA, "Table 'training' doesn't exist. Creating it");
database.exec("CREATE TABLE training (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id VARCHAR(32) UNIQUE, "
"cat1score1 INTEGER DEFAULT 0, cat1score2 INTEGER DEFAULT 0, cat1score3 INTEGER DEFAULT 0, cat1score4 INTEGER DEFAULT 0, "
"cat1score5 INTEGER DEFAULT 0, cat1score6 INTEGER DEFAULT 0, cat1score7 INTEGER DEFAULT 0, cat1score8 INTEGER DEFAULT 0,"
"cat1bonus1 INTEGER DEFAULT 0, cat1bonus2 INTEGER DEFAULT 0, cat1total INTEGER DEFAULT 0,"
"cat2score1 INTEGER DEFAULT 0, cat2score2 INTEGER DEFAULT 0, cat2score3 INTEGER DEFAULT 0, cat2score4 INTEGER DEFAULT 0, "
"cat2score5 INTEGER DEFAULT 0, cat2score6 INTEGER DEFAULT 0, cat2score7 INTEGER DEFAULT 0, cat2score8 INTEGER DEFAULT 0,"
"cat2bonus1 INTEGER DEFAULT 0, cat2bonus2 INTEGER DEFAULT 0, cat2total INTEGER DEFAULT 0,"
"cat3score1 INTEGER DEFAULT 0, cat3score2 INTEGER DEFAULT 0, cat3score3 INTEGER DEFAULT 0, cat3score4 INTEGER DEFAULT 0, "
"cat3score5 INTEGER DEFAULT 0, cat3score6 INTEGER DEFAULT 0, cat3score7 INTEGER DEFAULT 0, cat3score8 INTEGER DEFAULT 0,"
"cat3bonus1 INTEGER DEFAULT 0, cat3bonus2 INTEGER DEFAULT 0, cat3total INTEGER DEFAULT 0)");
}
}
using namespace std::placeholders;
http.addCgiHandler("/get_rank", std::bind(&RankAcceptor::handleRankHttp, this, _1, _2));
http.addCgiHandler("/get_training", std::bind(&RankAcceptor::handleTrainingHttp, this, _1, _2));
Instance = this;
}
void RankAcceptor::start()
{
RankConnection::Ptr newConnection = RankConnection::create(io_context, database);
acceptor.async_accept(newConnection->getSocket(),
[this, newConnection](const std::error_code& error) {
if (!error) {
INFO_LOG(Game::PropellerA, "New connection from %s", newConnection->getSocket().remote_endpoint().address().to_string().c_str());
newConnection->receive();
}
start();
});
}
void RankAcceptor::updateRank(const std::string& name, int kills, int wins, int games,
int flightTime, int flightDistance, int shotDown, int points)
{
Statement stmt(database, "UPDATE ranking SET kills = kills + ?, wins = wins + ?, games = games + ?,"
"flightTime = flightTime + ?, flightDistance = flightDistance + ?, shotDown = shotDown + ?, points = points + ?"
"WHERE user_id = ?");
stmt.bind(1, kills);
stmt.bind(2, wins);
stmt.bind(3, games);
stmt.bind(4, flightTime);
stmt.bind(5, flightDistance);
stmt.bind(6, shotDown);
stmt.bind(7, points);
stmt.bind(8, name);
stmt.step();
if (stmt.changedRows() == 0)
{
// New player
Statement stmt(database, "INSERT INTO ranking (kills, wins, games, flightTime, flightDistance, shotDown, points, user_id)"
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
stmt.bind(1, kills);
stmt.bind(2, wins);
stmt.bind(3, games);
stmt.bind(4, flightTime);
stmt.bind(5, flightDistance);
stmt.bind(6, shotDown);
stmt.bind(7, points);
stmt.bind(8, name);
stmt.step();
}
// Update rank (general -> airman basic)
{
Statement select(database, "SELECT points FROM ranking WHERE user_id = ?");
select.bind(1, name);
if (!select.step())
// shouldn't happen
return;
points = select.getIntColumn(0);
int rank = 14;
for (unsigned i = 0; i < std::size(RankPoints); i++)
if (points >= RankPoints[i]) {
rank = i + 1;
break;
}
Statement update(database, "UPDATE ranking SET rank = ? WHERE user_id = ?");
update.bind(1, rank);
update.bind(2, name);
update.step();
}
}
void RankAcceptor::handleRankHttp(const Request& request, Reply& reply)
{
try {
std::string sortBy = "kills";
if (!request.content.empty())
{
try {
json query = json::parse(request.content);
sortBy = query.at("sortBy").get<std::string>();
} catch (const json::exception& e) {
DEBUG_LOG(Game::PropellerA, "Invalid json: %s", e.what());
}
}
std::string select = "SELECT user_id, kills, wins, games, flightTime, flightDistance, shotDown, points, rank FROM ranking";
if (sortBy == "userName") {
select += " ORDER BY user_id";
}
else if (sortBy == "rank") {
select += " ORDER BY rank, user_id";
}
else if (sortBy == "kills" || sortBy == "wins" || sortBy == "games" || sortBy == "flightTime"
|| sortBy == "flightDistance" || sortBy == "shotDown" || sortBy == "points") {
select += " ORDER BY " + sortBy + " DESC, user_id";
}
else {
reply = Reply::stockReply(Reply::bad_request);
return;
}
Statement stmt(database, select.c_str());
json result = json::array();
while (stmt.step())
{
json entry;
entry["userName"] = stmt.getStringColumn(0);
entry["kills"] = stmt.getIntColumn(1);
entry["wins"] = stmt.getIntColumn(2);
entry["games"] = stmt.getIntColumn(3);
entry["flightTime"] = stmt.getIntColumn(4);
entry["flightDistance"] = stmt.getIntColumn(5);
entry["shotDown"] = stmt.getIntColumn(6);
entry["points"] = stmt.getIntColumn(7);
entry["rank"] = stmt.getIntColumn(8);
result.push_back(entry);
}
reply.setContent(result.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
} catch (const std::exception& e) {
ERROR_LOG(Game::PropellerA, "HTTP handler exception: %s", e.what());
reply = Reply::stockReply(Reply::internal_server_error);
}
}
static std::string formatTime(unsigned time)
{
char buf[16];
sprintf(buf, "%d'%02d\"%02d", time / 60 / 100, (time / 100) % 60, time % 100);
return buf;
}
void RankAcceptor::handleTrainingHttp(const Request& request, Reply& reply)
{
try {
std::string sortBy = "cat1total";
if (!request.content.empty())
{
try {
json query = json::parse(request.content);
sortBy = query.at("sortBy").get<std::string>();
} catch (const json::exception& e) {
DEBUG_LOG(Game::PropellerA, "Invalid json: %s", e.what());
}
}
std::string select = "SELECT user_id, cat1total, cat2total, cat3total FROM training";
if (sortBy == "userName") {
select += " ORDER BY user_id";
}
else if (sortBy == "cat1total") {
select += " ORDER BY " + sortBy + " DESC, user_id";
}
else if (sortBy == "cat2total" || sortBy == "cat3total") {
select += " ORDER BY " + sortBy + ", user_id";
}
else {
reply = Reply::stockReply(Reply::bad_request);
return;
}
Statement stmt(database, select.c_str());
json result = json::array();
while (stmt.step())
{
json entry;
entry["userName"] = stmt.getStringColumn(0);
entry["cat1total"] = stmt.getIntColumn(1);
entry["cat2total"] = formatTime(stmt.getIntColumn(2));
entry["cat3total"] = formatTime(stmt.getIntColumn(3));
result.push_back(entry);
}
reply.setContent(result.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
} catch (const std::exception& e) {
ERROR_LOG(Game::PropellerA, "HTTP handler exception: %s", e.what());
reply = Reply::stockReply(Reply::internal_server_error);
}
}