forked from vbawol/DayZhiveEpoch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HiveExtApp.cpp
1223 lines (1088 loc) · 35.8 KB
/
HiveExtApp.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2009-2012 Rajko Stojadinovic <http://github.com/rajkosto/hive>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "HiveExtApp.h"
#include <boost/bind.hpp>
#include <boost/optional.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/date_time/gregorian_calendar.hpp>
void HiveExtApp::setupClock()
{
namespace pt = boost::posix_time;
pt::ptime utc = pt::second_clock::universal_time();
pt::ptime now;
Poco::AutoPtr<Poco::Util::AbstractConfiguration> timeConf(config().createView("Time"));
string timeType = timeConf->getString("Type","Local");
if (boost::iequals(timeType,"Custom"))
{
now = utc;
const char* defOffset = "0";
string offsetStr = timeConf->getString("Offset",defOffset);
boost::trim(offsetStr);
if (offsetStr.length() < 1)
offsetStr = defOffset;
try
{
now += pt::duration_from_string(offsetStr);
}
catch(const std::exception&)
{
logger().warning("Invalid value for Time.Offset configuration variable (expected int, given: "+offsetStr+")");
}
}
else if (boost::iequals(timeType,"Static"))
{
now = pt::second_clock::local_time();
try
{
int hourOfTheDay = timeConf->getInt("Hour");
now -= pt::time_duration(now.time_of_day().hours(),0,0);
now += pt::time_duration(hourOfTheDay,0,0);
}
//do not change hour of the day if bad or missing value in config
catch(const Poco::NotFoundException&) {}
catch(const Poco::SyntaxException&)
{
string hourStr = timeConf->getString("Hour","");
boost::trim(hourStr);
if (hourStr.length() > 0)
logger().warning("Invalid value for Time.Hour configuration variable (expected int, given: "+hourStr+")");
}
//change the date
{
string dateStr = timeConf->getString("Date","");
boost::trim(dateStr);
if (dateStr.length() > 0) //only if non-empty value
{
namespace gr = boost::gregorian;
try
{
gr::date newDate = gr::from_uk_string(dateStr);
now = pt::ptime(newDate, now.time_of_day());
}
catch(const std::exception&)
{
logger().warning("Invalid value for Time.Date configuration variable (expected date, given: "+dateStr+")");
}
}
}
}
else
now = pt::second_clock::local_time();
_timeOffset = now - utc;
}
#include "Version.h"
int HiveExtApp::main( const std::vector<std::string>& args )
{
logger().information("HiveExt " + GIT_VERSION.substr(0,12));
setupClock();
if (!this->initialiseService())
{
logger().close();
return EXIT_IOERR;
}
return EXIT_OK;
}
HiveExtApp::HiveExtApp(string suffixDir) : AppServer("HiveExt",suffixDir), _serverId(-1)
{
//custom data retrieval
handlers[500] = boost::bind(&HiveExtApp::changeTableAccess,this,_1); //mechanism for setting up custom table permissions
handlers[501] = boost::bind(&HiveExtApp::dataRequest,this,_1,false); //sync load init and wait
handlers[502] = boost::bind(&HiveExtApp::dataRequest,this,_1,true); //async load init
handlers[503] = boost::bind(&HiveExtApp::dataStatus,this,_1); //retrieve request status and info
handlers[504] = boost::bind(&HiveExtApp::dataFetchRow,this,_1); //fetch row from completed query
handlers[505] = boost::bind(&HiveExtApp::dataClose,this,_1); //destroy any trace of request
//server and object stuff
handlers[302] = boost::bind(&HiveExtApp::streamObjects,this,_1); //Returns object count, superKey first time, rows after that
handlers[303] = boost::bind(&HiveExtApp::objectInventory,this,_1,false);
handlers[304] = boost::bind(&HiveExtApp::objectDelete,this,_1,false);
handlers[305] = boost::bind(&HiveExtApp::vehicleMoved,this,_1);
handlers[306] = boost::bind(&HiveExtApp::vehicleDamaged,this,_1);
handlers[307] = boost::bind(&HiveExtApp::getDateTime,this,_1);
handlers[308] = boost::bind(&HiveExtApp::objectPublish,this,_1);
// Custom to just return db ID for object UID
handlers[388] = boost::bind(&HiveExtApp::objectReturnId,this,_1);
// for maintain
handlers[396] = boost::bind(&HiveExtApp::datestampObjectUpdate,this,_1,false);
handlers[397] = boost::bind(&HiveExtApp::datestampObjectUpdate,this,_1,true);
// For traders
handlers[398] = boost::bind(&HiveExtApp::tradeObject,this,_1);
handlers[399] = boost::bind(&HiveExtApp::loadTraderDetails,this,_1);
// End custom
handlers[309] = boost::bind(&HiveExtApp::objectInventory,this,_1,true);
handlers[310] = boost::bind(&HiveExtApp::objectDelete,this,_1,true);
handlers[400] = boost::bind(&HiveExtApp::serverShutdown,this,_1); //Shut down the hiveExt instance
//player/character loads
handlers[101] = boost::bind(&HiveExtApp::loadPlayer,this,_1);
handlers[102] = boost::bind(&HiveExtApp::loadCharacterDetails,this,_1);
handlers[103] = boost::bind(&HiveExtApp::recordCharacterLogin,this,_1);
//character updates
handlers[201] = boost::bind(&HiveExtApp::playerUpdate,this,_1);
handlers[202] = boost::bind(&HiveExtApp::playerDeath,this,_1);
handlers[203] = boost::bind(&HiveExtApp::playerInit,this,_1);
handlers[204] = boost::bind(&HiveExtApp::updateGroup, this,_1); //update player group in player_data
handlers[205] = boost::bind(&HiveExtApp::updateGlobalCoins, this, _1); //update global coins in player_data - use existing calls 303/309 for saving object_data coins. use 201 for character coins
}
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
using boost::bad_lexical_cast;
void HiveExtApp::callExtension( const char* function, char* output, size_t outputSize )
{
Sqf::Parameters params;
try
{
params = lexical_cast<Sqf::Parameters>(function);
}
catch(bad_lexical_cast)
{
logger().error("Cannot parse function: " + string(function));
return;
}
int funcNum = -1;
try
{
string childIdent = boost::get<string>(params.at(0));
if (childIdent != "CHILD")
throw std::runtime_error("First element in parameters must be CHILD");
params.erase(params.begin());
funcNum = boost::get<int>(params.at(0));
params.erase(params.begin());
}
catch (...)
{
logger().error("Invalid function format: " + string(function));
return;
}
if (handlers.count(funcNum) < 1)
{
logger().error("Invalid method id: " + lexical_cast<string>(funcNum));
return;
}
if (logger().debug())
logger().debug("Original params: |" + string(function) + "|");
logger().information("Method: " + lexical_cast<string>(funcNum) + " Params: " + lexical_cast<string>(params));
HandlerFunc handler = handlers[funcNum];
Sqf::Value res;
boost::optional<ServerShutdownException> shutdownExc;
try
{
res = handler(params);
}
catch (const ServerShutdownException& e)
{
if (!e.keyMatches(_initKey))
{
logger().error("Actually not shutting down");
return;
}
shutdownExc = e;
res = e.getReturnValue();
}
catch (...)
{
logger().error("Error executing |" + string(function) + "|");
return;
}
string serializedRes = lexical_cast<string>(res);
logger().information("Result: " + serializedRes);
if (serializedRes.length() >= outputSize)
logger().error("Output size too big ("+lexical_cast<string>(serializedRes.length())+") for request : " + string(function));
else
strncpy_s(output,outputSize,serializedRes.c_str(),outputSize-1);
if (shutdownExc.is_initialized())
throw *shutdownExc;
}
namespace
{
Sqf::Parameters ReturnStatus(std::string status, Sqf::Parameters rest)
{
Sqf::Parameters outRet;
outRet.push_back(std::move(status));
for (size_t i=0; i<rest.size(); i++)
outRet.push_back(std::move(rest[i]));
return outRet;
}
template<typename T>
Sqf::Parameters ReturnStatus(std::string status, T other)
{
Sqf::Parameters rest; rest.push_back(std::move(other));
return ReturnStatus(std::move(status),std::move(rest));
}
Sqf::Parameters ReturnStatus(std::string status)
{
return ReturnStatus(std::move(status),Sqf::Parameters());
}
Sqf::Parameters ReturnBooleanStatus(bool isGood, string errorMsg = "")
{
string retStatus = "PASS";
if (!isGood)
retStatus = "ERROR";
if (errorMsg.length() < 1)
return ReturnStatus(std::move(retStatus));
else
return ReturnStatus(std::move(retStatus),std::move(errorMsg));
}
};
Sqf::Value HiveExtApp::getDateTime( Sqf::Parameters params )
{
namespace pt=boost::posix_time;
pt::ptime now = pt::second_clock::universal_time() + _timeOffset;
Sqf::Parameters retVal;
retVal.push_back(string("PASS"));
{
Sqf::Parameters dateTime;
dateTime.push_back(static_cast<int>(now.date().year()));
dateTime.push_back(static_cast<int>(now.date().month()));
dateTime.push_back(static_cast<int>(now.date().day()));
dateTime.push_back(static_cast<int>(now.time_of_day().hours()));
dateTime.push_back(static_cast<int>(now.time_of_day().minutes()));
retVal.push_back(dateTime);
}
return retVal;
}
#include <Poco/HexBinaryEncoder.h>
#include <Poco/HexBinaryDecoder.h>
#include "DataSource/ObjDataSource.h"
#include <Poco/RandomStream.h>
Sqf::Value HiveExtApp::streamObjects( Sqf::Parameters params)
{
bool legacyStream = boost::get<bool>(params.at(1));
if (_srvObjects.empty())
{
if (_initKey.length() < 1)
{
int serverId = boost::get<int>(params.at(0));
setServerId(serverId);
_objData->populateObjects(getServerId(), _srvObjects);
//set up initKey
{
boost::array<UInt8,16> keyData;
Poco::RandomInputStream().read((char*)keyData.c_array(),keyData.size());
std::ostringstream ostr;
Poco::HexBinaryEncoder enc(ostr);
enc.rdbuf()->setLineLength(0);
enc.write((const char*)keyData.data(),keyData.size());
enc.close();
_initKey = ostr.str();
}
Sqf::Parameters retVal;
retVal.push_back(string("ObjectStreamStart"));
retVal.push_back(static_cast<int>(_srvObjects.size()));
retVal.push_back(_initKey);
return retVal;
}
else
{
Sqf::Parameters retVal;
if (legacyStream) {
retVal.push_back(string("ERROR"));
retVal.push_back(string("Instance already initialized"));
} else {
string LastFileName = boost::get<string>(params.at(0));
remove(LastFileName.c_str()); //delete file
retVal.push_back(string("NOTICE"));
retVal.push_back(string("" + LastFileName + " has been deleted"));
}
return retVal;
}
}
else
{
if (legacyStream) {
Sqf::Parameters retVal = _srvObjects.front();
_srvObjects.pop();
return retVal;
} else {
string fileName = "ObjectData" + _initKey + ".sqf"; //filename will not be predictable if the init key is appended
std::ofstream ofs;
ofs.open(fileName, std::ofstream::out | std::ofstream::trunc); //clear file contents just incase it exists
ofs.close();
ofs.open(fileName, std::ofstream::out | std::ofstream::app); //open file again to write objects
int i = 0;
while (!(_srvObjects.empty())) { //write queue to file, formated as array in SQF
Sqf::Value writeVal = _srvObjects.front();
if (_srvObjects.size() == 1) {
ofs << writeVal;
ofs << "];";
}
else if (i < 1) {
ofs << "[";
ofs << writeVal;
ofs << ",";
i = 1;
}
else {
ofs << writeVal;
ofs << ",";
}
_srvObjects.pop();
}
ofs.close();
return fileName;
}
}
}
Sqf::Value HiveExtApp::objectInventory( Sqf::Parameters params, bool byUID /*= false*/ )
{
Int64 objectIdent = Sqf::GetBigInt(params.at(0));
Sqf::Value inventory = boost::get<Sqf::Parameters>(params.at(1));
Int64 coinsValue = -1;
try
{
if (!Sqf::IsNull(params.at(2))) {
coinsValue = Sqf::GetBigInt(params.at(2));
}
}
catch (const std::out_of_range&) {} //not using the coin system
if (objectIdent != 0) {
if (coinsValue >= 0) {
return ReturnBooleanStatus(_objData->updateObjectInventoryWCoins(getServerId(), objectIdent, byUID, inventory, coinsValue));
} else {
return ReturnBooleanStatus(_objData->updateObjectInventory(getServerId(), objectIdent, byUID, inventory));
}
}
return ReturnBooleanStatus(true);
}
Sqf::Value HiveExtApp::objectDelete( Sqf::Parameters params, bool byUID /*= false*/ )
{
Int64 objectIdent = Sqf::GetBigInt(params.at(0));
if (objectIdent != 0) //all the vehicles have objectUID = 0, so it would be bad to delete those
return ReturnBooleanStatus(_objData->deleteObject(getServerId(),objectIdent,byUID));
return ReturnBooleanStatus(true);
}
Sqf::Value HiveExtApp::datestampObjectUpdate(Sqf::Parameters params, bool byUID /*= false*/)
{
Int64 objectIdent = Sqf::GetBigInt(params.at(0));
if (objectIdent != 0) //all the vehicles have objectUID = 0, so it would be bad to delete those
return ReturnBooleanStatus(_objData->updateDatestampObject(getServerId(), objectIdent, byUID));
return ReturnBooleanStatus(true);
}
Sqf::Value HiveExtApp::vehicleMoved( Sqf::Parameters params )
{
Int64 objectIdent = Sqf::GetBigInt(params.at(0));
Sqf::Value worldspace = boost::get<Sqf::Parameters>(params.at(1));
double fuel = Sqf::GetDouble(params.at(2));
if (objectIdent > 0) //sometimes script sends this with object id 0, which is bad
return ReturnBooleanStatus(_objData->updateVehicleMovement(getServerId(),objectIdent,worldspace,fuel));
return ReturnBooleanStatus(true);
}
Sqf::Value HiveExtApp::vehicleDamaged( Sqf::Parameters params )
{
Int64 objectIdent = Sqf::GetBigInt(params.at(0));
Sqf::Value hitPoints = boost::get<Sqf::Parameters>(params.at(1));
double damage = Sqf::GetDouble(params.at(2));
if (objectIdent > 0) //sometimes script sends this with object id 0, which is bad
return ReturnBooleanStatus(_objData->updateVehicleStatus(getServerId(),objectIdent,hitPoints,damage));
return ReturnBooleanStatus(true);
}
Sqf::Value HiveExtApp::objectPublish( Sqf::Parameters params )
{
string className = boost::get<string>(params.at(1));
double damage = Sqf::GetDouble(params.at(2));
Int64 characterId = Sqf::GetBigInt(params.at(3));
Sqf::Value worldSpace = boost::get<Sqf::Parameters>(params.at(4));
Sqf::Value inventory = boost::get<Sqf::Parameters>(params.at(5));
Sqf::Value hitPoints = boost::get<Sqf::Parameters>(params.at(6));
double fuel = Sqf::GetDouble(params.at(7));
Int64 uniqueId = Sqf::GetBigInt(params.at(8));
return ReturnBooleanStatus(_objData->createObject(getServerId(),className,damage,characterId,worldSpace,inventory,hitPoints,fuel,uniqueId));
}
Sqf::Value HiveExtApp::objectReturnId( Sqf::Parameters params )
{
Int64 ObjectUID = Sqf::GetBigInt(params.at(0));
return _objData->fetchObjectId(getServerId(),ObjectUID);
}
#include "DataSource/CharDataSource.h"
Sqf::Value HiveExtApp::loadPlayer( Sqf::Parameters params )
{
string playerId = Sqf::GetStringAny(params.at(0));
string playerName = Sqf::GetStringAny(params.at(2));
return _charData->fetchCharacterInitial(playerId,getServerId(),playerName);
}
Sqf::Value HiveExtApp::loadCharacterDetails( Sqf::Parameters params )
{
Int64 characterId = Sqf::GetBigInt(params.at(0));
return _charData->fetchCharacterDetails(characterId);
}
Sqf::Value HiveExtApp::loadTraderDetails( Sqf::Parameters params )
{
if (_srvObjects.empty())
{
Int64 characterId = Sqf::GetBigInt(params.at(0));
_objData->populateTraderObjects(characterId, _srvObjects);
Sqf::Parameters retVal;
retVal.push_back(string("ObjectStreamStart"));
retVal.push_back(static_cast<int>(_srvObjects.size()));
return retVal;
}
else
{
Sqf::Parameters retVal = _srvObjects.front();
_srvObjects.pop();
return retVal;
}
}
Sqf::Value HiveExtApp::tradeObject( Sqf::Parameters params )
{
int traderObjectId = Sqf::GetIntAny(params.at(0));
int action = Sqf::GetIntAny(params.at(1));
return _charData->fetchTraderObject(traderObjectId, action);
}
Sqf::Value HiveExtApp::recordCharacterLogin( Sqf::Parameters params )
{
string playerId = Sqf::GetStringAny(params.at(0));
Int64 characterId = Sqf::GetBigInt(params.at(1));
int action = Sqf::GetIntAny(params.at(2));
return ReturnBooleanStatus(_charData->recordLogin(playerId,characterId,action));
}
Sqf::Value HiveExtApp::playerUpdate( Sqf::Parameters params )
{
Int64 characterId = Sqf::GetBigInt(params.at(0));
CharDataSource::FieldsType fields;
try
{
if (!Sqf::IsNull(params.at(1)))
{
Sqf::Parameters worldSpaceArr = boost::get<Sqf::Parameters>(params.at(1));
if (worldSpaceArr.size() > 0)
{
Sqf::Value worldSpace = worldSpaceArr;
fields["Worldspace"] = worldSpace;
}
}
if (!Sqf::IsNull(params.at(2)))
{
Sqf::Parameters inventoryArr = boost::get<Sqf::Parameters>(params.at(2));
if (inventoryArr.size() > 0)
{
Sqf::Value inventory = inventoryArr;
fields["Inventory"] = inventory;
}
}
if (!Sqf::IsNull(params.at(3)))
{
Sqf::Parameters backpackArr = boost::get<Sqf::Parameters>(params.at(3));
if (backpackArr.size() > 0)
{
Sqf::Value backpack = backpackArr;
fields["Backpack"] = backpack;
}
}
if (!Sqf::IsNull(params.at(4)))
{
Sqf::Parameters medicalArr = boost::get<Sqf::Parameters>(params.at(4));
if (medicalArr.size() > 0)
{
for (size_t i=0;i<medicalArr.size();i++)
{
if (Sqf::IsAny(medicalArr[i]))
{
logger().warning("update.medical["+lexical_cast<string>(i)+"] changed from any to []");
medicalArr[i] = Sqf::Parameters();
}
}
Sqf::Value medical = medicalArr;
fields["Medical"] = medical;
}
}
if (!Sqf::IsNull(params.at(5)))
{
bool justAte = boost::get<bool>(params.at(5));
if (justAte) fields["JustAte"] = true;
}
if (!Sqf::IsNull(params.at(6)))
{
bool justDrank = boost::get<bool>(params.at(6));
if (justDrank) fields["JustDrank"] = true;
}
if (!Sqf::IsNull(params.at(7)))
{
int moreKillsZ = boost::get<int>(params.at(7));
if (moreKillsZ > 0) fields["KillsZ"] = moreKillsZ;
}
if (!Sqf::IsNull(params.at(8)))
{
int moreKillsH = boost::get<int>(params.at(8));
if (moreKillsH > 0) fields["HeadshotsZ"] = moreKillsH;
}
if (!Sqf::IsNull(params.at(9)))
{
int distanceWalked = static_cast<int>(Sqf::GetDouble(params.at(9)));
if (distanceWalked > 0) fields["DistanceFoot"] = distanceWalked;
}
if (!Sqf::IsNull(params.at(10)))
{
int durationLived = static_cast<int>(Sqf::GetDouble(params.at(10)));
if (durationLived > 0) fields["Duration"] = durationLived;
}
if (!Sqf::IsNull(params.at(11)))
{
Sqf::Parameters currentStateArr = boost::get<Sqf::Parameters>(params.at(11));
if (currentStateArr.size() > 0)
{
Sqf::Value currentState = currentStateArr;
fields["CurrentState"] = currentState;
}
}
if (!Sqf::IsNull(params.at(12)))
{
int moreKillsHuman = boost::get<int>(params.at(12));
if (moreKillsHuman > 0) fields["KillsH"] = moreKillsHuman;
}
if (!Sqf::IsNull(params.at(13)))
{
int moreKillsBandit = boost::get<int>(params.at(13));
if (moreKillsBandit > 0) fields["KillsB"] = moreKillsBandit;
}
if (!Sqf::IsNull(params.at(14)))
{
string newModel = boost::get<string>(params.at(14));
fields["Model"] = newModel;
}
if (!Sqf::IsNull(params.at(15)))
{
int humanityDiff = static_cast<int>(Sqf::GetDouble(params.at(15)));
if (humanityDiff != 0) fields["Humanity"] = humanityDiff;
}
}
catch (const std::out_of_range&)
{
logger().warning("Update of character " + lexical_cast<string>(characterId) + " only had " + lexical_cast<string>(params.size()) + " parameters out of 16");
}
try
{
if (!Sqf::IsNull(params.at(16)))
{
Int64 coinsValue = static_cast<int>(Sqf::GetBigInt(params.at(16)));
fields["Coins"] = coinsValue;
}
} catch (const std::out_of_range&) {} //not using the coin system
if (fields.size() > 0) {
return ReturnBooleanStatus(_charData->updateCharacter(characterId, getServerId(), fields));
}
return ReturnBooleanStatus(true);
}
Sqf::Value HiveExtApp::playerInit( Sqf::Parameters params )
{
Int64 characterId = Sqf::GetBigInt(params.at(0));
Sqf::Value inventory = boost::get<Sqf::Parameters>(params.at(1));
Sqf::Value backpack = boost::get<Sqf::Parameters>(params.at(2));
return ReturnBooleanStatus(_charData->initCharacter(characterId,inventory,backpack));
}
Sqf::Value HiveExtApp::playerDeath( Sqf::Parameters params )
{
Int64 characterId = Sqf::GetBigInt(params.at(0));
int duration = static_cast<int>(Sqf::GetDouble(params.at(1)));
int infected = Sqf::GetIntAny(params.at(2));
return ReturnBooleanStatus(_charData->killCharacter(characterId,duration,infected));
}
Sqf::Value HiveExtApp::updateGroup(Sqf::Parameters params)
{
string playerId = Sqf::GetStringAny(params.at(0));
const Sqf::Value& playerGroup = boost::get<Sqf::Parameters>(params.at(2));
return ReturnBooleanStatus(_charData->updateCharacterGroup(playerId, getServerId(), playerGroup));
}
Sqf::Value HiveExtApp::updateGlobalCoins(Sqf::Parameters params)
{
string playerId = Sqf::GetStringAny(params.at(0));
Int64 coinsValue = Sqf::GetBigInt(params.at(2));
Int64 playerBank = Sqf::GetBigInt(params.at(3));
return ReturnBooleanStatus(_charData->updatePlayerCoins(playerId, getServerId(), coinsValue, playerBank));
}
namespace
{
class WhereVisitor : public boost::static_visitor<CustomDataSource::WhereElem>
{
public:
CustomDataSource::WhereElem operator()(const std::string& opStr) const
{
auto glue = CustomDataSource::WhereGlue(opStr);
if (!glue.isValid())
throw std::string("Logical operator unknown: '"+opStr+"'");
return glue;
}
CustomDataSource::WhereElem operator()(const Sqf::Parameters& condArr) const
{
const char* currElem;
try
{
currElem = "COLUMN";
const auto& columnStr = boost::get<string>(condArr.at(0));
currElem = "OP";
const auto& opStr = boost::get<string>(condArr.at(1));
auto opReal = CustomDataSource::WhereCond::OperandFromStr(opStr);
if (opReal >= CustomDataSource::WhereCond::OP_COUNT)
throw std::string("Condition has unknown OP '" + opStr + "'");
string constantStr;
if (opReal != CustomDataSource::WhereCond::OP_ISNULL &&
opReal != CustomDataSource::WhereCond::OP_ISNOTNULL)
{
currElem = "CONSTANT";
constantStr = boost::get<string>(condArr.at(2));
}
auto cond = CustomDataSource::WhereCond(columnStr,opReal,constantStr);
if (!cond.isValid())
throw std::string("Condition COLUMN is empty");
return cond;
}
catch(const boost::bad_get&)
{
throw std::string("Condition " + string(currElem) + " not a string");
}
catch(const std::out_of_range&)
{
throw std::string("Condition doesn't have " + string(currElem) + " element");
}
}
template <typename T> CustomDataSource::WhereElem operator()(T) const
{
throw boost::bad_get();
}
};
std::string TokenToHex(UInt32 token)
{
std::ostringstream ostr;
Poco::HexBinaryEncoder enc(ostr);
enc.rdbuf()->setLineLength(0);
enc.write((const char*)&token,sizeof(token));
enc.close();
return ostr.str();
}
UInt32 HexToToken(std::string strData)
{
strData.erase(remove_if(strData.begin(),strData.end(),::isspace), strData.end());
if (strData.length() != sizeof(UInt32)*2)
throw boost::bad_lexical_cast();
UInt32 token = 0;
std::istringstream istr(strData);
try
{
Poco::HexBinaryDecoder dec(istr);
dec.read((char*)&token,sizeof(token));
}
catch(const Poco::DataFormatException&)
{
throw boost::bad_lexical_cast();
}
return token;
}
UInt32 FetchToken(const Sqf::Parameters& params)
{
try
{
return HexToToken(Sqf::GetStringAny(params.at(0)));
}
catch(const boost::bad_lexical_cast&)
{
//invalid characters in string
return 0;
}
catch(const boost::bad_get&)
{
//not a string
return 0;
}
catch(const std::out_of_range&)
{
//doesn't even exist
return 0;
}
}
};
//CHILD:501:DbName.TableName:["ColumnName1","ColumnName2"]:["NOT",["ColumnNameX","<","Constant"]],"AND",["SomeOtherColumn","RLIKE","[0-9]"]]:[0,50]:
//CHILD:FUNC:TBLNAME:COLUMNSARR:WHEREARR:LIMITS
//If you use function number 501 the request is synchronous (and query errors are returned immediately)
//otherwise, function number 502 is asynchronous, which means the data might be in WAIT state for a while
//DbName in TBLNAME is either Character or Object
//The requested Table must be previously-enabled for custom data queries through HiveExt.ini
//COLUMNSARR is an array of column names to fetch
//alternatively, COLUMNSARR can be a single string called COUNT to get the row count ONLY
//WHEREARR is an array, whose elements can either be:
//1. a single string, which denotes the boolean-link operator to apply
//in this case, it can be "AND", "OR", "NOT", or any number of "(" or ")"
//2. an array of 3 elements [COLUMN,OP,CONSTANT], all 3 elements should be strings
//COLUMN is the column on which comparison OP will be applied to
//you can append .length to COLUMN to use it's length instead of it's value
//OP can be "<", ">", "=", "<>", "IS NULL", "IS NOT NULL", "LIKE", "NOT LIKE", "RLIKE", "NOT RLIKE"
//CONSTANT is a literal value with which to perform the comparison
//in the LIKE/RLIKE case, it's either a LIKE formatting string, or a REGEXP formatted string
//LIMITS is either an array of two numbers, [OFFSET, COUNT]
//or a single number COUNT
//this corresponds to the SQL versions of LIMIT COUNT or LIMIT OFFSET,COUNT
//this parameter is optional, you can omit it by just not having that :[*] at the end
//The return value is either ["PASS",UNIQID] where UNIQID represents the string token that you can later use to retrieve results
//or ["ERROR",ERRORDESCR] where ERRORDESCR is a description of the error that happened
Sqf::Value HiveExtApp::dataRequest( Sqf::Parameters params, bool async )
{
auto retErr = [](string errMsg) -> Sqf::Value
{
vector<Sqf::Value> errRtn; errRtn.push_back(string("ERROR")); errRtn.push_back(std::move(errMsg));
return errRtn;
};
auto tableName = boost::get<string>(params.at(0));
vector<string> fields;
{
int currIdx = -1;
try
{
const auto& sqfFields = boost::get<Sqf::Parameters>(params.at(1));
fields.reserve(sqfFields.size());
for (size_t i=0; i<sqfFields.size(); i++)
{
currIdx++;
fields.push_back(boost::get<string>(sqfFields[i]));
}
}
catch(const boost::bad_get&)
{
string errorMsg;
if (currIdx < 0)
errorMsg = "FIELDS not an array";
else
errorMsg = "FIELDS[" + boost::lexical_cast<string>(currIdx) + "] not a string";
}
}
vector<CustomDataSource::WhereElem> where;
{
const auto& whereSqfArr = boost::get<Sqf::Parameters>(params.at(2));
for (size_t i=0; i<whereSqfArr.size(); i++)
{
try
{
where.push_back(boost::apply_visitor(WhereVisitor(),whereSqfArr[i]));
}
catch (const boost::bad_get&)
{
string errorMsg = "WHERE[" + boost::lexical_cast<string>(i) + "] not a string or array";
return retErr(errorMsg);
}
catch(const std::string& e)
{
string errorMsg = "WHERE[" + boost::lexical_cast<string>(i) + "] " + e;
return retErr(errorMsg);
}
}
}
Int64 limitCount = -1;
Int64 limitOffset = 0;
if (params.size() >= 4)
{
try
{
limitCount = Sqf::GetBigInt(params[3]);
}
catch (const boost::bad_get&)
{
try
{
const auto& limitArr = boost::get<Sqf::Parameters>(params[3]);
if (limitArr.size() < 2)
throw boost::bad_get();
limitOffset = Sqf::GetBigInt(limitArr[0]);
limitCount = Sqf::GetBigInt(limitArr[1]);
}
catch (const boost::bad_get&)
{
string errorMsg = "LIMIT in invalid format: '"+boost::lexical_cast<string>(params[3])+"'";
return retErr(errorMsg);
}
}
}
try
{
UInt32 token = _customData->dataRequest(tableName,fields,where,limitCount,limitOffset,async);
vector<Sqf::Value> goodRtn;
goodRtn.push_back(string("PASS"));
goodRtn.push_back(TokenToHex(token));
return goodRtn;
}
catch(const CustomDataSource::DataException& e)
{
return retErr(e.toString());
}
}
namespace
{
Sqf::Value ReturnBadToken(bool reallyBad = true)
{
return ReturnStatus("UNKID",reallyBad);
}
Sqf::Value ReturnError(std::string errMsg)
{
return ReturnBooleanStatus(false,std::move(errMsg));
}
Sqf::Value HandleRequestState(CustomDataSource::RequestState state)
{
if (state == CustomDataSource::REQ_PENDING)
return ReturnStatus("WAIT");
else if (state == CustomDataSource::REQ_NOMOREROWS)
return ReturnStatus("NOMORE");
else if (state == CustomDataSource::REQ_UNKNOWN)
return ReturnBadToken(false);
else
return ReturnError("Unknown status");
}
};
//CHILD:503:UNIQID:
//UNIQID is the string you received with a call to 501/502
//the return value is either
//["PASS",numRows,numFields,[field1,field2]]
//["WAIT"]
//["ERROR",ERRORDESCR]
//["UNKID",isInvalidId]
//"PASS" return code gives you information about the query,
//like total number of rows, number of fields, and the field names in an array
//"WAIT" = the asynchronous operation didn't complete yet
//"ERROR" = the asynchronous operation failed, error info is in ERRORDESCR
//if you get this result, the UNIQID will not be usable anymore (not even for status)
//"UNKID" = unknown UNIQID specified, or it has been cleared (by fetching ERROR status or last row)
//additiionally, if isInvalidId is set to true, then the UNIQID is malformed/missing and would never have worked
Sqf::Value HiveExtApp::dataStatus( Sqf::Parameters params )
{
UInt32 token = FetchToken(params);
if (!token)
return ReturnBadToken();
try
{
UInt64 numRows = 0;
size_t numCols = 0;
vector<string> fields;
auto reqStatus = _customData->requestStatus(token,numRows,numCols,fields);
if (reqStatus == CustomDataSource::REQ_OK)
{
Sqf::Parameters retVal;
retVal.push_back(static_cast<Int64>(numRows));
retVal.push_back(static_cast<Int64>(numCols));
{
Sqf::Parameters realFields;
for (auto it=fields.begin(); it!=fields.end(); ++it)
realFields.push_back(Sqf::Value(std::move(*it)));
retVal.push_back(std::move(realFields));
}
return ReturnStatus("PASS",std::move(retVal));
}
return HandleRequestState(reqStatus);
}
catch(const CustomDataSource::DataException& e)
{
return ReturnError(e.toString());
}
}