forked from N00byKing/APCpp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Archipelago.cpp
1124 lines (1037 loc) · 34.8 KB
/
Archipelago.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
#include "Archipelago.h"
#include "ixwebsocket/IXNetSystem.h"
#include "ixwebsocket/IXWebSocket.h"
#include "ixwebsocket/IXUserAgent.h"
#include <cstddef>
#include <cstdint>
#include <random>
#include <fstream>
#include <iostream>
#include <json/json.h>
#include <json/reader.h>
#include <json/value.h>
#include <json/writer.h>
#include <deque>
#include <set>
#include <string>
#include <chrono>
#include <functional>
#include <utility>
#include <vector>
constexpr int AP_OFFLINE_SLOT = 1404;
#define AP_OFFLINE_NAME "You"
//Setup Stuff
bool init = false;
bool auth = false;
bool refused = false;
bool multiworld = true;
bool isSSL = true;
bool disconnecting = false;
int ap_player_id;
int ap_player_team;
std::string ap_player_name;
std::string ap_deathlink_alias;
size_t ap_player_name_hash;
std::string ap_ip;
std::string ap_game;
std::string ap_slot_game;
std::string ap_passwd;
std::uint64_t ap_uuid = 0;
std::set<std::string> ap_tags;
std::set<int64_t> missing_locs;
std::mt19937 rando;
AP_NetworkVersion client_version = {0,4,4}; // Default for compatibility reasons
//Deathlink Stuff
bool deathlinkstat = false;
bool deathlinksupported = false;
bool enable_deathlink = false;
bool force_deathlink = false; //enable it regardless of slot data
int deathlink_amnesty = 0;
int cur_deathlink_amnesty = 0;
int force_deathlink_amnesty = -1;
// Message System
std::deque<AP_Message*> messageQueue;
bool queueitemrecvmsg = true;
// Data Maps
std::map<int, AP_NetworkPlayer> map_players;
std::map<std::pair<std::string,int64_t>, std::string> map_location_id_name;
std::map<std::pair<std::string,int64_t>, std::string> map_item_id_name;
// Callback function pointers
void (*resetItemValues)();
void (*getitemfunc)(int64_t,bool);
std::function<void(int64_t)> checklocfunc;
std::function<void(std::vector<AP_NetworkItem>)> locinfofunc;
void (*recvdeath)() = nullptr;
void (*setreplyfunc)(AP_SetReply) = nullptr;
std::function<void(std::string,std::string)> recvdeath2;
std::function<void()> onConnectedFunc;
std::function<void(AP_RoomInfo const&)> preConnectFunc;
std::function<void(std::string)> onConnectErrFunc;
std::function<void(std::string)> onLogMessage;
std::function<void(std::string)> onErrMessage;
// Serverdata Management
std::map<std::string,AP_DataType> map_serverdata_typemanage;
AP_GetServerDataRequest resync_serverdata_request;
size_t last_item_idx = 0;
// Singleplayer Seed Info
std::string sp_save_path;
Json::Value sp_save_root;
//Misc Data for Clients
AP_RoomInfo lib_room_info;
//Server Data Stuff
std::map<std::string, AP_GetServerDataRequest*> map_server_data;
//Slot Data Stuff
std::map<std::string, void (*)(int)> map_slotdata_callback_int;
std::map<std::string, void (*)(std::string)> map_slotdata_callback_raw;
std::map<std::string, void (*)(std::map<int,int>)> map_slotdata_callback_mapintint;
std::vector<std::string> slotdata_strings;
// Datapackage Stuff
std::string const datapkg_cache_path = "APCpp_datapkg.cache";
Json::Value datapkg_cache;
std::set<std::string> datapkg_outdated_games;
ix::WebSocket webSocket;
Json::Reader reader;
Json::FastWriter writer;
Json::Value sp_ap_root;
// PRIV Func Declarations Start
void AP_Init_Generic();
bool parse_response(std::string msg, std::string &request);
void APSend(std::string req);
void WriteFileJSON(Json::Value val, std::string path);
std::string getItemName(std::string game, int64_t id);
std::string getLocationName(std::string game, int64_t id);
void parseDataPkg(Json::Value new_datapkg);
void parseDataPkg();
AP_NetworkPlayer getPlayer(int team, int slot);
bool useDeathlink();
void updateAPTags();
int getDeathAmnesty();
// PRIV Func Declarations End
//LOCAL EDITS
void AP_Log(std::string const& str)
{
if(onLogMessage)
onLogMessage(str);
else std::cout << "AP: " << str << std::endl;
}
void AP_Error(std::string const& str)
{
if(onErrMessage)
onErrMessage(str);
else std::cerr << "AP: " << str << std::endl;
}
void AP_Disconnect() //Disconnect from a slot, call AP_Init again to reconnect
{
init = false;
auth = false;
refused = false;
multiworld = true;
enable_deathlink = false;
disconnecting = true;
webSocket.stop();
messageQueue.clear();
map_players.clear();
map_location_id_name.clear();
map_item_id_name.clear();
slotdata_strings.clear();
missing_locs.clear();
}
void AP_SetTags(std::set<std::string> tags) //Set the slot's tags
{
if(useDeathlink())
tags.insert("DeathLink");
else tags.erase("DeathLink");
if(tags == ap_tags)
return;
ap_tags = tags;
updateAPTags();
}
std::set<std::string> const& AP_GetTags()
{
return ap_tags;
}
void AP_SetDeathLinkForced(bool forced) //Set if DeathLink is *forced* on, or not.
{
if(force_deathlink == forced)
return; //unchanged
force_deathlink = forced;
if(ap_tags.contains("DeathLink") == useDeathlink())
return; //unchanged
AP_SetTags(ap_tags);
}
void AP_SetDeathAmnestyForced(int amnesty)
{
force_deathlink_amnesty = amnesty;
if(cur_deathlink_amnesty > getDeathAmnesty())
cur_deathlink_amnesty = getDeathAmnesty();
}
int AP_GetCurrentDeathAmnesty()
{
return useDeathlink() ? cur_deathlink_amnesty : -1;
}
void AP_SetDeathLinkAlias(std::string const& alias)
{
ap_deathlink_alias = alias;
}
std::map<std::pair<std::string,int64_t>, std::string>& AP_GetLocationMap()
{
return map_location_id_name;
}
std::map<int, AP_NetworkPlayer>& AP_GetPlayerMap()
{
return map_players;
}
std::map<std::pair<std::string,int64_t>, std::string>& AP_GetItemMap()
{
return map_item_id_name;
}
std::string const& AP_GetSlotGame()
{
return ap_slot_game;
}
std::set<int64_t> const& AP_GetMissingLocations()
{
return missing_locs;
}
void AP_Init(const char* ip, const char* game, const char* player_name, const char* passwd) {
if(init) AP_Disconnect();
multiworld = true;
uint64_t milliseconds_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
rando = std::mt19937((unsigned int)milliseconds_since_epoch);
if (!strcmp(ip,"")) {
ip = "archipelago.gg:38281";
AP_Log(format("Using default Server Address: '{}'", ip));
} else {
AP_Log(format("Using Server Address: '{}'", ip));
}
ap_ip = ip;
ap_game = game;
ap_player_name = player_name;
ap_passwd = passwd;
AP_Log("Initializing...");
//Connect to server
ix::initNetSystem();
webSocket.setUrl("wss://" + ap_ip);
isSSL = true;
webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
{
bool err = false;
if (msg->type == ix::WebSocketMessageType::Message)
{
std::string request;
if (parse_response(msg->str, request)) {
APSend(request);
}
}
else if (msg->type == ix::WebSocketMessageType::Open)
{
AP_Log("Connected to Archipelago");
}
else if(msg->type == ix::WebSocketMessageType::Close)
{
AP_Log("Disconnected");
if(!disconnecting)
err = true;
}
if (err || msg->type == ix::WebSocketMessageType::Error)
{
auth = false;
for (auto itr = map_server_data.begin(); itr != map_server_data.end();)
{
itr->second->status = AP_RequestStatus::Error;
itr = map_server_data.erase(itr);
}
AP_Error(format("Error connecting to Archipelago. (Status: {}, '{}') Retries: {}", msg->errorInfo.http_status, msg->errorInfo.reason, msg->errorInfo.retries));
if (isSSL)
{
webSocket.setUrl("ws://" + ap_ip);
isSSL = false;
}
else
{
webSocket.setUrl("wss://" + ap_ip);
isSSL = true;
}
}
}
);
webSocket.setPingInterval(45);
AP_NetworkPlayer archipelago {
-1,
0,
"Archipelago",
"Archipelago",
"__Server"
};
map_players[0] = archipelago;
AP_Init_Generic();
}
void AP_Init(const char* filename) {
if(init) AP_Disconnect();
multiworld = false;
std::ifstream mwfile(filename);
reader.parse(mwfile,sp_ap_root);
mwfile.close();
sp_save_path = std::string(filename) + ".save";
std::ifstream savefile(sp_save_path);
reader.parse(savefile, sp_save_root);
savefile.close();
WriteFileJSON(sp_save_root, sp_save_path);
ap_player_name = AP_OFFLINE_NAME;
AP_Init_Generic();
}
void AP_Start() {
init = true;
disconnecting = false;
if (multiworld) {
webSocket.start();
} else {
if (!sp_save_root.get("init", false).asBool()) {
sp_save_root["init"] = true;
sp_save_root["checked_locations"] = Json::arrayValue;
sp_save_root["store"] = Json::objectValue;
}
// Only game in the data package is our game
ap_game = sp_ap_root["data_package"]["data"]["games"].getMemberNames()[0];
Json::Value fake_msg;
fake_msg[0]["cmd"] = "Connected";
fake_msg[0]["slot"] = AP_OFFLINE_SLOT;
fake_msg[0]["slot_info"][std::to_string(AP_OFFLINE_SLOT)]["game"] = ap_game;
fake_msg[0]["players"] = Json::arrayValue;
fake_msg[0]["players"][0]["team"] = 0;
fake_msg[0]["players"][0]["slot"] = AP_OFFLINE_SLOT;
fake_msg[0]["players"][0]["alias"] = AP_OFFLINE_NAME;
fake_msg[0]["players"][0]["name"] = AP_OFFLINE_NAME;
fake_msg[0]["checked_locations"] = sp_save_root["checked_locations"];
fake_msg[0]["slot_data"] = sp_ap_root["slot_data"];
std::string req;
parse_response(writer.write(fake_msg), req);
fake_msg.clear();
fake_msg[0]["cmd"] = "DataPackage";
fake_msg[0]["data"] = sp_ap_root["data_package"]["data"];
parse_response(writer.write(fake_msg), req);
fake_msg.clear();
fake_msg[0]["cmd"] = "ReceivedItems";
fake_msg[0]["index"] = 0;
fake_msg[0]["items"] = Json::arrayValue;
for (unsigned int i = 0; i < sp_save_root["checked_locations"].size(); i++) {
Json::Value item;
item["item"] = sp_ap_root["location_to_item"][sp_save_root["checked_locations"][i].asString()].asInt64();
item["location"] = 0;
item["player"] = ap_player_id;
fake_msg[0]["items"].append(item);
}
parse_response(writer.write(fake_msg), req);
}
}
bool AP_IsInit() {
return init;
}
void AP_SetClientVersion(AP_NetworkVersion* version) {
client_version.major = version->major;
client_version.minor = version->minor;
client_version.build = version->build;
}
void AP_SendItem(int64_t idx) {
AP_SendItem(std::set<int64_t>{ idx });
}
void AP_SendItem(std::set<int64_t> const& locations) {
for (int64_t idx : locations) {
AP_Log(format("Checked '{}'.", getLocationName(ap_game, idx).c_str()));
}
if (multiworld) {
Json::Value req_t;
req_t[0]["cmd"] = "LocationChecks";
req_t[0]["locations"] = Json::arrayValue;
for (int64_t loc : locations) {
req_t[0]["locations"].append(loc);
};
APSend(writer.write(req_t));
} else {
std::set<int64_t> new_locations;
for (int64_t idx : locations) {
bool was_previously_checked = false;
for (auto itr : sp_save_root["checked_locations"]) {
if (itr.asInt64() == idx) {
was_previously_checked = true;
break;
}
}
if (!was_previously_checked) new_locations.insert(idx);
}
Json::Value fake_msg;
fake_msg[0]["cmd"] = "ReceivedItems";
fake_msg[0]["index"] = last_item_idx+1;
fake_msg[0]["items"] = Json::arrayValue;
for (int64_t idx : new_locations) {
int64_t recv_item_id = sp_ap_root["location_to_item"].get(std::to_string(idx), 0).asInt64();
if (recv_item_id == 0) continue;
Json::Value item;
item["item"] = recv_item_id;
item["location"] = idx;
item["player"] = ap_player_id;
fake_msg[0]["items"].append(item);
}
std::string req;
parse_response(writer.write(fake_msg), req);
fake_msg.clear();
fake_msg[0]["cmd"] = "RoomUpdate";
fake_msg[0]["checked_locations"] = Json::arrayValue;
for (int64_t idx : new_locations) {
fake_msg[0]["checked_locations"].append(idx);
sp_save_root["checked_locations"].append(idx);
}
WriteFileJSON(sp_save_root, sp_save_path);
parse_response(writer.write(fake_msg), req);
}
}
void AP_SendLocationScouts(std::set<int64_t> const& locations, int create_as_hint) {
if (multiworld) {
Json::Value req_t;
req_t[0]["cmd"] = "LocationScouts";
req_t[0]["locations"] = Json::arrayValue;
for (int64_t loc : locations) {
req_t[0]["locations"].append(loc);
}
req_t[0]["create_as_hint"] = create_as_hint;
APSend(writer.write(req_t));
} else {
Json::Value fake_msg;
fake_msg[0]["cmd"] = "LocationInfo";
fake_msg[0]["locations"] = Json::arrayValue;
for (int64_t loc : locations) {
Json::Value netitem;
netitem["item"] = sp_ap_root["location_to_item"].get(std::to_string(loc), 0).asInt64();
netitem["location"] = loc;
netitem["player"] = ap_player_id;
netitem["flags"] = 0b001; // Hardcoded for SP seeds.
fake_msg[0]["locations"].append(netitem);
}
}
}
void AP_StoryComplete() {
if (!multiworld) return;
Json::Value req_t;
req_t[0]["cmd"] = "StatusUpdate";
req_t[0]["status"] = 30; //CLIENT_GOAL
APSend(writer.write(req_t));
}
bool AP_DeathLinkSend(std::string cause) {
if (!init || !useDeathlink() || !multiworld)
return false;
if (cur_deathlink_amnesty > 0) {
cur_deathlink_amnesty--;
return false;
}
cur_deathlink_amnesty = getDeathAmnesty();
std::chrono::time_point<std::chrono::system_clock> timestamp = std::chrono::system_clock::now();
Json::Value req_t;
req_t[0]["cmd"] = "Bounce";
req_t[0]["data"]["time"] = std::chrono::duration_cast<std::chrono::seconds>(timestamp.time_since_epoch()).count();
req_t[0]["data"]["source"] = ap_deathlink_alias.empty() ? ap_player_name : ap_deathlink_alias; // Name and Shame >:D
if(!cause.empty())
req_t[0]["data"]["cause"] = cause;
req_t[0]["tags"][0] = "DeathLink";
APSend(writer.write(req_t));
return true;
}
void AP_EnableQueueItemRecvMsgs(bool b) {
queueitemrecvmsg = b;
}
void AP_SetItemClearCallback(void (*f_itemclr)()) {
resetItemValues = f_itemclr;
}
void AP_SetItemRecvCallback(void (*f_itemrecv)(int64_t,bool)) {
getitemfunc = f_itemrecv;
}
void AP_SetLocationCheckedCallback(std::function<void(int64_t)> f_loccheckrecv) {
checklocfunc = f_loccheckrecv;
}
void AP_SetLocationInfoCallback(std::function<void(std::vector<AP_NetworkItem>)> f_locinfrecv) {
locinfofunc = f_locinfrecv;
}
void AP_SetLoggingCallback(std::function<void(std::string const&)> proc)
{
onLogMessage = proc;
}
void AP_SetLoggingErrorCallback(std::function<void(std::string const&)> proc)
{
onErrMessage = proc;
}
void AP_SetDeathLinkRecvCallback(void (*f_deathrecv)()) {
recvdeath = f_deathrecv;
}
void AP_SetDeathLinkRecvCallback(std::function<void(std::string,std::string)> proc) {
recvdeath2 = proc;
}
void AP_SetConnectedCallback(std::function<void()> proc)
{
onConnectedFunc = proc;
}
void AP_SetPreConnectCallback(std::function<void(AP_RoomInfo const&)> proc)
{
preConnectFunc = proc;
}
void AP_OnConnectError(std::function<void(std::string)> proc)
{
onConnectErrFunc = proc;
}
void AP_RegisterSlotDataIntCallback(std::string key, void (*f_slotdata)(int)) {
map_slotdata_callback_int[key] = f_slotdata;
slotdata_strings.push_back(key);
}
void AP_RegisterSlotDataRawCallback(std::string key, void (*f_slotdata)(std::string)) {
map_slotdata_callback_raw[key] = f_slotdata;
slotdata_strings.push_back(key);
}
void AP_RegisterSlotDataMapIntIntCallback(std::string key, void (*f_slotdata)(std::map<int,int>)) {
map_slotdata_callback_mapintint[key] = f_slotdata;
slotdata_strings.push_back(key);
}
void AP_SetDeathLinkSupported(bool supdeathlink) {
deathlinksupported = supdeathlink;
}
bool AP_DeathLinkPending() {
return deathlinkstat;
}
void AP_DeathLinkClear() {
deathlinkstat = false;
}
bool AP_IsMessagePending() {
return !messageQueue.empty();
}
AP_Message* AP_GetLatestMessage() {
return messageQueue.front();
}
void AP_ClearLatestMessage() {
if (AP_IsMessagePending()) {
delete messageQueue.front();
messageQueue.pop_front();
}
}
void AP_Say(std::string text) {
Json::Value req_t;
req_t[0]["cmd"] = "Say";
req_t[0]["text"] = text;
APSend(writer.write(req_t));
}
int AP_GetRoomInfo(AP_RoomInfo* client_roominfo) {
if (!auth) return 1;
*client_roominfo = lib_room_info;
return 0;
}
AP_ConnectionStatus AP_GetConnectionStatus() {
if (!multiworld && auth) return AP_ConnectionStatus::Authenticated;
if (refused) {
return AP_ConnectionStatus::ConnectionRefused;
}
if (webSocket.getReadyState() == ix::ReadyState::Open) {
if (auth) {
return AP_ConnectionStatus::Authenticated;
} else {
return AP_ConnectionStatus::Connected;
}
}
return AP_ConnectionStatus::Disconnected;
}
int AP_GetUUID() {
return (int)ap_uuid;
}
int AP_GetPlayerID() {
return ap_player_id;
}
int AP_GetPlayerTeam() {
return ap_player_team;
}
void AP_SetServerData(AP_SetServerDataRequest* request) {
request->status = AP_RequestStatus::Pending;
Json::Value req_t;
req_t[0]["cmd"] = "Set";
req_t[0]["key"] = request->key;
switch (request->type) {
case AP_DataType::Int:
for (int i = 0; i < request->operations.size(); i++) {
req_t[0]["operations"][i]["operation"] = request->operations[i].operation;
req_t[0]["operations"][i]["value"] = *((int*)request->operations[i].value);
}
break;
case AP_DataType::Double:
for (int i = 0; i < request->operations.size(); i++) {
req_t[0]["operations"][i]["operation"] = request->operations[i].operation;
req_t[0]["operations"][i]["value"] = *((double*)request->operations[i].value);
}
break;
default:
for (int i = 0; i < request->operations.size(); i++) {
req_t[0]["operations"][i]["operation"] = request->operations[i].operation;
Json::Value data;
reader.parse((*(std::string*)request->operations[i].value), data);
req_t[0]["operations"][i]["value"] = data;
}
Json::Value default_val_json;
reader.parse(*((std::string*)request->default_value), default_val_json);
req_t[0]["default"] = default_val_json;
break;
}
req_t[0]["want_reply"] = request->want_reply;
map_serverdata_typemanage[request->key] = request->type;
APSend(writer.write(req_t));
request->status = AP_RequestStatus::Done;
}
void AP_RegisterSetReplyCallback(void (*f_setreply)(AP_SetReply)) {
setreplyfunc = f_setreply;
}
void AP_SetNotify(std::map<std::string,AP_DataType> keylist) {
Json::Value req_t;
req_t[0]["cmd"] = "SetNotify";
int i = 0;
for (std::pair<std::string,AP_DataType> keytypepair : keylist) {
req_t[0]["keys"][i] = keytypepair.first;
map_serverdata_typemanage[keytypepair.first] = keytypepair.second;
i++;
}
APSend(writer.write(req_t));
}
void AP_SetNotify(std::string key, AP_DataType type) {
std::map<std::string,AP_DataType> keylist;
keylist[key] = type;
AP_SetNotify(keylist);
}
void AP_GetServerData(AP_GetServerDataRequest* request) {
request->status = AP_RequestStatus::Pending;
if (map_server_data.find(request->key) != map_server_data.end()) return;
map_server_data[request->key] = request;
Json::Value req_t;
req_t[0]["cmd"] = "Get";
req_t[0]["keys"][0] = request->key;
APSend(writer.write(req_t));
}
std::string AP_GetPrivateServerDataPrefix() {
return "APCpp" + std::to_string(ap_player_name_hash) + "APCpp" + std::to_string(ap_player_id) + "APCpp";
}
// PRIV
void AP_Init_Generic() {
ap_player_name_hash = std::hash<std::string>{}(ap_player_name);
std::ifstream datapkg_cache_file(datapkg_cache_path);
reader.parse(datapkg_cache_file,datapkg_cache);;
datapkg_cache_file.close();
}
bool parse_response(std::string msg, std::string &request) {
Json::Value root;
reader.parse(msg, root);
for (unsigned int i = 0; i < root.size(); i++) {
std::string cmd = root[i]["cmd"].asString();
if (cmd == "RoomInfo")
{
lib_room_info.version.major = root[i]["version"]["major"].asInt();
lib_room_info.version.minor = root[i]["version"]["minor"].asInt();
lib_room_info.version.build = root[i]["version"]["build"].asInt();
std::vector<std::string> serv_tags;
for (auto itr : root[i]["tags"]) {
serv_tags.push_back(itr.asString());
}
lib_room_info.tags = serv_tags;
lib_room_info.password_required = root[i]["password"].asBool();
std::map<std::string,int> serv_permissions;
for (auto itr : root[i]["permissions"].getMemberNames()) {
serv_permissions[itr] = root[i]["permissions"][itr].asInt();
}
lib_room_info.permissions = serv_permissions;
lib_room_info.hint_cost = root[i]["hint_cost"].asInt();
lib_room_info.location_check_points = root[i]["location_check_points"].asInt();
std::map<std::string,std::string> serv_datapkg_checksums;
for (auto itr : root[i]["datapackage_checksums"].getMemberNames()) {
serv_datapkg_checksums[itr] = root[i]["datapackage_checksums"][itr].asString();
}
lib_room_info.datapackage_checksums = serv_datapkg_checksums;
lib_room_info.seed_name = root[i]["seed_name"].asString();
lib_room_info.time = root[i]["time"].asFloat();
if (!auth) {
AP_Log(format("AP Version: {}.{}.{}", lib_room_info.version.major, lib_room_info.version.minor, lib_room_info.version.build));
if(preConnectFunc)
preConnectFunc(lib_room_info);
Json::Value req_t;
ap_uuid = rando();
req_t[0]["cmd"] = "Connect";
req_t[0]["game"] = ap_game;
req_t[0]["name"] = ap_player_name;
req_t[0]["password"] = ap_passwd;
req_t[0]["uuid"] = ap_uuid;
req_t[0]["tags"] = Json::arrayValue;
for(std::string const& tag : ap_tags)
req_t[0]["tags"].append(tag);
req_t[0]["version"]["major"] = client_version.major;
req_t[0]["version"]["minor"] = client_version.minor;
req_t[0]["version"]["build"] = client_version.build;
req_t[0]["version"]["class"] = "Version";
req_t[0]["items_handling"] = 7; // Full Remote
request = writer.write(req_t);
return true;
}
}
else if (cmd == "Connected")
{
// Avoid inconsistency if we disconnected before
(*resetItemValues)();
auth = true;
refused = false;
AP_Log("Authenticated");
ap_player_id = root[i]["slot"].asInt();
ap_player_team = root[i]["team"].asInt();
ap_slot_game = root[i]["slot_info"][std::to_string(ap_player_id)]["game"].asString();
missing_locs.clear();
for (unsigned int j = 0; j < root[i]["missing_locations"].size(); j++) {
//Sync missing location list
int64_t loc_id = root[i]["missing_locations"][j].asInt64();
missing_locs.insert(loc_id);
}
for (unsigned int j = 0; j < root[i]["checked_locations"].size(); j++) {
//Sync checks with server
int64_t loc_id = root[i]["checked_locations"][j].asInt64();
if(checklocfunc)
checklocfunc(loc_id);
}
for (unsigned int j = 0; j < root[i]["players"].size(); j++) {
AP_NetworkPlayer player = {
root[i]["players"][j]["team"].asInt(),
root[i]["players"][j]["slot"].asInt(),
root[i]["players"][j]["name"].asString(),
root[i]["players"][j]["alias"].asString(),
"PLACEHOLDER"
};
player.game = root[i]["slot_info"][std::to_string(player.slot)]["game"].asString();
map_players[root[i]["players"][j]["slot"].asInt()] = player;
}
if ((root[i]["slot_data"].get("death_link", false).asBool() || root[i]["slot_data"].get("DeathLink", false).asBool()) && deathlinksupported) enable_deathlink = true;
if (root[i]["slot_data"]["death_link_amnesty"] != Json::nullValue)
deathlink_amnesty = root[i]["slot_data"].get("death_link_amnesty", 0).asInt();
else if (root[i]["slot_data"]["DeathLink_Amnesty"] != Json::nullValue)
deathlink_amnesty = root[i]["slot_data"].get("DeathLink_Amnesty", 0).asInt();
cur_deathlink_amnesty = getDeathAmnesty();
for (std::string key : slotdata_strings) {
if (map_slotdata_callback_int.count(key)) {
(*map_slotdata_callback_int.at(key))(root[i]["slot_data"][key].asInt());
} else if (map_slotdata_callback_raw.count(key)) {
(*map_slotdata_callback_raw.at(key))(writer.write(root[i]["slot_data"][key]));
} else if (map_slotdata_callback_mapintint.count(key)) {
std::map<int,int> out;
for (auto itr : root[i]["slot_data"][key].getMemberNames()) {
out[std::stoi(itr)] = root[i]["slot_data"][key][itr.c_str()].asInt();
}
(*map_slotdata_callback_mapintint.at(key))(out);
}
}
resync_serverdata_request.key = "APCppLastRecv" + ap_player_name + std::to_string(ap_player_id);
resync_serverdata_request.value = &last_item_idx;
resync_serverdata_request.type = AP_DataType::Int;
AP_GetServerData(&resync_serverdata_request);
AP_RoomInfo info;
AP_GetRoomInfo(&info);
Json::Value req_t = Json::arrayValue;
if (force_deathlink || (enable_deathlink && deathlinksupported)) {
if(!ap_tags.contains("DeathLink")) {
ap_tags.insert("DeathLink");
updateAPTags();
}
}
// Get datapackage for outdated games
for (std::pair<std::string,std::string> game_pkg : info.datapackage_checksums) {
if (datapkg_cache.get("games", Json::objectValue).get(game_pkg.first, Json::objectValue).get("checksum", "_None") != game_pkg.second) {
AP_Log(format("Cache outdated for game: {}", game_pkg.first.c_str()));
datapkg_outdated_games.insert(game_pkg.first);
}
}
if (!datapkg_outdated_games.empty()) {
Json::Value resync_datapkg;
resync_datapkg["cmd"] = "GetDataPackage";
resync_datapkg["games"] = Json::arrayValue;
resync_datapkg["games"].append(*datapkg_outdated_games.begin());
req_t.append(resync_datapkg);
} else {
parseDataPkg();
Json::Value sync;
sync["cmd"] = "Sync";
req_t.append(sync);
}
request = writer.write(req_t);
if(onConnectedFunc)
onConnectedFunc();
return true;
}
else if (cmd == "DataPackage")
{
parseDataPkg(root[i]["data"]);
Json::Value req_t;
if (!datapkg_outdated_games.empty()) {
req_t[0]["cmd"] = "GetDataPackage";
req_t[0]["games"] = Json::arrayValue;
req_t[0]["games"].append(*datapkg_outdated_games.begin());
} else {
req_t[0]["cmd"] = "Sync";
}
request = writer.write(req_t);
return true;
}
else if (cmd == "Retrieved")
{
for (auto itr : root[i]["keys"].getMemberNames()) {
if (!map_server_data.count(itr)) continue;
AP_GetServerDataRequest* target = map_server_data[itr];
switch (target->type) {
case AP_DataType::Int:
*((int*)target->value) = root[i]["keys"][itr].asInt();
break;
case AP_DataType::Double:
*((double*)target->value) = root[i]["keys"][itr].asDouble();
break;
case AP_DataType::Raw:
*((std::string*)target->value) = writer.write(root[i]["keys"][itr]);
break;
}
target->status = AP_RequestStatus::Done;
map_server_data.erase(itr);
}
}
else if (cmd == "SetReply")
{
if (setreplyfunc) {
int int_val;
int int_orig_val;
double dbl_val;
double dbl_orig_val;
std::string raw_val;
std::string raw_orig_val;
AP_SetReply setreply;
setreply.key = root[i]["key"].asString();
switch (map_serverdata_typemanage[setreply.key]) {
case AP_DataType::Int:
int_val = root[i]["value"].asInt();
int_orig_val = root[i]["original_value"].asInt();
setreply.value = &int_val;
setreply.original_value = &int_orig_val;
break;
case AP_DataType::Double:
dbl_val = root[i]["value"].asDouble();
dbl_orig_val = root[i]["original_value"].asDouble();
setreply.value = &dbl_val;
setreply.original_value = &dbl_orig_val;
break;
default:
raw_val = writer.write(root[i]["value"]);
raw_orig_val = writer.write(root[i]["original_value"]);
setreply.value = &raw_val;
setreply.original_value = &raw_orig_val;
break;
}
(*setreplyfunc)(setreply);
}
}
else if (cmd == "PrintJSON")
{
const std::string printType = root[i].get("type","").asString();
if (printType == "ItemSend" || printType == "ItemCheat") {
if (getPlayer(0, root[i]["receiving"].asInt()).alias == getPlayer(0, ap_player_id).alias || getPlayer(0,root[i]["item"]["player"].asInt()).alias != getPlayer(0,ap_player_id).alias) continue;
AP_NetworkPlayer recv_player = getPlayer(0, root[i]["receiving"].asInt());
AP_ItemSendMessage* msg = new AP_ItemSendMessage;
msg->type = AP_MessageType::ItemSend;
msg->item = getItemName(recv_player.game, root[i]["item"]["item"].asInt64());
msg->recvPlayer = recv_player.alias;
msg->text = msg->item + std::string(" was sent to ") + msg->recvPlayer;
messageQueue.push_back(msg);
} else if (printType == "Hint") {
AP_NetworkPlayer send_player = getPlayer(0, root[i]["item"]["player"].asInt());
AP_NetworkPlayer recv_player = getPlayer(0, root[i]["receiving"].asInt());
AP_HintMessage* msg = new AP_HintMessage;
msg->type = AP_MessageType::Hint;
msg->item = getItemName(recv_player.game,root[i]["item"]["item"].asInt64());
msg->sendPlayer = send_player.alias;
msg->recvPlayer = recv_player.alias;
msg->location = getLocationName(send_player.game, root[i]["item"]["location"].asInt64());
msg->checked = root[i]["found"].asBool();
msg->text = std::string("Item ") + msg->item + std::string(" from ") + msg->sendPlayer + std::string(" to ") + msg->recvPlayer + std::string(" at ") + msg->location + std::string((msg->checked ? " (Checked)" : " (Unchecked)"));
messageQueue.push_back(msg);
} else if (printType == "Countdown") {
AP_CountdownMessage* msg = new AP_CountdownMessage;
msg->type = AP_MessageType::Countdown;
msg->timer = root[i]["countdown"].asInt();
msg->text = root[i]["data"][0]["text"].asString();
messageQueue.push_back(msg);
} else {
AP_Message* msg = new AP_Message;
msg->text = "";
for (auto itr : root[i]["data"]) {
if (itr.get("type","").asString() == "player_id") {
msg->text += getPlayer(0, itr["text"].asInt()).alias;
} else if (itr.get("text","") != "") {
msg->text += itr["text"].asString();
}
}
messageQueue.push_back(msg);
}
}
else if (cmd == "LocationInfo")
{
std::vector<AP_NetworkItem> locations;
for (unsigned int j = 0; j < root[i]["locations"].size(); j++) {
AP_NetworkItem item;
item.item = root[i]["locations"][j]["item"].asInt64();
item.location = root[i]["locations"][j]["location"].asInt64();
AP_NetworkPlayer player = getPlayer(0, root[i]["locations"][j]["player"].asInt());
item.player = player.slot;
item.flags = root[i]["locations"][j]["flags"].asInt();
item.itemName = getItemName(player.game, item.item);
item.locationName = getLocationName(ap_game, item.location);
item.playerName = player.alias;
locations.push_back(item);
}
if (locinfofunc) {
locinfofunc(locations);
} else {
AP_Error("Received LocationInfo but no handler registered!");
}
}
else if (cmd == "ReceivedItems")
{
int item_idx = root[i]["index"].asInt();
bool notify;
for (unsigned int j = 0; j < root[i]["items"].size(); j++) {
int64_t item_id = root[i]["items"][j]["item"].asInt64();
notify = (item_idx == 0 && last_item_idx <= j && multiworld) || item_idx != 0;
(*getitemfunc)(item_id, notify);
if (queueitemrecvmsg && notify) {
AP_ItemRecvMessage* msg = new AP_ItemRecvMessage;
AP_NetworkPlayer sender = getPlayer(0, root[i]["items"][j]["player"].asInt());
msg->type = AP_MessageType::ItemRecv;
msg->item = getItemName(ap_game, item_id);
msg->sendPlayer = sender.alias;
msg->text = std::string("Received ") + msg->item + std::string(" from ") + msg->sendPlayer;
messageQueue.push_back(msg);
}
}
last_item_idx = item_idx == 0 ? root[i]["items"].size() : last_item_idx + root[i]["items"].size();
AP_SetServerDataRequest request;
request.key = "APCppLastRecv" + ap_player_name + std::to_string(ap_player_id);
AP_DataStorageOperation replac;
replac.operation = "replace";
replac.value = &last_item_idx;
std::vector<AP_DataStorageOperation> operations;
operations.push_back(replac);
request.operations = operations;
request.default_value = 0;
request.type = AP_DataType::Int;
request.want_reply = false;
AP_SetServerData(&request);
}
else if (cmd == "RoomUpdate")
{