Repository navigation
Expand file tree
/
Copy pathapclient.hpp
More file actions
1898 lines (1683 loc) · 66.3 KB
/
Copy pathapclient.hpp
File metadata and controls
1898 lines (1683 loc) · 66.3 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
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) 2022-2026 black-sliver, FelicitusNeko, highrow623, NewSoupVi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _APCLIENT_HPP
#define _APCLIENT_HPP
#define APCLIENTPP_VERSION_INITIALIZER {0, 6, 6}
#if defined _WSWRAP_HPP && !defined WSWRAP_SEND_EXCEPTIONS
#if defined _MSC_VER && __cplusplus < 202302L
#pragma message("Can't set exception behavior. wswrap already included.")
#else
#warning "Can't set exception behavior. wswrap already included."
#endif
#elif !defined WSWRAP_SEND_EXCEPTIONS
#define WSWRAP_SEND_EXCEPTIONS // backwards compatibility for at least 1 version
#endif
//#define APCLIENT_DEBUG // to get debug output
//#define AP_NO_DEFAULT_DATA_PACKAGE_STORE // to disable auto-construction of data package store
//#define AP_NO_SCHEMA // to disable schema checking
//#define AP_PREFER_UNENCRYPTED // try unencrypted connection first, then encrypted
#include <chrono>
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <wswrap.hpp>
// check for optional
#if defined(_MSC_VER) && _MSC_VER < 1910 // older msvc doesn't like the has_include
#define NO_OPTIONAL
#else
#if (defined __cplusplus && __cplusplus >= 201703L) || (defined __has_include && __has_include(<optional>))
#include <optional>
#elif defined __has_include && __has_include(<experimental/optional>)
#include <experimental/optional>
#else
#define NO_OPTIONAL
#endif
#endif
#include <nlohmann/json.hpp>
#ifndef AP_NO_SCHEMA
#include <valijson/adapters/nlohmann_json_adapter.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/validator.hpp>
#endif
#ifndef WSWRAP_VERSION
#define WSWRAP_VERSION 10000 // 1.0 did not have this define
#endif
#if WSWRAP_VERSION < 10300 && !defined __EMSCRIPTEN__
#if defined _MSC_VER && __cplusplus < 202302L
#pragma message("Please update wswrap to enable compression! Archipelago will require compression in the future.")
#else
#warning "Please update wswrap to enable compression! Archipelago will require compression in the future."
#endif
#elif defined WSWRAP_NO_COMPRESSION && !defined __EMSCRIPTEN__
#if defined _MSC_VER && __cplusplus < 202302L
#pragma message("Don't disable compression in prod! Archipelago will require compression in the future.")
#else
#warning "Don't disable compression in prod! Archipelago will require compression in the future."
#endif
#endif
/**
* Abstract data package storage handler.
*
* Inherit, instantiate and pass to APClient's constructor to handle data package caching.
* A default implementation is `DefaultDataPackageStore` in `defaultdatapackagestore.hpp`.
*/
class APDataPackageStore {
protected:
using json = nlohmann::json;
APDataPackageStore() {}
public:
virtual ~APDataPackageStore() = default;
virtual bool load(const std::string& game, const std::string& checksum, json& data) = 0;
virtual bool save(const std::string& game, const json& data) = 0;
};
#ifndef AP_NO_DEFAULT_DATA_PACKAGE_STORE
#include "defaultdatapackagestore.hpp"
#endif
/**
* Archipelago Client implementation.
*
* Instantiate, hook up callbacks and call `poll()` repeatedly to attach your game to a server.
*/
class APClient {
protected:
typedef nlohmann::json json;
typedef wswrap::WS WS;
#ifndef AP_NO_SCHEMA
typedef valijson::adapters::NlohmannJsonAdapter JsonSchemaAdapter;
#endif
static int64_t stoi64(const std::string& s) {
return std::stoll(s);
}
public:
static constexpr int64_t INVALID_NAME_ID = std::numeric_limits<int64_t>::min();
#if !defined _MSC_VER || _MSC_VER >= 1911
static constexpr char DEFAULT_URI[] = "localhost:38281";
#else
static const char DEFAULT_URI[]; // = "localhost:38281"; // assign this in implementation
#endif
APClient(const std::string& uuid, const std::string& game, const std::string& uri = "localhost:38281",
const std::string& certStore="", APDataPackageStore* dataPackageStore = nullptr,
const bool autoGetDataPackage = true)
: _dataPackageStore(dataPackageStore), _autoGetDataPackage(autoGetDataPackage)
{
// check if certStore is supported and required
#if WSWRAP_VERSION < 10100 && !defined __EMSCRIPTEN__
if (!certStore.empty()) {
log("Cert store not supported, please update wswrap!\n");
}
#elif !defined __EMSCRIPTEN__
_certStore = certStore;
#else
(void)certStore; // avoid warning
#endif
// check if wss is requested and supported
#if WSWRAP_VERSION < 10100 && !defined __EMSCRIPTEN__
if (uri.rfind("wss://", 0) == 0) {
auto msg = "No SSL support. Please update wswrap library!";
log(msg);
throw std::invalid_argument(msg);
} else
#endif
// fix up URI (add ws:// and default port if none is given)
if (!uri.empty()) {
auto p = uri.find("://");
if (p == std::string::npos) {
#if WSWRAP_VERSION >= 10100 || defined __EMSCRIPTEN__
_tryWSS = true;
#ifdef AP_PREFER_UNENCRYPTED
_uri = "ws://" + uri;
p = 2;
#else
_uri = "wss://" + uri;
p = 3;
#endif
#else // no ssl support -> ws://
_uri = "ws://" + uri;
p = 2;
#endif
} else {
_uri = uri;
}
const auto pColon = _uri.find(':', p + 3); // FIXME: this fails for IPv6 addresses
const auto pSlash = _uri.find('/', p + 3);
if (pColon == std::string::npos || (pSlash != std::string::npos && pColon > pSlash)) {
auto tmp = _uri.substr(0, pSlash) + ":38281";
if (pSlash != std::string::npos) tmp += _uri.substr(pSlash);
_uri = tmp;
}
}
if (!_dataPackageStore) {
#ifndef AP_NO_DEFAULT_DATA_PACKAGE_STORE
_autoDataPackageStore = std::make_unique<DefaultDataPackageStore>();
_dataPackageStore =_autoDataPackageStore.get();
#else
const char* msg = "dataPackageStore is required if compiled with AP_NO_DEFAULT_DATA_PACKAGE_STORE";
fprintf(stderr, "APClient: %s!\n", msg);
#ifdef __cpp_exceptions
throw std::runtime_error(msg);
#endif
#endif
}
_uuid = uuid;
_game = game;
_dataPackage = {
{"version", -1},
{"games", json(json::value_t::object)},
};
#ifndef AP_NO_SCHEMA
valijson::SchemaParser parser;
parser.populateSchema(JsonSchemaAdapter(_packetSchemaJson), _packetSchema);
parser.populateSchema(JsonSchemaAdapter(_retrievedSchemaJson), _commandSchemas["Retrieved"]);
parser.populateSchema(JsonSchemaAdapter(_setReplySchemaJson), _commandSchemas["SetReply"]);
#endif
// Connect on first poll
_reconnectNow = true;
}
virtual ~APClient() = default;
enum class State {
DISCONNECTED,
SOCKET_CONNECTING,
SOCKET_CONNECTED,
ROOM_INFO,
SLOT_CONNECTED,
};
enum class ClientStatus : int {
UNKNOWN = 0,
CONNECTED = 5,
READY = 10,
PLAYING = 20,
GOAL = 30,
};
enum class RenderFormat {
TEXT,
HTML,
ANSI,
};
enum ItemFlags {
FLAG_NONE = 0,
FLAG_ADVANCEMENT = 1,
FLAG_NEVER_EXCLUDE = 2,
FLAG_TRAP = 4,
};
enum class Permission {
DISABLED = 0, ///< Completely disables access
ENABLED = 1, ///< Allows manual use
GOAL = 2, ///< Allows manual use after goal completion
FORCED = 4, ///< Forces usage
AUTO = FORCED | GOAL, ///< Forces use after goal completion, only works for release and collect
AUTO_ENABLED = FORCED | GOAL | ENABLED, ///< Forces use after goal completion, allows manual use any time
};
enum HintStatus {
HINT_UNSPECIFIED = 0, ///< The receiving player has not specified any status
HINT_NO_PRIORITY = 10, ///< The receiving player has specified that the item is unneeded
HINT_AVOID = 20, ///< The receiving player has specified that the item is detrimental
HINT_PRIORITY = 30, ///< The receiving player has specified that the item is needed
HINT_FOUND = 40, ///< The location has been collected. Status cannot be changed once found.
};
enum class SlotType : int {
SPECTATOR = 0,
PLAYER = 1,
GROUP = 2,
};
struct NetworkItem {
int64_t item;
int64_t location;
int player;
unsigned flags;
int index = -1; // to sync items, not actually part of NetworkItem
};
struct NetworkPlayer {
int team;
int slot;
std::string alias;
std::string name;
friend void to_json(nlohmann::json &j, const NetworkPlayer &player)
{
j = nlohmann::json{
{"team", player.team},
{"slot", player.slot},
{"alias", player.alias},
{"name", player.name},
};
}
};
struct NetworkSlot {
std::string name;
std::string game;
SlotType type{};
std::list<int> members;
};
struct TextNode {
std::string type;
std::string color;
std::string text;
int player = 0;
unsigned flags = FLAG_NONE;
unsigned hintStatus = HINT_UNSPECIFIED;
static TextNode from_json(const json& j)
{
TextNode node;
node.type = j.value("type", "");
node.color = j.value("color", "");
node.text = j.value("text", "");
node.player = j.value("player", 0);
node.flags = j.value("flags", 0U);
node.hintStatus = j.value("hint_status", 0U);
return node;
}
};
/**
* Parsed arguments of PrintJSON.
* Pointer arguments are optional (null if missing).
* You can not store any pointer. You'll have to store a copy of the value.
*/
struct PrintJSONArgs {
std::list<TextNode> data;
std::string type;
// members below are optional and absent when null
int* receiving = nullptr;
NetworkItem* item = nullptr;
bool* found = nullptr;
int* team = nullptr;
int* slot = nullptr;
std::string* message = nullptr;
std::list<std::string>* tags = nullptr;
int* countdown = nullptr;
};
struct Version {
int ma;
int mi;
int build;
friend void to_json(nlohmann::json& j, const Version& ver)
{
j = nlohmann::json{
{"major", ver.ma},
{"minor", ver.mi},
{"build", ver.build},
{"class", "Version"}
};
}
static Version from_json(const nlohmann::json& j)
{
if (j.is_null()) {
return {0, 0, 0};
}
return {
j.value("major", 0),
j.value("minor", 0),
j.value("build", 0)
};
}
constexpr bool operator<(const Version& other) const
{
return (ma < other.ma) || (ma == other.ma && mi < other.mi) ||
(ma == other.ma && mi == other.mi && build < other.build);
}
constexpr bool operator>=(const Version& other) const
{
return !(*this < other);
}
};
struct DataStorageOperation {
std::string operation;
json value;
friend void to_json(nlohmann::json &j, const DataStorageOperation &op)
{
j = nlohmann::json{
{"operation", op.operation},
{"value", op.value}
};
}
};
void set_socket_connected_handler(std::function<void()> f)
{
_hOnSocketConnected = std::move(f);
}
void set_socket_error_handler(std::function<void(const std::string&)> f)
{
_hOnSocketError = std::move(f);
}
void set_socket_disconnected_handler(std::function<void()> f)
{
_hOnSocketDisconnected = std::move(f);
}
void set_slot_connected_handler(std::function<void(const json&)> f)
{
_hOnSlotConnected = std::move(f);
}
void set_slot_refused_handler(std::function<void(const std::list<std::string>&)> f)
{
_hOnSlotRefused = std::move(f);
}
void set_slot_disconnected_handler(std::function<void()> f)
{
_hOnSlotDisconnected = std::move(f);
}
void set_room_info_handler(std::function<void()> f)
{
_hOnRoomInfo = std::move(f);
}
void set_room_update_handler(std::function<void()> f)
{
_hOnRoomUpdate = std::move(f);
}
void set_items_received_handler(std::function<void(const std::list<NetworkItem>&)> f)
{
_hOnItemsReceived = std::move(f);
}
void set_location_info_handler(std::function<void(const std::list<NetworkItem>&)> f)
{
_hOnLocationInfo = std::move(f);
}
void set_data_package_changed_handler(std::function<void(const json&)> f)
{
_hOnDataPackageChanged = std::move(f);
}
void set_print_handler(std::function<void(const std::string&)> f)
{
_hOnPrint = std::move(f);
}
void set_print_json_handler(std::function<void(const json& command)> f)
{
_hOnPrintJson = std::move(f);
}
void set_print_json_handler(const std::function<void(const PrintJSONArgs&)>& f)
{
set_print_json_handler([f](const json& command) {
if (!f) return;
PrintJSONArgs args;
int receiving;
NetworkItem item;
bool found;
int team;
int slot;
std::string message;
std::list<std::string> tags;
int countdown;
for (const auto& part: command["data"]) {
args.data.push_back(TextNode::from_json(part));
}
args.type = command.value("type", "");
auto it = command.find("receiving");
if (it != command.end()) {
receiving = *it;
args.receiving = &receiving;
}
it = command.find("item");
if (it != command.end()) {
item.item = it->value("item", static_cast<int64_t>(0));
item.location = it->value("location", static_cast<int64_t>(0));
item.player = it->value("player", 0);
item.flags = it->value("flags", 0U);
item.index = -1;
args.item = &item;
}
it = command.find("found");
if (it != command.end()) {
found = *it;
args.found = &found;
}
it = command.find("team");
if (it != command.end()) {
team = *it;
args.team = &team;
}
it = command.find("slot");
if (it != command.end()) {
slot = *it;
args.slot = &slot;
}
it = command.find("message");
if (it != command.end()) {
message = *it;
args.message = &message;
}
it = command.find("tags");
if (it != command.end()) {
it->get_to(tags);
args.tags = &tags;
}
it = command.find("countdown");
if (it != command.end()) {
countdown = *it;
args.countdown = &countdown;
}
f(args);
});
}
void set_print_json_handler(const std::function<void(const std::list<TextNode>&, const NetworkItem*, const int*)>& f)
{
set_print_json_handler([f](const PrintJSONArgs& args) {
if (!f) return;
f(args.data, args.item, args.receiving);
});
}
void set_print_json_handler(const std::function<void(const std::list<TextNode>&)>& f)
{
set_print_json_handler([f](const json& command) {
if (!f) return;
std::list<TextNode> data;
for (const auto& part: command["data"]) {
data.push_back(TextNode::from_json(part));
}
f(data);
});
}
void set_print_json_handler(const std::function<void(const std::list<TextNode>&, const json& extra)>& f)
{
set_print_json_handler([f](const json& command) {
if (!f)
return;
std::list<TextNode> data;
json extra;
for (const auto& part: command["data"]) {
data.push_back(TextNode::from_json(part));
}
for (const auto& pair: command.items()) {
extra[pair.key()] = pair.value();
}
f(data, extra);
});
}
void set_bounced_handler(std::function<void(const json&)> f)
{
_hOnBounced = std::move(f);
}
void set_location_checked_handler(std::function<void(const std::list<int64_t>&)> f)
{
_hOnLocationChecked = std::move(f);
}
void set_retrieved_handler(const std::function<void(const std::map<std::string,json>&)>& f)
{
set_retrieved_handler([f](const std::map<std::string, json>& keys, const json&) {
if (!f)
return;
f(keys);
});
}
void set_retrieved_handler(std::function<void(const std::map<std::string,json>&, const json& message)> f)
{
_hOnRetrieved = std::move(f);
}
void set_set_reply_handler(std::function<void(const json& command)> f)
{
_hOnSetReply = std::move(f);
}
void set_set_reply_handler(const std::function<void(const std::string&, const json&, const json&)>& f) {
set_set_reply_handler([f](const json& command) {
if (!f) return;
f(command["key"].get<std::string>(), command["value"], command["original_value"]);
});
}
/// Set location sending/receiving mode:
/// If receiveOwnLocations is set to true, missing and checked locations
/// won't update until the server acknowledges the LocationChecks and
/// on_location_checks will be run even for sent LocationChecks.
void set_receive_own_locations(bool receiveOwnLocations)
{
_receiveOwnLocations = receiveOwnLocations;
}
/// Gets location sending/receiving mode:
/// \sa see set_receive_own_locations for details.
bool get_receive_own_locations() const
{
return _receiveOwnLocations;
}
std::set<int64_t> get_checked_locations() const
{
return _checkedLocations;
}
std::set<int64_t> get_missing_locations() const
{
return _missingLocations;
}
const std::list<NetworkPlayer>& get_players() const
{
return _players;
}
std::string get_player_alias(const int slot) const
{
if (slot == 0)
return "Server";
for (const auto& player: _players) {
if (player.team == _team && player.slot == slot) {
return player.alias;
}
}
return "Unknown";
}
const std::string& get_player_game(const int player) const
{
static const std::string ARCHIPELAGO_STRING = "Archipelago";
static const std::string BLANK;
if (player == 0)
return ARCHIPELAGO_STRING;
const auto slotIt = _slotInfo.find(player);
if (slotIt != _slotInfo.end())
return slotIt->second.game;
return BLANK;
}
/// Get the currently played game name or an empty string
const std::string& get_game() const
{
return get_player_game(get_player_number());
}
std::string get_location_name(const int64_t code, const std::string& game) const
{
if (game.empty()) { // old code path ("global" ids)
const auto it = _locations.find(code);
if (it != _locations.end())
return it->second;
} else {
const static std::string archipelago = "Archipelago";
for (const auto& gameLookup : {game, archipelago}) {
const auto locationsIt = _gameLocations.find(gameLookup);
if (locationsIt != _gameLocations.end()) {
const auto it = locationsIt->second.find(code);
if (it != locationsIt->second.end()) {
return it->second;
}
}
}
}
return "Unknown";
}
/**
* Usage is not recommended
* Return the id associated with the location name
* Return APClient::INVALID_NAME_ID when undefined
*/
int64_t get_location_id(const std::string& name) const
{
if (_dataPackage["games"].contains(_game)) {
for (const auto& pair: _dataPackage["games"][_game]["location_name_to_id"].items()) {
if (pair.key() == name)
return pair.value().get<int64_t>();
}
}
return INVALID_NAME_ID;
}
std::string get_item_name(const int64_t code, const std::string& game) const
{
if (game.empty()) { // old code path ("global" ids)
const auto it = _items.find(code);
if (it != _items.end())
return it->second;
} else {
const static std::string archipelago = "Archipelago";
for (const auto& gameLookup : {game, archipelago}) {
const auto itemsIt = _gameItems.find(gameLookup);
if (itemsIt != _gameItems.end()) {
const auto it = itemsIt->second.find(code);
if (it != itemsIt->second.end()) {
return it->second;
}
}
}
}
return "Unknown";
}
/**
* Usage is not recommended
* Return the id associated with the item name
* Return APClient::INVALID_NAME_ID when undefined
*/
int64_t get_item_id(const std::string& name) const
{
if (_dataPackage["games"].contains(_game)) {
for (const auto& pair: _dataPackage["games"][_game]["item_name_to_id"].items()) {
if (pair.key() == name)
return pair.value().get<int64_t>();
}
}
return INVALID_NAME_ID;
}
bool slot_concerns_self(const int slot) const
{
if (slot == _slotnr)
return true;
const auto it = _slotInfo.find(slot);
if (it != _slotInfo.end()) {
const auto& members = it->second.members;
return std::find(members.begin(), members.end(), _slotnr) != members.end();
}
return false;
}
std::string render_json(const std::list<TextNode>& msg, RenderFormat fmt = RenderFormat::TEXT) const
{
// TODO: implement RenderFormat::HTML
if (fmt == RenderFormat::HTML)
throw std::invalid_argument("AP::render_json(..., HTML) not implemented");
std::string out;
bool colorIsSet = false;
for (const auto& node: msg) {
std::string color;
std::string text;
if (fmt != RenderFormat::TEXT) color = node.color;
if (node.type == "player_id") {
int id = std::stoi(node.text);
if (color.empty() && slot_concerns_self(id)) color = "magenta";
else if (color.empty()) color = "yellow";
text = get_player_alias(id);
} else if (node.type == "item_id") {
int64_t id = stoi64(node.text);
if (color.empty()) {
if (node.flags & ItemFlags::FLAG_ADVANCEMENT) color = "plum";
else if (node.flags & ItemFlags::FLAG_NEVER_EXCLUDE) color = "slateblue";
else if (node.flags & ItemFlags::FLAG_TRAP) color = "salmon";
else color = "cyan";
}
text = get_item_name(id, get_player_game(node.player));
} else if (node.type == "location_id") {
int64_t id = stoi64(node.text);
if (color.empty()) color = "blue";
text = get_location_name(id, get_player_game(node.player));
} else if (node.type == "hint_status") {
text = node.text;
if (node.hintStatus == HINT_FOUND) color = "green";
else if (node.hintStatus == HINT_UNSPECIFIED) color = "grey";
else if (node.hintStatus == HINT_NO_PRIORITY) color = "slateblue";
else if (node.hintStatus == HINT_AVOID) color = "salmon";
else if (node.hintStatus == HINT_PRIORITY) color = "plum";
else color = "red"; // unknown status -> red
} else {
text = node.text;
}
if (fmt == RenderFormat::ANSI) {
if (color.empty() && colorIsSet) {
out += color2ansi(""); // reset color
colorIsSet = false;
} else if (!color.empty()) {
out += color2ansi(color);
colorIsSet = true;
}
deansify(text);
out += text;
} else {
out += text;
}
}
if (fmt == RenderFormat::ANSI && colorIsSet) out += color2ansi("");
return out;
}
bool LocationChecks(const std::list<int64_t>& locations)
{
// returns true if checks were sent or queued
if (_state == State::SLOT_CONNECTED) {
auto packet = json{{
{"cmd", "LocationChecks"},
{"locations", locations},
}};
debug("> " + packet[0]["cmd"].get<std::string>() + ": " + packet.dump());
_ws->send(packet.dump());
} else {
_checkQueue.insert(locations.begin(), locations.end());
}
if (!_receiveOwnLocations) {
// for receiveOwnLocations, this will be done on the server response instead
for (const auto& location: locations) {
_checkedLocations.insert(location);
_missingLocations.erase(location);
}
}
return true;
}
bool LocationScouts(const std::list<int64_t>& locations, int create_as_hint = 0)
{
// returns true if scouts were sent or queued
if (_state == State::SLOT_CONNECTED) {
auto packet = json{{
{"cmd", "LocationScouts"},
{"locations", locations},
{"create_as_hint", create_as_hint},
}};
debug("> " + packet[0]["cmd"].get<std::string>() + ": " + packet.dump());
_ws->send(packet.dump());
} else {
_scoutQueues[create_as_hint].insert(locations.begin(), locations.end());
}
return true;
}
/**
* Sends UpdateHint to the server to update hint status/priority.
* Returns true if hint update was sent or queued.
*/
bool UpdateHint(int player, int64_t location, HintStatus status)
{
if (_state == State::SLOT_CONNECTED) {
auto packet = json{{
{"cmd", "UpdateHint"},
{"player", player},
{"location", location},
{"status", status},
}};
debug("> " + packet[0]["cmd"].get<std::string>() + ": " + packet.dump());
_ws->send(packet.dump());
} else {
_updateHintQueue.emplace_back(player, location, status);
}
return true;
}
bool CreateHints(std::list<int64_t> locations, int target_player = -1,
HintStatus hint_status = static_cast<HintStatus>(INT_MIN)) {
if (_serverVersion < Version{ 0, 6, 3 }) {
return false;
}
if (target_player == -1) {
target_player = get_player_number();
}
// returns true if hints were sent or queued
if (_state == State::SLOT_CONNECTED) {
auto packet = json{{
{"cmd", "CreateHints"},
{"locations", locations},
{"player", target_player},
}};
if (hint_status != static_cast<HintStatus>(INT_MIN)) {
packet[0]["status"] = hint_status;
}
debug("> " + packet[0]["cmd"].get<std::string>() + ": " + packet.dump());
_ws->send(packet.dump());
}
else {
_createHintsQueueByPlayerAndStatus[{target_player, hint_status}].insert(locations.begin(), locations.end());
}
return true;
}
bool StatusUpdate(ClientStatus status)
{
// returns true if status update was sent or queued
if (_state == State::SLOT_CONNECTED) {
auto packet = json{{
{"cmd", "StatusUpdate"},
{"status", status},
}};
debug("> " + packet[0]["cmd"].get<std::string>() + ": " + packet.dump());
_ws->send(packet.dump());
return true;
}
_clientStatus = status;
return false;
}
bool ConnectSlot(const std::string& name, const std::string& password, const int items_handling,
const std::list<std::string>& tags = {}, const Version& ver = APCLIENTPP_VERSION_INITIALIZER,
const bool slot_data = true)
{
if (_state < State::SOCKET_CONNECTED)
return false;
_slot = name;
debug("Connecting slot...");
auto packet = json{{
{"cmd", "Connect"},
{"game", _game},
{"uuid", _uuid},
{"name", name},
{"password", password},
{"version", ver},
{"items_handling", items_handling},
{"tags", tags},
{"slot_data", slot_data},
}};
debug("> " + packet[0]["cmd"].get<std::string>() + ": " + packet.dump());
_ws->send(packet.dump());
return true;
}
#if defined __cpp_lib_optional || defined __cpp_lib_experimental_optional
# if defined __cpp_lib_optional
template<class T>
using optional = std::optional<T>;
# else
template<class T>
using optional = std::experimental::optional<T>;
# endif
bool ConnectUpdate(optional<int> items_handling, optional<const std::list<std::string>> tags)
{
return ConnectUpdate((bool)items_handling, *items_handling, (bool)tags, *tags);
}
#endif
bool ConnectUpdate(bool send_items_handling, int items_handling, bool send_tags, const std::list<std::string>& tags)
{
if (_state < State::SOCKET_CONNECTED)
return false;
if (!send_items_handling && !send_tags)
return false;
auto packet = json{{
{"cmd", "ConnectUpdate"},