-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswgohhelp-api.js
1345 lines (1146 loc) · 43.7 KB
/
swgohhelp-api.js
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
/*jshint esversion: 6 */
/**
* CombatTypeEnum is the enum value for an Unit combat type.
*/
const CombatTypeEnum = {
"CombatTypeChar": 1,
"CombatTypeShip": 2
};
/**
* SquadUnitTypeEnum is the enum value of an arena unit type.
*/
const SquadUnitTypeEnum = {
"SquadUnitNormal": 1,
"SquadUnitLeader": 2,
"SquadUnitCapitalShip": 3,
"SquadUnitReinforcement": 5
};
/**
* ModSetEnum is the enum of possible bonus set values.
*/
const ModSetEnum = {
"ModSetHealth": 1,
"ModSetOffense": 2,
"ModSetDefense": 3,
"ModSetSpeed": 4,
"ModSetCritChance": 5,
"ModSetCritDamage": 6,
"ModSetPotency": 7,
"ModSetTenacity": 8
};
/**
* ModUnitStatEnum is the enum with mod unit stat values.
*/
const ModUnitStatEnum = {
"StatHealth": 1,
"StatStrength": 2,
"StatAgility": 3,
"StatIntelligence": 4,
"StatSpeed": 5,
"StatAttackDamage": 6,
"StatAbilityPower": 7,
"StatArmor": 8,
"StatSuppression": 9,
"StatArmorPenetration": 10,
"StatSuppressionPenetration": 11,
"StatDodgeRating": 12,
"StatDeflectionRating": 13,
"StatAttackCriticalRating": 14,
"StatAbilityCriticalRating": 15,
"StatCriticalDamage": 16,
"StatAccuracy": 17,
"StatResistance": 18,
"StatDodgePercentAdditive": 19,
"StatDeflectionPercentAdditive": 20,
"StatAttackCriticalPercentAdditive": 21,
"StatAbilityCriticalPercentAdditive": 22,
"StatArmorPercentAdditive": 23,
"StatSuppressionPercentAdditive": 24,
"StatArmorPenetrationPercentAdditive": 25,
"StatSuppressionPenetrationPercentAdditive" : 26,
"StatHealthSteal": 27,
"StatMaxShield": 28,
"StatShieldPenetration": 29,
"StatHealthRegen": 30,
"StatAttackDamagePercentAdditive": 31,
"StatAbilityPowerPercentAdditive": 32,
"StatDodgeNegatePercentAdditive": 33,
"StatDeflectionNegatePercentAdditive": 34,
"StatAttackCriticalNegatePercentAdditive": 35,
"StatAbilityCriticalNegatePercentAdditive": 36,
"StatDodgeNegateRating": 37,
"StatDeflectionNegateRating": 38,
"StatAttackCriticalNegateRating": 39,
"StatAbilityCriticalNegateRating": 40,
"StatOffense": 41,
"StatDefense": 42,
"StatDefensePenetration": 43,
"StatEvasionRating": 44,
"StatCriticalRating": 45,
"StatEvasionNegateRating": 46,
"StatCriticalNegateRating": 47,
"StatOffensePercentAdditive": 48,
"StatDefensePercentAdditive": 49,
"StatDefensePenetrationPercentAdditive": 50,
"StatEvasionPercentAdditive": 51,
"StatEvasionNegatePercentAdditive": 52,
"StatCriticalChancePercentAdditive" : 53,
"StatCriticalNegateChancePercentAdditive": 54,
"StatMaxHealthPercentAdditive": 55,
"StatMaxShieldPercentAdditive": 56,
"StatSpeedPercentAdditive": 57,
"StatCounterAttackRating": 58,
"StatTaunt": 59
};
/**
* ModSlotEnum is the mod slot enum.
*/
const ModSlotEnum = {
"ModSlotSquare": 1,
"ModSlotArrow": 2,
"ModSlotDiamond": 3,
"ModSlotTriangle": 4,
"ModSlotCircle": 5,
"ModSlotCross": 6
};
/**
* Maximum unit levels.
*/
const MAX_UNIT_LEVELS = 85;
/**
* Maximum unit stars.
*/
const MAX_UNIT_STARS = 7;
/**
* Maximum character gear level.
*/
const MAX_CHAR_GEAR_LEVEL = 13;
/**
* Maximum character zetas.
*/
const MAX_CHAR_ZETAS = 6;
/**
* Maximum character relics (for gear 13).
*/
const MAX_CHAR_RELICS = 9;
/**
* Valid collections for data gathering in APIs.
*/
const CollectionsEnum = {
"CollectionAbilityList": "abilityList",
"CollectionBattleEnvironmentsList": "battleEnvironmentsList",
"CollectionBattleTargetingRuleList": "battleTargetingRuleList",
"CollectionCategoryList": "categoryList",
"CollectionChallengeList": "challengeList",
"CollectionChallengeStyleList": "challengeStyleList",
"CollectionEffectList": "effectList",
"CollectionEnvironmentCollectionList": "environmentCollectionList",
"CollectionEquipmentList": "equipmentList",
"CollectionEventSamplingList": "eventSamplingList",
"CollectionGuildExchangeItemList": "guildExchangeItemList",
"CollectionGuildRaidList": "guildRaidList",
"CollectionHelpEntryList": "helpEntryList",
"CollectionMaterialList": "materialList",
"CollectionPlayerTitleList": "playerTitleList",
"CollectionPowerUpBundleList": "powerUpBundleList",
"CollectionRaidConfigList": "raidConfigList",
"CollectionRecipeList": "recipeList",
"CollectionRequirementList": "requirementList",
"CollectionSkillList": "skillList",
"CollectionStarterGuildList": "starterGuildList",
"CollectionStatModList": "statModList",
"CollectionStatModSetList": "statModSetList",
"CollectionStatProgressionList": "statProgressionList",
"CollectionTableList": "tableList",
"CollectionTargetingSetList": "targetingSetList",
"CollectionTerritoryBattleDefinitionList": "territoryBattleDefinitionList",
"CollectionTerritoryWarDefinitionList": "territoryWarDefinitionList",
"CollectionUnitsList": "unitsList",
"CollectionUnlockAnnouncementDefinitionList": "unlockAnnouncementDefinitionList",
"CollectionWarDefinitionList": "warDefinitionList",
"CollectionXpTableList": "xpTableList"
};
/**
* Valid guild member levels.
*/
const GuildMemberLevelEnum = {
"GuildMemberLevelRegular": 2,
"GuildMemberLevelOfficer": 3,
"GuildMemberLevelLeader": 4
};
// file system access module
const fs = require('fs');
/**
* Player titles.
* @typedef {object} PlayerTitles
* @property {string} selected Selected player title.
* @property {string[]} unlocked Full list of unlocked player titles.
*/
/**
* Player stats.
* @typedef {object} PlayerStat
* @property {string} nameKey Stat name key.
* @property {number} value Stat value.
* @property {number} index Stat index.
*/
/**
* @typedef {object} ArenaSquadUnit
* @property {string} id Unit id.
* @property {string} defId Unit definition id.
* @property {number} squadUnitType Squad unit type (1 - Normal unit, 2 - Squad leader, 3 - Capital ship, 5 - Ship reinforcement)
*/
/**
* Arena data detail.
* @typedef {object} ArenaDataDetail
* @property {number} rank Arena rank.
* @property {ArenaSquadUnit[]} squad List of squad units used in arena.
*/
/**
* Player arena data.
* @typedef {object} PlayerArena
* @property {ArenaDataDetail} char Character arena data.
* @property {ArenaDataDetail} ship Ship arena data.
*/
/**
* Player portraits.
* @typedef {object} PlayerPortraits
* @property {string} selected Selected portrait.
* @property {string[]} unlocked List of all unlocked player portraits.
*/
/**
* Player grand arena instance.
* @typedef {object} PlayerGrandArenaInstance
* @property {string} seasonId Grand arena season id.
* @property {string} eventInstanceId Event instance id.
* @property {string} league Grand arena league (AURODIUM, KYBER, ...).
* @property {number} wins Number of player wins.
* @property {number} losses Number of player losses.
* @property {boolean} eliteDivision In elite division?
* @property {number} seasonPoints Number of season points.
* @property {number} division Player division for this instance.
* @property {number} joinTime Grand arena join time (UTC milliseconds).
* @property {number} endTime Grand arena end time (UTC milliseconds).
* @property {boolean} remove Remove?
* @property {number} rank Player rank in Grand Arena.
*/
/**
* Player equipment.
* @typedef {object} UnitEquipment
* @property {string} equipmentId Equipment id.
* @property {number} slot Equipped slot.
* @property {string} nameKey Equipment name key.
*/
/**
* Unit skill.
* @typedef {object} UnitSkill
* @property {string} id Skill id.
* @property {number} tier Skill tier.
* @property {string} nameKey Skill name key.
* @property {boolean} isZeta Whether this skill is zeta.
* @property {number} tiers Number of skill tiers.
*/
/**
* Primary mod stat.
* @typedef {object} PrimaryModStat
* @property {ModUnitStatEnum} unitStat Mod unit stat.
* @property {number} value Mod unit stat value.
*/
/**
* Secondary mod stat.
* @typedef {object} SecondaryModStat
* @property {ModUnitStatEnum} unitStat Mod unit stat.
* @property {number} value Mod unit stat value.
* @property {number} roll Mod unit stat roll.
*/
/**
* Unit mod.
* @typedef {object} UnitMod
* @property {string} id Unit mod id.
* @property {number} level Unit mod level.
* @property {number} tier Unit mod tier.
* @property {number} slot Unit mod slot.
* @property {number} set Unit mod set.
* @property {number} pips Unit mod pips.
* @property {PrimaryModStat} primaryStat Unit mod primary stat.
* @property {SecondaryModStat[]} secondayStat Unit mod primary stat.
*/
/**
* @typedef {object} CrewSkillReference
* @property {string} skillId Skill id.
* @property {number} requiredTier Required tier for skill.
* @property {number} requiredRarity Required rarity for skill.
* @property {number} requiredRelicTier Required relic tier for skill.
*/
/**
* Crew unit.
* @typedef {object} CrewUnit
* @property {string} unitId Crew unit definition id.
* @property {number} slot Crew unit slot number.
* @property {CrewSkillReference[]} skillReferenceList Crew skill reference list.
* @property {string} skilllessCrewAbilityId Skillless crew ability id.
* @property {number} gp Crew unit GP.
* @property {number} cp Crew unit CP.
*
*/
/**
* Unit relic.
* @typedef {object} UnitRelic
* @property {number} currentTier Current relic tier.
*/
/**
* Unit.
* @typedef {object} Unit
* @property {string} id Unit id.
* @property {string} defId Unit definition id.
* @property {string} nameKey Unit name key.
* @property {number} rarity Unit rarity (number of stars).
* @property {number} level Unit level.
* @property {number} xp Unit XP.
* @property {number} gear Unit gear level.
* @property {UnitEquipment[]} equipped List of equipment used by this unit.
* @property {CombatTypeEnum} combatType Unit combat type (1 for toons, 2 for ships).
* @property {UnitSkill[]} skills List of unit skills.
* @property {UnitMod[]} mods List of unit mods.
* @property {CrewUnit[]} crew List of unit in crew (for ships only)
* @property {number} gp Unit GP.
* @property {object} primaryUnitStat ???.
* @property {UnitRelic} relic Unit relic.
*/
/**
* Player data as returned by the swgoh.help/swgoh/player api.
* @typedef {object} Player
* @property {number} allyCode Player allycode.
* @property {string} id Player id.
* @property {string} name Player name.
* @property {number} level Player level.
* @property {PlayerTitles} titles Player titles.
* @property {string} guildRefId Guild referential id.
* @property {string} guildName Guild name.
* @property {string} guildBannerColor Guild banner color.
* @property {string} guildBannerLogo Guild banner logo.
* @property {string} guildTypeId Guild type id.
* @property {PlayerStat[]} stats Player stats.
* @property {Unit[]} roster List of player units.
* @property {PlayerArena} arena Player arena data.
* @property {number} lastActivity Last activitiy moment (UTC milliseconds).
* @property {number} poUTCOffsetMinutes Timezone offset information relative to UTC.
* @property {PlayerPortraits} portraits Player portraits.
* @property {PlayerGrandArenaInstance[]} grandArena List of player grand arena instance data.
* @property {number} grandArenaLifeTime Lifetime in grand arena (milliseconds).
* @property {number} updated Last update moment (UTC milliseconds).
*/
/**
* Guild raid.
* @typedef {object} GuildRaid
* @property {string} rancor Rancor pit guild raid.
* @property {string} aat HAAT guild raid.
* @property {string} sith_raid HSR guild raid.
*/
/**
* Guild player.
* @typedef {object} GuildPlayer
* @property {string} id Guild player id.
* @property {GuildMemberLevelEnum} guildMemberLevel Guild member level ().
* @property {string} name Guild player name.
* @property {number} level Guild player level.
* @property {number} allyCode Guild player ally code.
* @property {number} gp Guild player GP.
* @property {number} gpChar Guild player char GP.
* @property {number} gpShip Guild player ship GP.
* @property {number} updated Guild player info update moment (UTC milliseconds).
*/
/**
* Guild data.
* @typedef {object} Guild
* @property {string} id Guild id.
* @property {string} name Guild name.
* @property {string} desc Guild description.
* @property {number} members Number of guild members.
* @property {number} status Guild status.
* @property {number} required Guild required member level.
* @property {string} bannerColor Guild banner color.
* @property {string} bannerLogo Guild banner logo.
* @property {string} message Guild message.
* @property {number} gp Guild total gp.
* @property {GuildRaid} raid Guild raids.
* @property {GuildPlayer[]} roster Guild player roster.
* @property {number} updated Guild update momement (UTC milliseconds).
*/
/**
* Guild stats.
* @typedef {object} GuildStats
* @property {number} gpChar Guild total char GP.
* @property {number} gpShip Guild total ship GP.
*/
/**
* Summary stats for characters.
* @typedef {object} CharStats
* @property {number} count Number of roster units for this unit type.
* @property {number} galacticLegendCount Number of Galactic Legends.
* @property {number[]} levels Number of characters per level.
* @property {number[]} rarities Number of characters per star level.
* @property {number[]} gear Number of characters per gear level.
* @property {number} relic5Above Number of gear 13 chars with relic 5 or above.
* @property {number} zetas Number of zetas applied to characters.
*/
/**
* Summary stats for ships.
* @typedef {object} ShipStats
* @property {number} count Number of roster units for this unit type.
* @property {number[]} levels Number of ships per level.
* @property {number[]} rarities Number of ships per star level.
*/
/**
* Summary stats from player roster.
* @typedef {object} PlayerStats
* @property {CharStats} chars Number of ship with specific number of stars.
* @property {ShipStats} ships Number of Galactic Legends on player roster.
*/
/**
* Main API helper class.
* */
class SwgohHelpApi {
/**
* Default constructor.
* @param {string} user swgoh.help login user.
* @param {string} password swgoh.help login password.
* @param {object} logger log4js logger (optional).
* @param {string} language swgoh.help supported localization (defaults to 'eng_us').
*/
constructor(user, password, logger, language = 'eng_us') {
// setup logging
if (logger) {
this.logger = logger;
} else {
const log4js = require("log4js");
const loggerConfig = require('./log4jsconf.json');
log4js.configure(loggerConfig);
this.logger = log4js.getLogger();
}
// authentication
this.user = user;
this.password = password;
this.clientId = 'client_id';
this.clientSecret = 'client_secret';
this.token = null;
// language
this.setLanguage(language);
// base URL for api calls
this.urlBase = 'https://api.swgoh.help';
// load character acronyms from file
const ACRONYMS_FILE = module.path ? module.path + '/resources/toon_acronyms.json' : 'resources/toon_acronyms.json';
this.acronyms = SwgohHelpApi.loadAcronyms(ACRONYMS_FILE);
// add stats calculator module for swgoh.help
this.statsCalculator = require('swgoh-stat-calc');
// init stats calculator with game data
this.statsCalculator.setGameData(SwgohHelpApi.getGameData());
}
/**
* Load all acronyms from JSON file.
* @static
* @param {string} file name.
* @returns {Map<string, string>} Unit acronym map between acronym and unit name.
*/
static loadAcronyms(fileName) {
var tempAcronyms = JSON.parse(fs.readFileSync(fileName, 'utf8'));
// create new acronym map
const acronyms = {
chars: new Map(),
ships: new Map()
};
// add entries to maps
tempAcronyms.chars.forEach(acronym => acronyms.chars.set(acronym.acronym.toLowerCase(), acronym.name));
tempAcronyms.ships.forEach(acronym => acronyms.ships.set(acronym.acronym.toLowerCase(), acronym.name));
return acronyms;
}
/**
* Get game data needed to init stats calculator (from the game data info available at glitch.com or local cache).
* This will be required for statistic calculations on top of data retrieved from swgoh.help.
* @returns {object} Game data for use in the stats calculator.
*/
static getGameData() {
const GAME_DATA_URL = 'https://swgoh-stat-calc.glitch.me/gameData.json';
const GAME_DATA_CACHE = module.path ? module.path + '/cache/gameData.json' : './cache/gameData.json';
const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
var xhr = new XMLHttpRequest();
// open syncronous
xhr.open('GET', GAME_DATA_URL, false);
// setting request headers
xhr.setRequestHeader('Content-Type', 'application/json');
// try to get game data from glitch
xhr.send();
var gameData;
if (xhr.readyState == xhr.DONE && xhr.status == 200) {
// cache game data
fs.writeFileSync(GAME_DATA_CACHE, xhr.responseText, 'UTF-8');
// use glitch.com game data
gameData = JSON.parse(xhr.responseText);
} else {
/// use local cache
gameData = require(GAME_DATA_CACHE);
}
return gameData;
}
/**
* Get the number of achieved zetas for a combat unit.
* @static
* @param {Unit} unitData The unit data.
* @returns {number} The number of active zetas for the unit.
*/
static getZetaCount(unitData) {
return unitData.skills.filter(skill => skill.isZeta && skill.tier == skill.tiers).length;
}
/**
* Get array of zetas for a combat unit.
* @static
* @param {Unit} unitData The unit data.
* @returns {UnitSkill[]} Array of zetas skills for the unit.
*/
static getZetas(unitData) {
return unitData.skills.filter(skill => skill.isZeta && skill.tier == skill.tiers);
}
/**
* Get a specific unit directly from the player unit roster.
* @static
* @param {Player} player The player data object.
* @param {string} searchName The character name to search for (exact match).
* @returns {Unit} The unit from player roster.
*/
static getPlayerUnitFromUnits(player, searchName) {
return player.roster.filter(unit => unit.nameKey != null).find(unit => unit.nameKey.toLowerCase() == searchName.toLowerCase());
}
/**
* Checks if the unit is a GL.
* @static
* @param {Unit} unitData
* @returns {boolean} Whether this unit is a GL.
*/
static isGL(unitData) {
return unitData.skills.filter(skill => skill.id.includes('GALACTICLEGEND')).length > 0;
}
/**
* Get the proper description from the unit type code.
* @static
* @param {SquadUnitTypeEnum} unitType The unit type enum integer.
* @returns {string} The unit type description.
*/
static getSquadUnitTypeString(unitType) {
switch (unitType) {
case SquadUnitTypeEnum.SquadUnitNormal:
return "";
case SquadUnitTypeEnum.SquadUnitLeader:
return "Leader";
case SquadUnitTypeEnum.SquadUnitCapitalShip:
return "Capital Ship";
case SquadUnitTypeEnum.SquadUnitReinforcement:
return "Reinforcement";
default:
return `Unknown unit type: ${unitType}`;
}
}
/**
* Gets the proper description from the modset code.
* @static
* @param {ModSetEnum} modSet The mod set code.
* @returns {string} The mod set description.
*/
static getModSetString(modSet) {
switch (modSet) {
case ModSetEnum.ModSetHealth:
return "Health";
case ModSetEnum.ModSetOffense:
return "Offense";
case ModSetEnum.ModSetDefense:
return "Defense";
case ModSetEnum.ModSetSpeed:
return "Speed";
case ModSetEnum.ModSetCritChance:
return "Critical Chance";
case ModSetEnum.ModSetCritDamage:
return "Critical Damage";
case ModSetEnum.ModSetPotency:
return "Potency";
case ModSetEnum.ModSetTenacity:
return "Tenacity";
default:
return `Unknown mod set: ${modSet}`;
}
}
/**
* Get the proper description from the mod unit stat enum.
* @static
* @param {ModUnitStatEnum} modUnitStat Mod unit stat type enum.
* @returns Mod unit stat description.
*/
static getModUnitStatString(modUnitStat) {
switch (modUnitStat) {
case ModUnitStatEnum.StatHealth:
return "Health";
case ModUnitStatEnum.StatMaxHealthPercentAdditive:
return "% Health";
case ModUnitStatEnum.StatMaxShield:
return "Protection";
case ModUnitStatEnum.StatMaxShieldPercentAdditive:
return "% Protection";
case ModUnitStatEnum.StatOffense:
return "Offense";
case ModUnitStatEnum.StatOffensePercentAdditive:
return "% Offense";
case ModUnitStatEnum.StatDefense:
return "Defense";
case ModUnitStatEnum.StatDefensePercentAdditive:
return "% Defense";
case ModUnitStatEnum.StatCriticalDamage:
return "% Crit Damage";
case ModUnitStatEnum.StatCriticalChancePercentAdditive:
return "% Crit Chance";
case ModUnitStatEnum.StatSpeed:
return "Speed";
case ModUnitStatEnum.StatSpeedPercentAdditive:
return "% Speed";
case ModUnitStatEnum.StatAccuracy:
return "% Potency";
case ModUnitStatEnum.StatResistance:
return "% Tenacity";
case ModUnitStatEnum.StatEvasionNegatePercentAdditive:
return "% Accuracy";
case ModUnitStatEnum.StatCriticalNegateChancePercentAdditive:
return "% Crit Avoidance";
default:
return `Mod unit stat: ${modUnitStat}`;
}
}
/**
* Get the proper description for the mod slot.
* @static
* @param {ModSlotEnum} modSlot The mod slot type.
* @returns The mod slot description.
*/
static getModSlotString(modSlot) {
switch (modSlot) {
case ModSlotEnum.ModSlotSquare:
return "Square";
case ModSlotEnum.ModSlotArrow:
return "Arrow";
case ModSlotEnum.ModSlotDiamond:
return "Diamond";
case ModSlotEnum.ModSlotTriangle:
return "Triangle";
case ModSlotEnum.ModSlotCircle:
return "Circle";
case ModSlotEnum.ModSlotCross:
return "Cross";
default:
return `Unknown mod slot: ${modSlot}`;
}
}
/**
* Get guild stats (GP char and GP ships) from guild data.
* @static
* @param {Guild} guildData The guild data.
* @returns {GuildStats} The guild statistics.
*/
static getGuildStats(guildData) {
return {
gpChar: guildData.roster.map(player => player.gpChar).reduce((a, b) => a + b),
gpShip: guildData.roster.map(player => player.gpShip).reduce((a, b) => a + b)
};
}
/**
* Get guild leader from guild data.
* @static
* @param {Guild} guildData The guild data.
* @returns {GuildPlayer} Guild leader according to guild roster.
*/
static getGuildLeader(guildData) {
return guildData.roster.find(player => player.guildMemberLevel == GuildMemberLevelEnum.GuildMemberLevelLeader);
}
/**
* Get guild officers from guild data.
* @static
* @param {Guild} guild The guild data.
* @returns {GuildPlayer[]} List of guild officers according to guild roster.
*/
static getGuildOfficers(guildData) {
return guildData.roster.filter(player => player.guildMemberLevel == GuildMemberLevelEnum.GuildMemberLevelOfficer);
}
/**
* Gets the desired player stat from player data.
* @static
* @param {Player} playerData Player data object from swgoh.help
* @param {string} statName Desired stat name.
* @returns {string} The stat value (or undefined if not found).
*/
static getPlayerStat(playerData, statName) {
var result;
// find stat in playerdata object by name
const stat = playerData.stats.find(stat => stat.nameKey == statName);
if (stat) result = stat.value;
return result;
}
/**
* Gets summary statistics from player data.
* @static
* @param {Player} player The player data.
* @returns {PlayerStats} The player stats.
*/
static getPlayerStatsSummary(player) {
/** @type {PlayerStats} */
var result = {
chars: {
count: 0,
galacticLegendCount: 0,
levels: new Array(MAX_UNIT_LEVELS).fill(0),
rarities: new Array(MAX_UNIT_STARS).fill(0),
gear: new Array(MAX_CHAR_GEAR_LEVEL).fill(0),
relics: new Array(MAX_CHAR_RELICS).fill(0),
relic5Above: 0,
zetas: 0,
},
ships: {
count: 0,
levels: new Array(MAX_UNIT_LEVELS).fill(0),
rarities: new Array(MAX_UNIT_STARS).fill(0)
}
};
// loop over units
for(var i = 0; i < player.roster.length; i++) {
/** @type {Unit} */
const unit = player.roster[i];
// handle characters and ships
if (unit.combatType == CombatTypeEnum.CombatTypeChar) {
// increase character count
result.chars.count++;
// test for GL
if (SwgohHelpApi.isGL(unit)) {
result.chars.galacticLegendCount++;
}
// increase level count
result.chars.levels[unit.level - 1]++;
// increase rarity count
result.chars.rarities[unit.rarity - 1]++;
// increase gear count
result.chars.gear[unit.gear - 1]++;
// check for relics
if (unit.gear == 13) result.chars.relics[unit.relic.currentTier - 2]++;
// check G13 and relic 5 or above
if (unit.gear == 13 && unit.relic.currentTier >= 7) result.chars.relic5Above++;
// increase zeta count
result.chars.zetas += SwgohHelpApi.getZetaCount(unit);
} else if (unit.combatType == CombatTypeEnum.CombatTypeShip) {
// increase ship count
result.ships.count++;
// increase level count
result.ships.levels[unit.level - 1]++;
// increase rarity count
result.ships.rarities[unit.rarity - 1]++;
}
}
return result;
}
/**
* Sets the API language.
* @param {string} language The desired API language string (e.g.: 'eng_us').
*/
setLanguage(language) {
this.language = language;
}
/**
* Gets the API language.
* @returns {string} The current API language string.
*/
getLanguage(language) {
return this.language;
}
/**
* Fetch data using XMLHttpRequest with auto retry for login.
* @param {string} method String with desired method (GET or POST).
* @param {string} URL Endpoint URL.
* @param {JSON} The JSON payload to use.
* @returns {XMLHttpRequest} The XMLHttpRequest obejct.
*/
fetchRetry(method, url, payload) {
this.logger.debug(`fetchRetry@swgohhelp-api: ${method}(t)ing data from "${url}" ${payload ? 'with payload ' + JSON.stringify(payload) : ''}`);
// test if token already available
if (!this.token) {
this.signIn();
}
const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
var xhr = new XMLHttpRequest();
// open syncronous
xhr.open(method, url, false);
// setting request headers
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', `Bearer ${this.token}`);
// get JSON string from payload
if (payload) {
xhr.send(JSON.stringify(payload));
} else {
xhr.send();
}
if (xhr.readyState == xhr.DONE) {
if (xhr.status == 503) {
// bearer token expired?
this.logger.error(`fetchRetry@swgohhelp-api: error 503 (service not available), bearer token expired?`);
// force re-login
this.token = null;
// retry send
return this.fetchRetry(method, url, payload);
} else {
return xhr;
}
} else {
this.logger.error(`fetchRetry@swgohhelp-api: error fetching data (ready state = ${xhr.readyState})`);
return xhr;
}
}
/**
* Build full units cache from swgoh.help.
* @returns {Map<string, UnitData}} Map between unit base id and unit data.
*/
fetchUnits() {
this.logger.debug("fetchUnits@swgohhelp-api: fetching units from swgoh.help");
const payload = {
"collection": CollectionsEnum.CollectionUnitsList,
"language": this.language,
"match" : {
"rarity": 7,
"obtainable" : true,
"obtainableTime": 0
}
};
// get units list
const tempUnits = this.getData(payload);
var units;
if (tempUnits) {
units = new Map();
// loop over units to create map
tempUnits.forEach(unit => units.set(unit.baseId, unit));
this.logger.debug(`fetchUnits@swgohhelp-api: API loaded units ok (total = ${units.size})`);
}
return units;
}
/**
* Build local cache for game definitions.
* @private
*/
buildCache() {
// set TTL to one hour
const MAX_TTL_SECONDS = 3600;
const now = new Date();
if (!this.cache) {
if (this.logger) this.logger.debug('buildCache@swgohhelp-api: No cache found, fetching new cache data');
// build cache object
this.cache = {
units: this.fetchUnits(),
updated: new Date()
};
} else if (now.getTime() - this.cache.updated.getTime() > MAX_TTL_SECONDS * 1000) {
if (this.logger) this.logger.debug('buildCache@swgohhelp-api: Cache TTL exceeded, rebuilding cache');
// ttl exceeded, let's rebuild cache
this.cache = undefined;
this.buildCache();
}
}
/**
* Gets a unit definition from the local cache.
* @param {string} defId The unit definition id.
* @returns {Unit} Unit definition from the local cache.
*/
getUnit(defId) {
this.buildCache();
return this.cache.units.get(defId);
}
/**
* Search for a unit from the unit cache (uses acronyms, full name or partial name matching).
* @param {string} unitName The desired unit name.
* @returns {UnitData} The unit data structure.
*/
findUnit(unitName) {
var result;
this.buildCache();
this.logger.debug(`findUnit@swgohhelp-api: data request for unit "${unitName}"`);
var searchName = unitName.toLowerCase();
// test for acronym
if (this.acronyms.chars.has(searchName)) {
// set new search name to acronym mapping
searchName = this.acronyms.chars.get(searchName).toLowerCase();
this.logger.debug(`findUnit@swgohhelp-api: mapped "${unitName}" to character "${searchName}"`);
} else if (this.acronyms.ships.has(searchName)) {
// set new search name to acronym mapping
searchName = this.acronyms.ships.get(searchName).toLowerCase();
this.logger.debug(`findUnit@swgohhelp-api: mapped "${unitName}" to ship "${searchName}"`);
}
// search for full unit name
result = Array.from(this.cache.units.values()).find(unit => unit.nameKey.toLowerCase() == searchName);