forked from simulationcraft/simc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sc_bcp_api.cpp
1337 lines (1099 loc) · 41.3 KB
/
sc_bcp_api.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
// ==========================================================================
// Dedmonwakeen's Raid DPS/TPS Simulator.
// Send questions to [email protected]
// ==========================================================================
#include "simulationcraft.hpp"
#include "util/rapidjson/document.h"
#include "util/rapidjson/stringbuffer.h"
#include "util/rapidjson/prettywriter.h"
#ifndef SC_NO_NETWORKING
#include <curl/curl.h>
#endif
#include "util/utf8-2.h"
// ==========================================================================
// Blizzard Community Platform API
// ==========================================================================
namespace { // UNNAMED NAMESPACE
struct player_spec_t
{
std::string region, server, name, url, origin, talent_spec;
std::string local_json;
std::string local_json_spec;
std::string local_json_equipment;
std::string local_json_media;
};
static const std::string GLOBAL_OAUTH_ENDPOINT_URI = "https://{}.battle.net/oauth/token";
static const std::string CHINA_OAUTH_ENDPOINT_URI = "https://www.battlenet.com.cn/oauth/token";
static const std::string GLOBAL_GUILD_ENDPOINT_URI = "https://{}.api.blizzard.com/wow/guild/{}/{}?fields=members&locale={}";
static const std::string CHINA_GUILD_ENDPOINT_URI = "https://gateway.battlenet.com.cn/wow/guild/{}/{}?fields=members&locale={}";
static const std::string GLOBAL_PLAYER_ENDPOINT_URI = "https://{}.api.blizzard.com/profile/wow/character/{}/{}?namespace=profile-{}&locale={}";
static const std::string CHINA_PLAYER_ENDPOINT_URI = "https://gateway.battlenet.com.cn/profile/wow/character/{}/{}?namespace=profile-cn";
static const std::string GLOBAL_ITEM_ENDPOINT_URI = "https://{}.api.blizzard.com/wow/item/{}?locale={}";
static const std::string CHINA_ITEM_ENDPOINT_URI = "https://gateway.battlenet.com.cn/wow/item/{}";
static const std::string GLOBAL_ORIGIN_URI = "https://worldofwarcraft.com/{}/character/{}/{}";
static const std::string CHINA_ORIGIN_URI = "https://www.wowchina.com/zh-cn/character/{}/{}";
static std::unordered_map<std::string, std::pair<std::string, std::string>> LOCALES {
{ "us", { "en_US", "en-us" } },
{ "eu", { "en_GB", "en-gb" } },
{ "kr", { "ko_KR", "ko-kr" } },
{ "tw", { "zh_TW", "zh-tw" } }
};
static std::string token_path = "";
static std::string token = "";
static bool authorization_failed = false;
mutex_t token_mutex;
#ifndef SC_NO_NETWORKING
size_t data_cb( void* contents, size_t size, size_t nmemb, void* usr )
{
std::string* obj = reinterpret_cast<std::string*>( usr );
obj->append( reinterpret_cast<const char*>( contents ), size * nmemb );
return size * nmemb;
}
std::vector<std::string> token_paths()
{
std::vector<std::string> paths;
paths.push_back( "./simc-apitoken" );
if ( const char* home_path = getenv( "HOME" ) )
{
paths.push_back( std::string( home_path ) + "/.simc-apitoken" );
}
if ( const char* home_drive = getenv( "HOMEDRIVE" ) )
{
if ( const char* home_path = getenv( "HOMEPATH" ) )
{
paths.push_back( std::string( home_drive ) + std::string( home_path ) + "/simc-apitoken" );
}
}
return paths;
}
// Authorize to the blizzard api
bool authorize( sim_t* sim, const std::string& region )
{
if ( !sim->user_apitoken.empty() )
{
return true;
}
// Authorization needs to be a single threaded process, all threads will re-use the same token
// once a single thread properly fetches it
auto_lock_t lock( token_mutex );
// If an authorization process failed on any thread attempting to perform it, no point trying it
// again, just fail the rest
if ( authorization_failed )
{
return false;
}
// A token has already been loaded, so don't re-authorize
if ( !token.empty() )
{
return true;
}
std::string ua_str = "Simulationcraft/" + std::string( SC_VERSION );
std::string oauth_endpoint;
if ( util::str_compare_ci( region, "eu" ) || util::str_compare_ci( region, "us" ) )
{
oauth_endpoint = fmt::format( GLOBAL_OAUTH_ENDPOINT_URI, region );
}
else if ( util::str_compare_ci( region, "kr" ) || util::str_compare_ci( region, "tw" ) )
{
oauth_endpoint = fmt::format( GLOBAL_OAUTH_ENDPOINT_URI, "apac" );
}
else if ( util::str_compare_ci( region, "cn" ) )
{
oauth_endpoint = CHINA_OAUTH_ENDPOINT_URI;
}
auto handle = curl_easy_init();
std::string buffer;
char error_buffer[ CURL_ERROR_SIZE ];
error_buffer[ 0 ] = '\0';
curl_easy_setopt( handle, CURLOPT_URL, oauth_endpoint.c_str() );
//curl_easy_setopt( handle, CURLOPT_VERBOSE, 1L);
curl_easy_setopt( handle, CURLOPT_FAILONERROR, 1L);
curl_easy_setopt( handle, CURLOPT_POSTFIELDS, "grant_type=client_credentials" );
curl_easy_setopt( handle, CURLOPT_USERPWD, sim->apikey.c_str() );
curl_easy_setopt( handle, CURLOPT_TIMEOUT, 15L );
curl_easy_setopt( handle, CURLOPT_FOLLOWLOCATION, 1L );
curl_easy_setopt( handle, CURLOPT_MAXREDIRS, 5L );
curl_easy_setopt( handle, CURLOPT_ACCEPT_ENCODING, "");
curl_easy_setopt( handle, CURLOPT_USERAGENT, ua_str.c_str() );
curl_easy_setopt( handle, CURLOPT_WRITEFUNCTION, data_cb );
curl_easy_setopt( handle, CURLOPT_WRITEDATA, reinterpret_cast<void*>( &buffer ) );
curl_easy_setopt( handle, CURLOPT_ERRORBUFFER, error_buffer );
auto res = curl_easy_perform( handle );
if ( res != CURLE_OK )
{
std::cerr << "Unable to fetch bearer token from " << oauth_endpoint << ", " << error_buffer << std::endl;
curl_easy_cleanup( handle );
authorization_failed = true;
return false;
}
rapidjson::Document response;
response.Parse< 0 >( buffer );
if ( response.HasParseError() )
{
std::cerr << "Unable to parse response message from " << oauth_endpoint << std::endl;
curl_easy_cleanup( handle );
authorization_failed = true;
return false;
}
if ( !response.HasMember( "access_token" ) )
{
std::cerr << "Malformed JSON object from " << oauth_endpoint << std::endl;
curl_easy_cleanup( handle );
authorization_failed = true;
return false;
}
token = response[ "access_token" ].GetString();
curl_easy_cleanup( handle );
return true;
}
#else
bool authorize( sim_t*, const std::string& )
{
return false;
}
#endif /* SC_NO_NETWORKING */
// download
// Check for errors and return the (HTTP) return code from the status message, if applicable. Return
// value of 0 indicates error.
int check_for_error( sim_t* sim,
const rapidjson::Document& d,
std::vector<int> allowed_codes = {} )
{
auto ret_code = 200;
// Old community API NOK status, report Blizzard API reason to the user. Note that there's no way
// to check for the return codes in the json object response, since they don't exist there
if ( d.IsObject() && d.HasMember( "status" ) &&
util::str_compare_ci( d[ "status" ].GetString(), "nok" ) )
{
sim->error( "Error response from Blizzard API: {}", d[ "reason" ].GetString() );
return 0;
}
// New community API status code handling
if ( d.IsObject() && d.HasMember( "code" ) )
{
ret_code = d[ "code" ].GetInt();
if ( range::find( allowed_codes, ret_code ) == allowed_codes.end() )
{
sim->error( "Error response {} from Blizzard API: {}", ret_code, d[ "detail" ].GetString() );
return 0;
}
}
return ret_code;
}
// Check if HTTP response code falls on the ranges of successful responses from the Blizzard API
bool check_response_code( int response_code )
{
// 401 implies reauthentication required, so it's not a valid response
return ( response_code >= 200 && response_code < 300 ) ||
( response_code >= 400 && response_code < 500 && response_code != 401 );
}
bool download( sim_t* sim,
rapidjson::Document& d,
const std::string& region,
const std::string& url,
cache::behavior_e caching )
{
std::vector<std::string> headers;
std::string result;
if ( !authorize( sim, region ) )
{
return false;
}
if ( !sim->user_apitoken.empty() )
{
headers.push_back( "Authorization: Bearer " + sim->user_apitoken );
}
else
{
headers.push_back( "Authorization: Bearer " + token );
}
// We can make two attempts at most
for ( size_t i = 0; i < 2; ++i )
{
auto response_code = http::get( result, url, caching, "", headers );
if ( check_response_code( response_code ) )
{
break;
}
// Blizzard's issue, lets not bother trying again
if ( response_code >= 500 && response_code < 600 )
{
sim->error( "Blizzard API responded with internal server error ({}), aborting",
response_code );
return false;
}
// Bearer token is invalid, lets try to regenerate if we can
else if ( response_code == 401 )
{
// Loaded token is bogus, so clear it
token.clear();
// If there's an user provided apitoken and we get 401, or if we already regenerated
// our bearer token successfully, there's no point in trying again
if ( !sim->user_apitoken.empty() )
{
sim->error( "Invalid user 'apitoken' option value '{}'", sim->user_apitoken );
return false;
}
// Re-Authorization failed
if ( !authorize( sim, region ) )
{
return false;
}
// Clear old bearer token from headers and add the new one
headers.clear();
headers.push_back( "Authorization: Bearer " + token );
}
// Note, not modified is automatically handled by http::get, and translated into 200 OK
else
{
sim->error( "Blizzard API responded with an unhandled HTTP response code {}",
response_code );
return false;
}
}
d.Parse<0>( result.c_str() );
// Corrupt data
if ( !result.empty() && d.HasParseError() )
{
sim->error( "Malformed response from Blizzard API" );
return false;
}
if ( sim->debug )
{
rapidjson::StringBuffer b;
rapidjson::PrettyWriter< rapidjson::StringBuffer > writer( b );
d.Accept( writer );
sim->out_debug.raw() << b.GetString();
}
return true;
}
// download_item ==============================================================
bool download_item( sim_t* sim,
rapidjson::Document& d,
const std::string& region,
unsigned item_id,
cache::behavior_e caching )
{
if ( item_id == 0 )
return false;
std::string url;
if ( !util::str_compare_ci( region, "cn" ) )
{
url = fmt::format( GLOBAL_ITEM_ENDPOINT_URI, region, item_id, LOCALES[ region ].first );
}
else
{
url = fmt::format( CHINA_ITEM_ENDPOINT_URI, item_id );
}
if ( !download( sim, d, region, url, caching ) )
return false;
if ( !check_for_error( sim, d ) )
{
return false;
}
return true;
}
bool parse_file( sim_t* sim, const std::string& path, rapidjson::Document& d )
{
std::string result;
io::ifstream ifs;
ifs.open( path );
result.assign( std::istreambuf_iterator<char>( ifs ), std::istreambuf_iterator<char>() );
d.Parse<0>( result.c_str() );
// Corrupt data
if ( ! result.empty() && d.HasParseError() )
{
sim->error( "Malformed data in '{}'", path );
return false;
}
if ( sim->debug )
{
rapidjson::StringBuffer b;
rapidjson::PrettyWriter< rapidjson::StringBuffer > writer( b );
d.Accept( writer );
sim->out_debug.raw() << b.GetString();
}
return true;
}
// parse_talents ============================================================
void parse_talents( player_t* p, const player_spec_t& spec_info, const std::string& url, cache::behavior_e caching )
{
rapidjson::Document spec;
if ( spec_info.local_json.empty() && spec_info.local_json_spec.empty() )
{
if ( !download( p->sim, spec, p->region_str, url + "&locale=en_US", caching ) )
{
throw std::runtime_error(fmt::format("Unable to download talent JSON from '{}'.",
url ));
}
}
else if ( !spec_info.local_json_spec.empty() )
{
if ( !parse_file( p->sim, spec_info.local_json_spec, spec ) )
{
throw std::runtime_error( fmt::format( "Unable to parse local JSON from '{}'.",
spec_info.local_json_spec ) );
}
}
if ( !spec.IsObject() )
{
return;
}
if ( !spec.HasMember( "active_specialization" ) ||
!spec[ "active_specialization" ].HasMember( "id" ) )
{
throw std::runtime_error( fmt::format( "Unable to determine active spec for talent parsing" ) );
}
unsigned spec_id = spec[ "active_specialization" ][ "id" ].GetUint();
// Iterate over talent specs, choosing the correct one
for ( auto idx = 0U, end = spec[ "specializations" ].Size(); idx < end; ++idx )
{
const auto& spec_data = spec[ "specializations" ][ idx ];
if ( !spec_data.HasMember( "specialization" ) ||
!spec_data[ "specialization" ].HasMember( "id" ) )
{
throw std::runtime_error( fmt::format( "Unable to determine talent spec for talent parsing" ) );
}
if ( spec_data[ "specialization" ][ "id" ].GetUint() != spec_id )
{
continue;
}
if ( !spec_data.HasMember( "talents" ) )
{
continue;
}
const auto& talents = spec_data[ "talents" ];
for ( auto talent_idx = 0u, talent_end = talents.Size(); talent_idx < talent_end; ++talent_idx )
{
const auto& talent_data = talents[ talent_idx ];
if ( !talent_data.HasMember( "talent" ) || !talent_data[ "talent" ].HasMember( "id" ) )
{
throw std::runtime_error( "Unable to determine talent id for talent parsing" );
}
auto talent_id = talent_data[ "talent" ][ "id" ].GetUint();
const auto talent = p->dbc.talent( talent_id );
if ( talent->id() != talent_id )
{
p->sim->error( "Warning: Unable to find talent id {} for {} from Simulationcraft client data",
talent_id, p->name() );
continue;
}
p->talent_points.select_row_col( talent->row(), talent->col() );
}
}
p->recreate_talent_str( TALENT_FORMAT_ARMORY );
}
// parse_items ==============================================================
void parse_items( player_t* p, const player_spec_t& spec, const std::string& url, cache::behavior_e caching )
{
rapidjson::Document equipment_data;
if ( spec.local_json.empty() && spec.local_json_equipment.empty() )
{
if ( !download( p->sim, equipment_data, p->region_str, url + "&locale=en_US", caching ) )
{
throw std::runtime_error(fmt::format("Unable to download equipment JSON from '{}'.",
url ));
}
}
else if ( !spec.local_json_equipment.empty() )
{
if ( !parse_file( p->sim, spec.local_json_equipment, equipment_data ) )
{
throw std::runtime_error( fmt::format( "Unable to parse equipment JSON from '{}'.",
spec.local_json_equipment ));
}
}
if ( !equipment_data.IsObject() || !equipment_data.HasMember( "equipped_items" ) )
{
return;
}
for ( auto idx = 0u, end = equipment_data[ "equipped_items" ].Size(); idx < end; ++idx )
{
const auto& slot_data = equipment_data[ "equipped_items" ][ idx ];
if ( !slot_data.HasMember( "item" ) || !slot_data[ "item" ].HasMember( "id" ) )
{
throw std::runtime_error( "Unable to parse item data: Missing item information" );
}
if ( !slot_data.HasMember( "slot" ) || !slot_data[ "slot" ].HasMember( "type" ) )
{
throw std::runtime_error( "Unable to parse item data: Missing slot information" );
}
slot_e slot = bcp_api::translate_api_slot( slot_data[ "slot" ][ "type" ].GetString() );
if ( slot == SLOT_INVALID )
{
throw std::runtime_error( fmt::format( "Unknown slot '{}'",
slot_data[ "slot" ][ "type" ].GetString() ) );
}
auto& item = p->items[ slot ];
item.parsed.data.id = slot_data[ "item" ][ "id" ].GetUint();
if ( slot_data.HasMember( "timewalker_level" ) )
{
item.parsed.drop_level = slot_data[ "timewalker_level" ].GetUint();
}
if ( slot_data.HasMember( "bonus_list" ) )
{
for ( auto bonus_idx = 0u, end = slot_data[ "bonus_list" ].Size(); bonus_idx < end; ++bonus_idx )
{
item.parsed.bonus_id.push_back( slot_data[ "bonus_list" ][ bonus_idx ].GetInt() );
}
}
if ( slot_data.HasMember( "enchantments" ) )
{
for ( auto ench_idx = 0u, end = slot_data[ "enchantments" ].Size(); ench_idx < end; ++ench_idx )
{
const auto& ench_data = slot_data[ "enchantments" ][ ench_idx ];
if ( !ench_data.HasMember( "enchantment_id" ) )
{
throw std::runtime_error( "Unable to parse enchant data: Missing enchantment ID" );
}
if ( !ench_data.HasMember( "enchantment_slot" ) )
{
throw std::runtime_error( "Unable to parse enchant data: Missing enchantment slot data" );
}
switch (ench_data[ "enchantment_slot" ][ "id" ].GetInt()) {
// PERMANENT
case 0:
item.parsed.enchant_id = ench_data[ "enchantment_id" ].GetInt();
break;
// BONUS_SOCKETS
case 6:
break;
// ON_USE_SPELL
case 7:
item.parsed.addon_id = ench_data[ "enchantment_id" ].GetInt();
break;
}
}
}
if ( slot_data.HasMember( "sockets" ) )
{
for ( auto gem_idx = 0u, end = slot_data[ "sockets" ].Size(); gem_idx < end; ++gem_idx )
{
const auto& socket_data = slot_data[ "sockets" ][ gem_idx ];
if ( !socket_data.HasMember( "item" ) )
{
continue;
}
if ( !socket_data[ "item" ].HasMember( "id" ) )
{
throw std::runtime_error( "Unable to parse socket data: Missing item information" );
}
item.parsed.gem_id[ gem_idx ] = socket_data[ "item" ][ "id" ].GetInt();
if ( socket_data.HasMember( "bonus_list" ) )
{
for ( auto gbonus_idx = 0u, end = socket_data[ "bonus_list" ].Size(); gbonus_idx < end; ++gbonus_idx )
{
item.parsed.gem_bonus_id[ gem_idx ].push_back( socket_data[ "bonus_list" ][ gbonus_idx ].GetInt() );
}
}
}
}
azerite::parse_blizzard_azerite_information( item, slot_data );
}
}
void parse_media( player_t* p,
const player_spec_t& spec,
const std::string& url,
cache::behavior_e caching )
{
rapidjson::Document media_data;
if ( spec.local_json.empty() && spec.local_json_media.empty() )
{
if ( !download( p->sim, media_data, p->region_str, url + "&locale=en_US", caching ) )
{
throw std::runtime_error(fmt::format("Unable to download media JSON from '{}'.", url ));
}
}
else if ( !spec.local_json_media.empty() )
{
if ( !parse_file( p->sim, spec.local_json_media, media_data ) )
{
throw std::runtime_error( fmt::format( "Unable to parse media information JSON from '{}'.",
spec.local_json_media ) );
}
}
if ( !media_data.IsObject() )
{
return;
}
if ( media_data.HasMember( "bust_url" ) )
{
p->report_information.thumbnail_url = media_data[ "bust_url" ].GetString();
}
}
// parse_player =============================================================
player_t* parse_player( sim_t* sim,
player_spec_t& player,
cache::behavior_e caching,
bool allow_failures = false )
{
sim -> current_slot = 0;
rapidjson::Document profile;
// China does not have mashery endpoints, so no point in even trying to get anything here
if ( player.local_json.empty() )
{
if ( !download( sim, profile, player.region, player.url + "&locale=en_US", caching ) )
{
throw std::runtime_error(fmt::format("Unable to download JSON from '{}'.",
player.url ));
}
}
else
{
if ( !parse_file( sim, player.local_json, profile ) )
{
throw std::runtime_error( fmt::format( "Unable to parse JSON from '{}'.",
player.local_json ) );
}
}
if ( !allow_failures && !check_for_error( sim, profile ) )
{
throw std::runtime_error(fmt::format("Unable to download JSON from '{}'.",
player.url ));
}
// 200, 403, 404 results are OK, anything else not OK
else if ( allow_failures )
{
auto ret_code = check_for_error( sim, profile, {403, 404} );
if ( !ret_code )
{
throw std::runtime_error(fmt::format("Unable to download JSON from '{}'.",
player.url ));
}
else if ( ret_code == 403 || ret_code == 404 )
{
return nullptr;
}
}
if ( profile.HasMember( "name" ) )
player.name = profile[ "name" ].GetString();
if ( ! profile.HasMember( "level" ) )
{
throw std::runtime_error("Unable to extract player level.");
}
if ( ! profile.HasMember( "character_class" ) )
{
throw std::runtime_error("Unable to extract player class.");
}
if ( ! profile.HasMember( "race" ) )
{
throw std::runtime_error("Unable to extract player race.");
}
if ( ! profile.HasMember( "specializations" ) )
{
throw std::runtime_error("Unable to extract player talents.");
}
std::string class_name = util::player_type_string( util::translate_class_id( profile[ "character_class" ][ "id" ].GetUint() ) );
race_e race = util::translate_race_id( profile[ "race" ][ "id" ].GetUint() );
const module_t* module = module_t::get( class_name );
if ( ! module || ! module -> valid() )
{
throw std::runtime_error(fmt::format("Module for class '{}' is currently not available.", class_name ));
}
std::string name = player.name;
if ( player.talent_spec != "active" && ! player.talent_spec.empty() )
{
name += '_';
name += player.talent_spec;
}
if ( ! name.empty() )
sim -> current_name = name;
player_t* p = sim -> active_player = module -> create_player( sim, name, race );
if ( ! p )
{
throw std::runtime_error(fmt::format("Unable to build player with class '{}' and name '{}'.",
class_name, name ));
}
p -> true_level = profile[ "level" ].GetUint();
p -> region_str = player.region.empty() ? sim -> default_region_str : player.region;
if ( ! profile.HasMember( "realm" ) && ! player.server.empty() )
p -> server_str = player.server;
else
p -> server_str = profile[ "realm" ][ "name" ].GetString();
if ( ! player.origin.empty() )
p -> origin_str = player.origin;
if ( profile.HasMember( "active_spec" ) && profile[ "active_spec" ].HasMember( "id" ) )
{
p->_spec = static_cast<specialization_e>( profile[ "active_spec" ][ "id" ].GetInt() );
}
if ( profile.HasMember( "media" ) && profile[ "media" ].HasMember( "href" ) )
{
parse_media( p, player, profile[ "media" ][ "href" ].GetString(), caching );
}
if ( profile.HasMember( "specializations" ) )
{
parse_talents( p, player, profile[ "specializations" ][ "href" ].GetString(), caching );
}
if ( profile.HasMember( "equipment" ) )
{
parse_items( p, player, profile[ "equipment" ][ "href" ].GetString(), caching );
}
if ( ! p -> server_str.empty() )
p -> armory_extensions( p -> region_str, p -> server_str, player.name, caching );
p->profile_source_ = profile_source::BLIZZARD_API;
return p;
}
// download_item_data =======================================================
bool download_item_data( item_t& item, cache::behavior_e caching )
{
rapidjson::Document js;
if ( ! download_item( item.sim, js, item.player -> region_str, item.parsed.data.id, caching ) ||
js.HasParseError() )
{
if ( caching != cache::ONLY )
{
item.sim -> errorf( "BCP API: Player '%s' unable to download item id '%u' at slot %s.\n",
item.player -> name(), item.parsed.data.id, item.slot_name() );
}
return false;
}
if ( item.sim -> debug )
{
rapidjson::StringBuffer b;
rapidjson::PrettyWriter< rapidjson::StringBuffer > writer( b );
js.Accept( writer );
item.sim -> out_debug.raw() << b.GetString();
}
try
{
if ( ! js.HasMember( "id" ) ) throw( "id" );
if ( ! js.HasMember( "itemLevel" ) ) throw( "item level" );
if ( ! js.HasMember( "quality" ) ) throw( "quality" );
if ( ! js.HasMember( "inventoryType" ) ) throw( "inventory type" );
if ( ! js.HasMember( "itemClass" ) ) throw( "item class" );
if ( ! js.HasMember( "itemSubClass" ) ) throw( "item subclass" );
if ( ! js.HasMember( "name" ) ) throw( "name" );
item.parsed.data.id = js[ "id" ].GetUint();
item.parsed.data.level = js[ "itemLevel" ].GetUint();
item.parsed.data.quality = js[ "quality" ].GetUint();
item.parsed.data.inventory_type = js[ "inventoryType" ].GetUint();
item.parsed.data.item_class = js[ "itemClass" ].GetUint();
item.parsed.data.item_subclass = js[ "itemSubClass" ].GetUint();
item.name_str = js[ "name" ].GetString();
util::tokenize( item.name_str );
if ( js.HasMember( "icon" ) ) item.icon_str = js[ "icon" ].GetString();
if ( js.HasMember( "requiredLevel" ) ) item.parsed.data.req_level = js[ "requiredLevel" ].GetUint();
if ( js.HasMember( "requiredSkill" ) ) item.parsed.data.req_skill = js[ "requiredSkill" ].GetUint();
if ( js.HasMember( "requiredSkillRank" ) ) item.parsed.data.req_skill_level = js[ "requiredSkillRank" ].GetUint();
if ( js.HasMember( "itemBind" ) ) item.parsed.data.bind_type = js[ "itemBind" ].GetUint();
if ( js.HasMember( "weaponInfo" ) )
{
const rapidjson::Value& weaponInfo = js[ "weaponInfo" ];
if ( ! weaponInfo.HasMember( "dps" ) ) throw( "dps" );
if ( ! weaponInfo.HasMember( "weaponSpeed" ) ) throw( "weapon speed" );
if ( ! weaponInfo.HasMember( "damage" ) ) throw( "damage" );
const rapidjson::Value& damage = weaponInfo[ "damage" ];
if ( ! damage.HasMember( "exactMin" ) ) throw( "weapon minimum damage" );
item.parsed.data.delay = static_cast< unsigned >( weaponInfo[ "weaponSpeed" ].GetDouble() * 1000.0 );
item.parsed.data.dmg_range = 2 - 2 * damage[ "exactMin" ].GetDouble() / ( weaponInfo[ "dps" ].GetDouble() * weaponInfo[ "weaponSpeed" ].GetDouble() );
}
if ( js.HasMember( "allowableClasses" ) )
{
for ( rapidjson::SizeType i = 0, n = js[ "allowableClasses" ].Size(); i < n; ++i )
item.parsed.data.class_mask |= ( 1 << ( js[ "allowableClasses" ][ i ].GetInt() - 1 ) );
}
else
item.parsed.data.class_mask = -1;
if ( js.HasMember( "allowableRaces" ) )
{
for ( rapidjson::SizeType i = 0, n = js[ "allowableRaces" ].Size(); i < n; ++i )
item.parsed.data.race_mask |= ( uint64_t(1) << ( js[ "allowableRaces" ][ i ].GetInt() - 1 ) );
}
else
item.parsed.data.race_mask = -1;
if ( js.HasMember( "bonusStats" ) )
{
for ( rapidjson::SizeType i = 0, n = js[ "bonusStats" ].Size(); i < n; ++i )
{
const rapidjson::Value& stat = js[ "bonusStats" ][ i ];
if ( ! stat.HasMember( "stat" ) ) throw( "bonus stat" );
if ( ! stat.HasMember( "amount" ) ) throw( "bonus stat amount" );
item.parsed.data.stat_type_e[ i ] = stat[ "stat" ].GetInt();
item.parsed.stat_val[ i ] = stat[ "amount" ].GetInt();
if ( js.HasMember( "weaponInfo" ) &&
( item.parsed.data.stat_type_e[ i ] == ITEM_MOD_INTELLECT ||
item.parsed.data.stat_type_e[ i ] == ITEM_MOD_SPIRIT ||
item.parsed.data.stat_type_e[ i ] == ITEM_MOD_SPELL_POWER ) )
item.parsed.data.flags_2 |= ITEM_FLAG2_CASTER_WEAPON;
}
}
if ( js.HasMember( "socketInfo" ) && js[ "socketInfo" ].HasMember( "sockets" ) )
{
const rapidjson::Value& sockets = js[ "socketInfo" ][ "sockets" ];
for (rapidjson::SizeType i = 0, n = as<rapidjson::SizeType>( std::min(static_cast< size_t >(sockets.Size()), sizeof_array(item.parsed.data.socket_color))); i < n; ++i)
{
if ( ! sockets[ i ].HasMember( "type" ) )
continue;
std::string color = sockets[ i ][ "type" ].GetString();
if ( color == "META" )
item.parsed.data.socket_color[ i ] = SOCKET_COLOR_META;
else if ( color == "RED" )
item.parsed.data.socket_color[ i ] = SOCKET_COLOR_RED;
else if ( color == "YELLOW" )
item.parsed.data.socket_color[ i ] = SOCKET_COLOR_YELLOW;
else if ( color == "BLUE" )
item.parsed.data.socket_color[ i ] = SOCKET_COLOR_BLUE;
else if ( color == "PRISMATIC" )
item.parsed.data.socket_color[ i ] = SOCKET_COLOR_PRISMATIC;
else if ( color == "COGWHEEL" )
item.parsed.data.socket_color[ i ] = SOCKET_COLOR_COGWHEEL;
else if ( color == "HYDRAULIC" )
item.parsed.data.socket_color[ i ] = SOCKET_COLOR_HYDRAULIC;
}
if ( js[ "socketInfo" ].HasMember( "socketBonus" ) )
{
std::string socketBonus = js[ "socketInfo" ][ "socketBonus" ].GetString();
std::string stat;
util::fuzzy_stats( stat, socketBonus );
std::vector<stat_pair_t> bonus = item_t::str_to_stat_pair( stat );
item.parsed.socket_bonus_stats.insert( item.parsed.socket_bonus_stats.end(), bonus.begin(), bonus.end() );
}
}
if ( js.HasMember( "itemSet" ) && js[ "itemSet" ].HasMember( "id" ) )
{
item.parsed.data.id_set = js[ "itemSet" ][ "id" ].GetUint();
}
if ( js.HasMember( "nameDescription" ) )
{
std::string nameDescription = js[ "nameDescription" ].GetString();
if ( util::str_in_str_ci( nameDescription, "heroic" ) )
item.parsed.data.type_flags |= RAID_TYPE_HEROIC;
else if ( util::str_in_str_ci( nameDescription, "raid finder" ) )
item.parsed.data.type_flags |= RAID_TYPE_LFR;
else if ( util::str_in_str_ci( nameDescription, "mythic" ) )
item.parsed.data.type_flags |= RAID_TYPE_MYTHIC;
if ( util::str_in_str_ci( nameDescription, "warforged" ) )
item.parsed.data.type_flags |= RAID_TYPE_WARFORGED;
}
if ( js.HasMember( "itemSpells" ) )
{
const rapidjson::Value& spells = js[ "itemSpells" ];
size_t spell_idx = 0;
for ( rapidjson::SizeType i = 0, n = spells.Size(); i < n && spell_idx < sizeof_array( item.parsed.data.id_spell ); ++i )
{
const rapidjson::Value& spell = spells[ i ];
if ( ! spell.HasMember( "spellId" ) || ! spell.HasMember( "trigger" ) )
continue;
int spell_id = spell[ "spellId" ].GetInt();
int trigger_type = -1;
if ( util::str_compare_ci( spell[ "trigger" ].GetString(), "ON_EQUIP" ) )
trigger_type = ITEM_SPELLTRIGGER_ON_EQUIP;
else if ( util::str_compare_ci( spell[ "trigger" ].GetString(), "ON_USE" ) )
trigger_type = ITEM_SPELLTRIGGER_ON_USE;
else if ( util::str_compare_ci( spell[ "trigger" ].GetString(), "ON_PROC" ) )
trigger_type = ITEM_SPELLTRIGGER_CHANCE_ON_HIT;
if ( trigger_type != -1 && spell_id > 0 )
{
item.parsed.data.id_spell[ spell_idx ] = spell_id;
item.parsed.data.trigger_spell[ spell_idx ] = trigger_type;
spell_idx++;
}
}
}
// Convert Blizzard item stat values into actual stat allocation percents, so we can do normal
// stat computation on the item. This presumes that blizzard item data will always give us the
// correct data for the item (in relation to the item level reported)
item_database::convert_stat_values( item );
}
catch ( const char* fieldname )
{
std::string error_str;
if ( js.HasMember( "reason" ) )
error_str = js[ "reason" ].GetString();
if ( caching != cache::ONLY )
item.sim -> errorf( "BCP API: Player '%s' unable to parse item '%u' %s at slot '%s': %s\n",
item.player -> name(), item.parsed.data.id, fieldname, item.slot_name(), error_str.c_str() );
return false;
}
return true;
}
// download_roster ==========================================================
bool download_roster( rapidjson::Document& d,
sim_t* sim,
const std::string& region,
const std::string& server,
const std::string& name,
cache::behavior_e caching )
{
std::string url;
if ( !util::str_compare_ci( region, "cn" ) )
{
url = fmt::format( GLOBAL_GUILD_ENDPOINT_URI, region, server, name, LOCALES[ region ].first );
}
else
{
url = fmt::format( CHINA_GUILD_ENDPOINT_URI, server, name );
}
if ( ! download( sim, d, region, url, caching ) )
{
return false;