-
Notifications
You must be signed in to change notification settings - Fork 2
/
asip.cpp
487 lines (439 loc) · 15.1 KB
/
asip.cpp
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include "asip.hpp"
#include "io.hpp"
#include "asip1.hpp"
ASIP::ASIP(QNetworkAccessManager& networkAccessManager_,const QString& serverURL,QObject* const parent,Data startingData) :
QObject(parent),
networkAccessManager(networkAccessManager_),
mostRecentData(std::move(startingData)),
server(getNetworkRequest(serverURL)),
gameStateReply(nullptr)
{
}
ASIP::Data ASIP::processReply(QNetworkReply& networkReply)
{
lastReplyTime=QDateTime::currentDateTimeUtc();
networkReply.deleteLater();
runtime_assert(networkReply.error()==QNetworkReply::NoError,networkReply.errorString());
const Status oldStatus=getStatus();
const auto rawData=networkReply.readAll();
const auto replyData=getReplyData(rawData);
updateCache(replyData);
timeEstimator.add(networkReply.property("post_time").toDateTime(),lastReplyTime,instantResponse(networkReply),replyData.value("timeonserver"));
const auto error=replyData.find("error");
if (error!=replyData.end())
throw std::runtime_error(error.value().toString().toStdString());
const Status newStatus=getStatus();
if (oldStatus!=newStatus)
emit statusChanged(oldStatus,newStatus);
return replyData;
}
QUrl ASIP::serverURL() const
{
return server.url();
}
qint64 ASIP::timeSinceLastReply() const
{
return lastReplyTime.msecsTo(QDateTime::currentDateTimeUtc());
}
QString ASIP::username() const
{
const QReadLocker readLocker(&mostRecentData_mutex);
return get<QString>("username");
}
QNetworkReply* ASIP::login(QObject* const requester,const QString& username,const QString& password)
{
return post(requester,{{"action","login"},{"username",username},{"password",password}});
}
QNetworkReply* ASIP::createGame(QObject* const requester,const QString& timeControl,const bool rated,const Side side)
{
return post(requester,{{"action","newgame"},dataPair("sid"),{"role",QString(toLetter(side))},{"timecontrol",timeControl},{"rated",rated ? "1" : "0"}});
}
QNetworkReply* ASIP::myGames()
{
return gameListAction("mygames",MY_GAMES);
}
QNetworkReply* ASIP::invitedGames()
{
return gameListAction("invitedmegames",INVITED_GAMES);
}
QNetworkReply* ASIP::openGames()
{
return gameListAction("opengames",OPEN_GAMES);
}
void ASIP::enterGame(QObject* const requester,const QString& gameID,const Side side,const std::function<void(QNetworkReply*)> networkReplyAction)
{
const auto role=(side==NO_SIDE ? "v" : QString(toLetter(side)));
const auto networkReply=post(requester,{{"action","reserveseat"},dataPair("sid"),{"gid",gameID},{"role",role}});
networkReplyAction(networkReply);
}
QNetworkReply* ASIP::cancelGame(QObject* const requester,const QString& gameID)
{
return post(requester,{{"action","cancelopengame"},dataPair("sid"),{"gid",gameID}});
}
QNetworkReply* ASIP::logout(QObject* const requester)
{
QReadLocker readLocker(&mostRecentData_mutex);
const auto sid=mostRecentData.find("sid");
if (sid!=mostRecentData.end()) {
const auto sid_value=sid.value();
readLocker.unlock();
return post(requester,{{"action","logout"},{"sid",sid_value.toString()}});
}
return nullptr;
}
std::vector<ASIP::GameListCategory> ASIP::availableGameListCategories() const
{
return {MY_GAMES,INVITED_GAMES,OPEN_GAMES};
}
std::vector<QNetworkReply*> ASIP::state()
{
return {myGames(),invitedGames(),openGames()};
}
std::vector<ASIP::GameInfo> ASIP::getGameList(QNetworkReply& networkReply,const GameListCategory gameListCategory)
{
const auto replyData=processReply(networkReply);
unsigned int numGames=-1;
std::vector<ASIP::GameInfo> result;
const auto self=username();
for (auto entry=replyData.begin();entry!=replyData.end();++entry) {
if (entry.key()=="num")
numGames=entry.value().toUInt();
else {
const size_t index=entry.key().toUInt();
result.resize(std::max(result.size(),index));
GameInfo& gameInfo=result[index-1];
std::stringstream ss;
ss<<entry.value().toString().toStdString();
std::string line;
QString opponent;
Side role=NO_SIDE;
while (getline(ss,line)) {
const auto divider=line.find('=');
const std::string key=line.substr(0,divider);
const std::string value=line.substr(divider+1);
if (key=="gid")
gameInfo.id=QString::fromStdString(value);
else if (key=="role")
role=toSide(value[0]);
else if (key=="timecontrol")
gameInfo.timeControl=QString::fromStdString(value);
else if (key=="rated")
gameInfo.rated=(value=="1");
else if (key=="postal")
gameInfo.postal=(value=="1");
else if (key=="createdts")
gameInfo.createdts=stoull(value);
else if (key=="opponent")
opponent=QString::fromStdString(value);
}
runtime_assert(role!=NO_SIDE,"No role.");
gameInfo.players[otherSide(role)]=opponent;
if (gameListCategory==MY_GAMES)
gameInfo.players[role]=self;
}
}
runtime_assert(numGames==result.size(),"Mismatching number of games.");
return result;
}
std::unique_ptr<ASIP> ASIP::getGame(QNetworkReply& networkReply)
{
processReply(networkReply);
return getGame();
}
std::unique_ptr<ASIP> ASIP::getGame() const
{
QReadLocker readLocker(&mostRecentData_mutex);
auto startingData=mostRecentData;
readLocker.unlock();
startingData.remove("sid");
auto game=create(networkAccessManager,mostRecentData.value("gsurl").toString(),nullptr,startingData);
connect(game.get(),&ASIP::statusChanged,this,&ASIP::childStatusChanged);
return game;
}
QNetworkReply* ASIP::gameListAction(const QString& action,const ASIP::GameListCategory gameListCategory)
{
const auto networkReply=post(this,{{"action",action},dataPair("sid")});
connect(networkReply,&QNetworkReply::finished,this,[this,networkReply,gameListCategory] {
try {
emit sendGameList(gameListCategory,getGameList(*networkReply,gameListCategory));
}
catch (const std::exception& exception) {
emit error(exception);
}
});
return networkReply;
}
bool ASIP::isEqualGame(const ASIP& otherGame) const
{
if (serverURL()!=otherGame.serverURL())
return false;
const QReadLocker readLocker(&mostRecentData_mutex);
const QReadLocker otherReadLocker(&otherGame.mostRecentData_mutex);
return mostRecentData.value("grid")==otherGame.mostRecentData.value("grid") &&
mostRecentData.value("tid")==otherGame.mostRecentData.value("tid");
}
Side ASIP::role() const
{
const QReadLocker readLocker(&mostRecentData_mutex);
return toSide(get<QString>("role")[0].toLatin1());
}
bool ASIP::gameStateAvailable() const
{
const QReadLocker readLocker(&mostRecentData_mutex);
return mostRecentData.contains("auth");
}
ASIP::Status ASIP::getStatus() const
{
const QReadLocker readLocker(&mostRecentData_mutex);
if (mostRecentData.contains("result"))
return FINISHED;
else if (mostRecentData.contains("starttime"))
return LIVE;
else if (mostRecentData.value("canstart")==1)
return UNSTARTED;
else
return OPEN;
}
Side ASIP::sideToMove() const
{
const QReadLocker readLocker(&mostRecentData_mutex);
return toSide(get<QString>("turn")[0].toLatin1());
}
std::tuple<GameTree,size_t,bool> ASIP::getMoves(NodePtr root) const
{
const QReadLocker readLocker(&mostRecentData_mutex);
return toTree(get<QString>("moves").toStdString(),std::move(root));
}
std::array<QString,NUM_SIDES> ASIP::getAnnotatedPlayers() const
{
const QReadLocker readLocker(&mostRecentData_mutex);
return {mostRecentData.value("wplayer").toString(),mostRecentData.value("bplayer").toString()};
}
std::array<QString,NUM_SIDES> ASIP::getPlayers() const
{
auto result=getAnnotatedPlayers();
const QString annotation="* ";
for (auto& annotedPlayer:result)
if (annotedPlayer.startsWith(annotation))
annotedPlayer.remove(0,annotation.size());
return result;
}
Result ASIP::getResult() const
{
const QReadLocker readLocker(&mostRecentData_mutex);
const auto result=mostRecentData.value("result").toString().toStdString();
if (result.size()>=2)
return {toSide(result[0]),toEndCondition(result[1])};
else
return {NO_SIDE,NO_END};
}
std::array<std::array<qint64,3>,NUM_SIDES> ASIP::getTimes() const
{
QReadLocker readLocker(&mostRecentData_mutex);
const Side sideToMove_=sideToMove();
runtime_assert(sideToMove_!=NO_SIDE,"No side to move.");
const auto status=getStatus();
const auto moveTime=mostRecentData.value("tcmove").toLongLong();
auto maxTurnTime=mostRecentData.value("tcturntime").toLongLong()*1000;
if (maxTurnTime==0)
maxTurnTime=std::numeric_limits<qint64>::max();
std::array<std::array<qint64,3>,NUM_SIDES> result;
for (Side side=FIRST_SIDE;side<NUM_SIDES;increment(side)) {
auto& hard=std::get<0>(result[side]);
auto& potential=std::get<1>(result[side]);
auto& used=std::get<2>(result[side]);
const auto sideLetter=toLetter(side);
qint64 moveTime_;
if (side==FIRST_SIDE && sideToMove_==SECOND_SIDE && get<int>("plycount")==1 && mostRecentData.contains("tcmoveorig"))
moveTime_=get<qint64>("tcmoveorig");
else
moveTime_=moveTime;
const auto reserveString=QString("tc")+sideLetter+"reserve";
potential=(moveTime_+mostRecentData.value(mostRecentData.contains(reserveString+'2') ? reserveString+'2' : reserveString).toLongLong())*1000;
hard=std::min(maxTurnTime,potential);
used=mostRecentData.value(sideLetter+QString("used")).toLongLong()*1000;
if (side==sideToMove_) {
if (status==LIVE)
used+=timeEstimator.estimatedExtraTime();
hard-=used;
potential-=used;
if (status==LIVE && sideToMove_==role()) {
const auto predictedSendLag=timeEstimator.estimatedRoundTripTime()/2;
hard-=predictedSendLag;
potential-=predictedSendLag;
}
}
}
return result;
}
void ASIP::sit()
{
QNetworkReply* sitReply=post(this,{{"action","sit"},dataPair("tid"),dataPair("grid")});
connect(sitReply,&QNetworkReply::finished,this,[=] {
try {
processReply(*sitReply);
gameStateReply=post(this,{{"action","gamestate"},dataPair("sid")});
connect(gameStateReply,&QNetworkReply::finished,this,[=] {
try {
processReply(*gameStateReply);
update(false);
}
catch (const std::exception& exception) {
gameStateReply=nullptr;
emit error(exception);
}
});
}
catch (const std::exception& exception) {
emit error(exception);
}
});
}
void ASIP::forceUpdate()
{
if (gameStateReply!=nullptr) {
disconnect(gameStateReply,&QNetworkReply::finished,nullptr,nullptr);
gameStateReply->deleteLater();
}
gameStateReply=post(this,{{"action","gamestate"},dataPair("sid"),{"wait","0"},{"maxwait","0"}});
connect(gameStateReply,&QNetworkReply::finished,this,[=] {
try {
processReply(*gameStateReply);
update(true);
}
catch (const std::exception& exception) {
gameStateReply=nullptr;
emit error(exception);
}
});
}
void ASIP::start()
{
postAuthDependingAction("startgame");
}
void ASIP::sendMove(const QString& move)
{
postAuthDependingAction("move",{{"move",move}});
}
void ASIP::resign()
{
postAuthDependingAction("resign");
}
void ASIP::requestTakeback()
{
postAuthDependingAction("takeback",{{"takeback","req"}});
}
void ASIP::replyToTakeback(const bool accepted)
{
postAuthDependingAction("takebackreply",{{"takebackreply",accepted ? "yes" : "no"}});
}
void ASIP::sendChat(const QString& chat)
{
postAuthDependingAction("chat",{{"chat",chat}});
}
void ASIP::leave()
{
if (role()!=NO_SIDE)
postAuthDependingAction("leave");
}
void ASIP::update(const bool hardSynchronization)
{
emit updated(hardSynchronization);
QReadLocker readLocker(&mostRecentData_mutex);
const auto oldMoves=mostRecentData.value("moves").toString();
const auto oldChat=mostRecentData.value("chat").toString();
readLocker.unlock();
gameStateReply=post(this,{{"action","updategamestate"},dataPair("sid"),{"wait","1"},dataPair("lastchange"),dataPair("moveslength"),dataPair("chatlength")});
connect(gameStateReply,&QNetworkReply::finished,this,[=] {
try {
processReply(*gameStateReply);
QWriteLocker writeLocker(&mostRecentData_mutex);
auto& newMoves=mostRecentData["moves"];
auto& newChat=mostRecentData["chat"];
newMoves=oldMoves+newMoves.toString();
newChat=oldChat+newChat.toString();
writeLocker.unlock();
update(false);
}
catch (const std::exception& exception) {
gameStateReply=nullptr;
emit error(exception);
}
});
}
void ASIP::postAuthDependingAction(const QString& action,const std::initializer_list<std::pair<QString,QString> >& extraItems)
{
const auto doAction=[=]{
std::vector<std::pair<QString,QString> > items={{"action",action},dataPair("sid"),dataPair("auth")};
items.insert(items.end(),extraItems);
QNetworkReply* actionReply=post(this,items);
connect(actionReply,&QNetworkReply::finished,[=]{
try {
processReply(*actionReply);
}
catch (const std::exception& exception) {
emit error(exception);
}
});};
QReadLocker readLocker(&mostRecentData_mutex);
if (mostRecentData.contains("auth")) {
readLocker.unlock();
doAction();
}
else {
const QObject* const oneTime=new QObject(this);
connect(this,&ASIP::updated,oneTime,[=]{
delete oneTime;
doAction();
});
}
}
std::pair<QString,QString> ASIP::dataPair(const QString& key) const
{
const QReadLocker readLocker(&mostRecentData_mutex);
const auto iterator=mostRecentData.find(key);
return {iterator.key(),iterator.value().toString()};
}
QNetworkReply* ASIP::post(QObject* const requester,const std::vector<std::pair<QString,QString> >& items)
{
QWriteLocker writeLocker(&mostRecentData_mutex);
for (const auto& item:items)
mostRecentData.insert(item.first,item.second);
writeLocker.unlock();
const auto rawData=getRequestData(items);
const auto networkReply=networkAccessManager.post(server,rawData);
networkReply->setProperty("post_time",QDateTime::currentDateTimeUtc());
for (const auto& item:items)
networkReply->setProperty(qPrintable(item.first),item.second);
if (requester!=nullptr)
networkReply->setParent(requester);
return networkReply;
}
void ASIP::synchronizeData(const ASIP& source)
{
QWriteLocker writeLocker(&mostRecentData_mutex);
QReadLocker readLocker(&source.mostRecentData_mutex);
mostRecentData=source.mostRecentData;
}
template<class Type>
Type ASIP::get(const QString& key) const
{
runtime_assert(mostRecentData.contains(key),"Key "+key.toStdString()+" not present.");
const auto value=mostRecentData.value(key);
runtime_assert(value.canConvert<Type>(),"Value "+value.toString()+" not convertible to "+QMetaType::typeName(qMetaTypeId<Type>())+".");
return value.value<Type>();
}
void ASIP::updateCache(const Data& replyData)
{
const QWriteLocker writeLocker(&mostRecentData_mutex);
for (auto iter=replyData.begin();iter!=replyData.end();++iter)
mostRecentData.insert(iter.key(),iter.value());
}
bool ASIP::instantResponse(const QNetworkReply& networkReply)
{
return ((networkReply.property("action")!="gamestate" &&
networkReply.property("action")!="updategamestate") ||
networkReply.property("wait")!="1");
}