-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathenums.py
More file actions
611 lines (496 loc) · 15.3 KB
/
Copy pathenums.py
File metadata and controls
611 lines (496 loc) · 15.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
"""
MIT License
Copyright (c) 2019-present Luc1412
Portions of this code are Copyright (c) 2015-present Rapptz
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.
"""
from __future__ import annotations
import types
from collections.abc import Iterator, Mapping
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar
from typing_extensions import Self
__all__: tuple[str, ...] = (
'KeyFormat',
'GameLanguage',
'MatchMethod',
'CosmeticCategory',
'CosmeticRarity',
'CosmeticType',
'AccountType',
'TimeWindow',
'StatsImageType',
'CosmeticCompatibleMode',
'BannerIntensity',
'CustomGender',
'ProductTag',
)
E = TypeVar('E', bound='Enum')
OldValue = NewValue = Any
def _create_value_cls(name: str, comparable: bool) -> type[NewValue]:
# All the type ignores here are due to the type checker being unable to recognise
# Runtime type creation without exploding.
class EnumValue:
__slots__ = ("name", "value")
def __init__(self, name: str, value: EnumValue) -> None:
self.name: str = name
self.value: EnumValue = value
def __repr__(self) -> str:
return f'<{name}.{self.name}: {self.value!r}>'
def __str__(self) -> str:
return f'{name}.{self.name}'
if comparable:
def __le__(self, other: object) -> bool:
return isinstance(other, self.__class__) and self.value <= other.value
def __ge__(self, other: object) -> bool:
return isinstance(other, self.__class__) and self.value >= other.value
def __lt__(self, other: object) -> bool:
return isinstance(other, self.__class__) and self.value < other.value
def __gt__(self, other: object) -> bool:
return isinstance(other, self.__class__) and self.value > other.value
EnumValue.__name__ = '_EnumValue_' + name
return EnumValue
def _is_descriptor(obj: type[object]) -> bool:
return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')
class EnumMeta(type):
if TYPE_CHECKING:
_enum_member_names_: ClassVar[list[str]]
_enum_member_map_: ClassVar[dict[str, NewValue]]
_enum_value_map_: ClassVar[dict[OldValue, NewValue]]
_enum_value_cls_: ClassVar[type[NewValue]]
def __new__(
cls,
name: str,
bases: tuple[type, ...],
attrs: dict[str, Any],
*,
comparable: bool = False,
) -> EnumMeta:
value_mapping: dict[OldValue, NewValue] = {}
member_mapping: dict[str, NewValue] = {}
member_names: list[str] = []
value_cls = _create_value_cls(name, comparable)
for key, value in list(attrs.items()):
is_descriptor = _is_descriptor(value)
if key[0] == '_' and not is_descriptor:
continue
# Special case classmethod to just pass through
if isinstance(value, classmethod):
continue
if is_descriptor:
setattr(value_cls, key, value)
del attrs[key]
continue
try:
new_value = value_mapping[value]
except KeyError:
new_value = value_cls(name=key, value=value)
value_mapping[value] = new_value
member_names.append(key)
member_mapping[key] = new_value
attrs[key] = new_value
attrs['_enum_value_map_'] = value_mapping
attrs['_enum_member_map_'] = member_mapping
attrs['_enum_member_names_'] = member_names
attrs['_enum_value_cls_'] = value_cls
actual_cls = super().__new__(cls, name, bases, attrs)
value_cls._actual_enum_cls_ = actual_cls
return actual_cls
def __iter__(cls) -> Iterator[Any]:
return (cls._enum_member_map_[name] for name in cls._enum_member_names_)
def __reversed__(cls) -> Iterator[Any]:
return (cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_))
def __len__(cls) -> int:
return len(cls._enum_member_names_)
def __repr__(cls) -> str:
return f'<enum {cls.__name__}>'
@property
def __members__(cls) -> Mapping[str, Any]:
return types.MappingProxyType(cls._enum_member_map_)
def __call__(cls, value: str) -> Any:
try:
return cls._enum_value_map_[value]
except (KeyError, TypeError):
raise ValueError(f'{value!r} is not a valid {cls.__name__}')
def __getitem__(cls, key: str) -> Any:
return cls._enum_member_map_[key]
def __setattr__(cls, name: str, value: Any) -> None:
raise TypeError('Enums are immutable.')
def __delattr__(cls, attr: str) -> None:
raise TypeError('Enums are immutable')
def __instancecheck__(self, instance: Any) -> bool:
# isinstance(x, Y)
# -> __instancecheck__(Y, x)
try:
return instance._actual_enum_cls_ is self
except AttributeError:
return False
if TYPE_CHECKING:
from enum import Enum
else:
class Enum(metaclass=EnumMeta):
@classmethod
def try_value(cls, value: Any) -> Any:
try:
return cls._enum_value_map_[value]
except (KeyError, TypeError):
return value
class KeyFormat(Enum):
"""Represents a return format type for the AES endpoint.
Attributes
----------
HEX
Return the AES keys in hexadecimal format.
BASE64
Return the AES keys in base64 format.
"""
HEX = 'hex'
BASE64 = 'base64'
class GameLanguage(Enum):
"""Represents a language that Fortnite supports. This can be
used to change the return language of many API calls.
Attributes
----------
ARABIC
Arabic language.
GERMAN
German language.
ENGLISH
English language.
SPANISH
Spanish language.
SPANISH_LATIN
Latin Spanish language.
FRENCH
French language.
ITALIAN
Italian language.
JAPANESE
Japanese language.
KOREAN
Korean language.
POLISH
Polish language.
PORTUGUESE_BRASIL
Portuguese (Brasil) language.
RUSSIAN
Russian language.
TURKISH
Turkish language.
CHINESE_SIMPLIFIED
Simplified Chinese language.
CHINESE_TRADITIONAL
Traditional Chinese language.
"""
ARABIC = 'ar'
GERMAN = 'de'
ENGLISH = 'en'
SPANISH = 'es'
SPANISH_LATIN = 'es-419'
FRENCH = 'fr'
ITALIAN = 'it'
JAPANESE = 'ja'
KOREAN = 'ko'
POLISH = 'pl'
PORTUGUESE_BRASIL = 'pt-BR'
RUSSIAN = 'ru'
TURKISH = 'tr'
CHINESE_SIMPLIFIED = 'zh-CN'
CHINESE_TRADITIONAL = 'zh-Hant'
class MatchMethod(Enum):
"""Represents a string matching method for some search methods in the API.
Attributes
----------
FULL
Match the full string.
CONTAINS
Match if the string contains the search string.
STARTS
Match if the string starts with the search string.
ENDS
Match if the string ends with the search string.
"""
FULL = 'full'
CONTAINS = 'contains'
STARTS = 'starts'
ENDS = 'ends'
class CosmeticCategory(Enum):
"""Represents the internal names for the types of a cosmetics in Fortnite.
Attributes
----------
BR
Type of a :class:`fortnite_api.CosmeticBr` cosmetic.
TRACKS
Type of a :class:`fortnite_api.CosmeticTrack` cosmetic.
INSTRUMENTS
Type of a :class:`fortnite_api.CosmeticInstrument` cosmetic.
CARS
Type of a :class:`fortnite_api.CosmeticCar` cosmetic.
LEGO
Type of a :class:`fortnite_api.VariantLego` cosmetic variant.
LEGO_KITS
Type of a :class:`fortnite_api.CosmeticLegoKit` cosmetic.
BEANS
Type of a :class:`fortnite_api.VariantBean` cosmetic variant.
"""
BR = "br"
TRACKS = "tracks"
INSTRUMENTS = "instruments"
CARS = "cars"
LEGO = "lego"
LEGO_KITS = "legokits"
BEANS = "beans"
class CosmeticRarity(Enum):
"""Represents a rarity of a :class:`~fortnite_api.Cosmetic` object.
Attributes
----------
FROZEN
LAVA
LEGENDARY
GAMING_LEGENDS
DARK
STARWARS
MARVEL
DC
ICON_SERIES
SHADOW
SLURP
EPIC
LAMBORGHINI
RARE
UNCOMMON
COMMON
"""
FROZEN = 'frozen'
LAVA = 'lava'
LEGENDARY = 'legendary'
GAMING_LEGENDS = 'gaminglegends'
DARK = 'dark'
STARWARS = 'starwars'
MARVEL = 'marvel'
DC = 'dc'
ICON_SERIES = 'icon'
SHADOW = 'shadow'
SLURP = 'slurp'
EPIC = 'epic'
LAMBORGHINI = 'lamborghini'
RARE = 'rare'
UNCOMMON = 'uncommon'
COMMON = 'common'
MYTHIC = 'mythic'
class CosmeticType(Enum):
"""Represents a type of a :class:`fortnite_api.CosmeticBr` cosmetic.
Attributes
----------
OUTFIT
BACKPACK
PET
PET_CARRIER
PICKAXE
SHOES
GLIDER
CONTRAIL
AURA
EMOTE
EMOJI
SPRAY
TOY
SIDEKICK
WRAP
BANNER
MUSIC
LOADING_SCREEN
GUITAR
BASS
DRUMS
MICROPHONE
KEYTAR
CAR_BODY
DECAL
WHEELS
TRAIL
BOOST
JAM_TRACK
LEGO_BUILD
LEGO_DECOR_BUNDLE
SHOUT
"""
OUTFIT = 'outfit'
BACKPACK = 'backpack'
PET = 'pet'
PET_CARRIER = 'petcarrier'
PICKAXE = 'pickaxe'
GLIDER = 'glider'
SHOES = 'shoe'
CONTRAIL = 'contrail'
AURA = 'aura'
EMOTE = 'emote'
EMOJI = 'emoji'
SPRAY = 'spray'
TOY = 'toy'
SIDEKICK = 'sidekick'
WRAP = 'wrap'
BANNER = 'banner'
MUSIC = 'music'
LOADING_SCREEN = 'loadingscreen'
GUITAR = 'guitar'
BASS = 'bass'
DRUMS = 'drum'
MICROPHONE = 'mic'
KEYTAR = 'keyboard'
CAR_BODY = 'body'
DECAL = 'skin'
WHEELS = 'wheel'
TRAIL = 'drifttrail'
BOOST = 'booster'
JAM_TRACK = 'track'
LEGO_BUILD = 'legoset'
LEGO_DECOR_BUNDLE = 'legoprop'
SHOUT = 'shout'
class AccountType(Enum):
"""Represents the type of a :class:`fortnite_api.account.Account`.
Attributes
----------
EPIC
Epic Games account.
PSN
PlayStation Network account.
XBL
Xbox Live account.
"""
EPIC = 'epic'
PSN = 'psn'
XBL = 'xbl'
class TimeWindow(Enum):
"""Represents a time window for statistics in the API.
Attributes
----------
SEASON
Denotes that the results should only be for the current season.
LIFETIME
Denotes that the results should be for the lifetime of an account.
"""
SEASON = 'season'
LIFETIME = 'lifetime'
class StatsImageType(Enum):
"""Represents the type of image that should be returned from the stats image endpoint.
Attributes
----------
ALL
Return an image that has statistics for all input types.
KEYBOARD_MOUSE
Return an image that has statistics for only keyboard and mouse input types.
GAMEPAD
Return an image that has statistics for only gamepad (controller) input types.
TOUCH
Return an image that has statistics for only touch input types.
NONE
No image should be returned.
"""
ALL = 'all'
KEYBOARD_MOUSE = 'keyboardMouse'
GAMEPAD = 'gamepad'
TOUCH = 'touch'
NONE = 'none'
class CosmeticCompatibleMode(Enum):
"""A class that represents the compatibility of a cosmetic :class:`fortnite_api.MaterialInstance` with other modes.
Attributes
----------
BATTLE_ROYALE
The material instance is compatible with Battle Royale.
LEGO
The material instance is compatible with LEGO.
ROCKET_RACING
The material instance is compatible with Rocket Racing.
FESTIVAL
The material instance is compatible with Festival.
ALL
The material instance is compatible with all modes.
"""
BATTLE_ROYALE = 'battleroyale'
LEGO = 'juno'
ROCKET_RACING = 'delmar'
FESTIVAL = 'sparks'
ALL = 'max'
@classmethod
def _from_str(cls: type[Self], string: str) -> Self:
# The Epic Games API uses both "CosmeticCompatibleMode" and "CosmeticCompatibleModeLegacy" enums
# with the same values, so we need to handle both.
# To easily handle this, we'll remove the "ECosmeticCompatibleMode::" or "ECosmeticCompatibleModeLegacy::" prefix.
# and then convert it to the enum.
trimmed = string.split('::')[-1]
return try_enum(cls, trimmed)
class BannerIntensity(Enum):
"""Denotes the intensity of a :class:`fortnite_api.ShopEntryBanner`.
Attributes
----------
LOW
Low intensity.
HIGH
High intensity.
"""
LOW = 'Low'
HIGH = 'High'
class CustomGender(Enum):
"""Denotes the gender of a character in Fortnite.
At the moment, this is only used on the :class:`fortnite_api.VariantBean` class.
Attributes
----------
FEMALE
A female character.
MALE
A male character.
"""
FEMALE = 'EFortCustomGender::Female'
MALE = 'EFortCustomGender::Male'
class ProductTag(Enum):
"""A class that represents the tag of a product.
Attributes
----------
BATTLE_ROYALE
The product is for Battle Royale.
LEGO
The product is for LEGO.
ROCKET_RACING
The product is for Rocket Racing.
FESTIVAL
The product is for Festival.
ALL
The product is for all modes.
"""
BATTLE_ROYALE = 'br'
LEGO = 'juno'
ROCKET_RACING = 'delmar'
FESTIVAL = 'sparks'
ALL = 'max'
@classmethod
def _from_str(cls: type[Self], string: str) -> Self:
# The Epic Games API "Product" enums contains both lower case and capitalized values, so we need to handle both.
# To easily handle this, we'll remove the "Product." prefix and convert it to lowercase.
trimmed = string.split('.')[-1]
return try_enum(cls, trimmed.lower())
def create_unknown_value(cls: type[E], val: Any) -> NewValue:
value_cls = cls._enum_value_cls_ # type: ignore # This is narrowed below
name = f'UNKNOWN_{val}'
return value_cls(name=name, value=val) # type: ignore
def try_enum(cls: type[E], val: Any) -> E:
"""A function that tries to turn the value into enum ``cls``.
If it fails it returns a proxy invalid value instead.
"""
try:
return cls._enum_value_map_[val] # type: ignore # All errors are caught below
except (KeyError, TypeError, AttributeError):
return create_unknown_value(cls, val)