Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions src/swgoh_comlink/helpers/_guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,20 @@

from ..exceptions import SwgohComlinkValueError
from ._utils import _client_kind, get_function_name, sanitize_allycode
from ._wire import as_int
from ._wire import as_int, parse_enum

if TYPE_CHECKING:
from swgoh_comlink import SwgohComlink, SwgohComlinkAsync

# memberLevel (GuildMemberLevel), looked up as text: an integer (enums=False) or its enum name (enums=True)
# GuildMemberLevel members and their roles. memberLevel arrives as a number (enums=False) or a member name
# (enums=True), bare (GUILD_MEMBER) or type-prefixed (GUILDMEMBERLEVEL_GUILDMEMBER); parse_enum reads all three.
_MEMBER_ROLES: dict[str, tuple[int, str]] = {
"1": (1, "Pending"),
"2": (2, "Member"),
"3": (3, "Officer"),
"4": (4, "Leader"),
"GUILD_PENDING": (1, "Pending"),
"GUILD_MEMBER": (2, "Member"),
"GUILD_OFFICER": (3, "Officer"),
"GUILD_LEADER": (4, "Leader"),
}
_MEMBER_LEVELS = {name: level for name, (level, _) in _MEMBER_ROLES.items()}


class TerritoryBattleResult(TypedDict):
Expand Down Expand Up @@ -210,7 +208,8 @@ def get_guild_activity(guild: dict[str, Any]) -> GuildActivity:
The payload's numbers are read whether they arrive as integers or as strings. Member join times
(``guildJoinTime``) are epoch **seconds**, while ``lastActivityTime`` is epoch milliseconds; both are
returned as datetimes, and a missing or zero value as ``None``. ``memberLevel`` is read as a number
or as its ``GuildMemberLevel`` enum name (``enums=True``).
or as its ``GuildMemberLevel`` enum name (``enums=True``), bare (``GUILD_MEMBER``) or type-prefixed
(``GUILDMEMBERLEVEL_GUILDMEMBER``).

Args:
guild: The response from ``SwgohComlink.get_guild(..., include_recent_guild_activity_info=True)``.
Expand Down Expand Up @@ -272,7 +271,8 @@ def get_guild_activity(guild: dict[str, Any]) -> GuildActivity:

member_activity: list[GuildMemberActivity] = []
for member in members:
level, role = _MEMBER_ROLES.get(str(member.get("memberLevel")), (None, None))
level_name = parse_enum(member.get("memberLevel"), _MEMBER_LEVELS, enum_name="GuildMemberLevel")
level, role = _MEMBER_ROLES.get(level_name or "", (None, None))
player_id = member.get("playerId", "")
member_activity.append(
{
Expand Down
38 changes: 25 additions & 13 deletions src/swgoh_comlink/helpers/_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from ..exceptions import SwgohComlinkValueError
from ._localization import _localize
from ._stat_data import CURRENCY_NAMES, CURRENCY_TYPES, ITEM_TYPES, MOD_SET_IDS, MOD_SLOTS, UNIT_RARITY_NAMES
from ._wire import parse_enum

_ITEM_TYPE_NUMBERS = {name: number for number, name in ITEM_TYPES.items()}
_UNIT = _ITEM_TYPE_NUMBERS["UNIT"]
Expand Down Expand Up @@ -39,8 +40,9 @@
# A unit shard is a material whose id is the unit's baseId behind this prefix.
_SHARD_PREFIX = "unitshard_"

# Enum member names that game data fetched with enums=True carries in place of the numbers. StatModSlot
# numbers start at 2: STATMOD_SLOT_01 is the Square (see MOD_SLOTS).
# Enum member names that game data fetched with enums=True carries in place of the numbers, bare
# (STATMOD_SLOT_01) or type-prefixed (STATMODSLOT_STATMODSLOT01). StatModSlot numbers start at 2:
# STATMOD_SLOT_01 is the Square (see MOD_SLOTS).
_MOD_SLOT_ENUMS = {f"STATMOD_SLOT_{n:02d}": n + 1 for n in range(1, 7)}
_MOD_TIER_ENUMS = {f"STATMOD_TIER_{n:02d}": n for n in range(1, 6)}
# Rarity also has NO_STAR (8), which UNIT_RARITY_NAMES leaves out.
Expand Down Expand Up @@ -102,17 +104,22 @@ class NamedReward(TypedDict):
paid; otherwise ``None``."""


def _as_int(value: Any, enum_names: Mapping[str, int] | None = None) -> int | None:
"""Read an int field that may hold a number, a numeric string or (with ``enums=True``) an enum name."""
def _as_int(value: Any, enum_names: Mapping[str, int] | None = None, enum_name: str | None = None) -> int | None:
"""Read an int field that may hold a number, a numeric string or (with ``enums=True``) an enum name.

A name is matched by :func:`parse_enum`, so the type-prefixed spelling some servers send
(``RARITY_SEVENSTAR``) reads like the bare one (``SEVEN_STAR``). *enum_name* is the enum's type name,
which that prefix must match.
"""
if isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, str):
if value.lstrip("-").isdigit():
return int(value)
if enum_names is not None:
return enum_names.get(value)
if enum_names is not None and (name := parse_enum(value, enum_names, enum_name=enum_name)) is not None:
return enum_names[name]
return None


Expand Down Expand Up @@ -295,14 +302,14 @@ def get_mod_catalog(
if not isinstance(mod, dict) or not mod.get("id"):
continue
set_id = str(mod.get("setId", ""))
slot = _as_int(mod.get("slot"), _MOD_SLOT_ENUMS) or 0
slot = _as_int(mod.get("slot"), _MOD_SLOT_ENUMS, "StatModSlot") or 0
definitions[mod["id"]] = {
"definition_id": mod["id"],
"set_id": set_id,
"set_name": set_names.get(set_id) or MOD_SET_IDS.get(set_id, set_id),
"slot": slot,
"slot_name": MOD_SLOTS.get(str(slot), ""),
"rarity": _as_int(mod.get("rarity"), _RARITY_ENUMS) or 0,
"rarity": _as_int(mod.get("rarity"), _RARITY_ENUMS, "Rarity") or 0,
}
return {"sets": sets, "definitions": definitions}

Expand Down Expand Up @@ -434,13 +441,18 @@ def _mystery_mod_name(self, item_id: str) -> str | None:
mod = self._mystery_mods.get(item_id)
if mod is None:
return None
pips = _range(_as_int(mod.get("minRarity"), _RARITY_ENUMS), _as_int(mod.get("maxRarity"), _RARITY_ENUMS))
pips = _range(
_as_int(mod.get("minRarity"), _RARITY_ENUMS, "Rarity"),
_as_int(mod.get("maxRarity"), _RARITY_ENUMS, "Rarity"),
)
tier = _range(
_as_int(mod.get("minTier"), _MOD_TIER_ENUMS),
_as_int(mod.get("maxTier"), _MOD_TIER_ENUMS),
_as_int(mod.get("minTier"), _MOD_TIER_ENUMS, "StatModTier"),
_as_int(mod.get("maxTier"), _MOD_TIER_ENUMS, "StatModTier"),
_MOD_TIER_LETTERS,
)
slots = [MOD_SLOTS.get(str(_as_int(slot, _MOD_SLOT_ENUMS)), "?") for slot in mod.get("slot") or []]
slots = [
MOD_SLOTS.get(str(_as_int(slot, _MOD_SLOT_ENUMS, "StatModSlot")), "?") for slot in mod.get("slot") or []
]
slot = "any-slot" if len(set(slots)) >= len(MOD_SLOTS) else " or ".join(slots)
set_id = str(mod.get("setId", ""))
set_name = self._mod_sets.get(set_id) or MOD_SET_IDS.get(set_id, "")
Expand Down Expand Up @@ -469,7 +481,7 @@ def item_type_number(self, item_type: Any) -> int | None:

Returns ``None`` for a member name this instance's table does not list.
"""
return _as_int(item_type, self._item_type_numbers)
return _as_int(item_type, self._item_type_numbers, "ItemType")

def item_type_name(self, number: int) -> str | None:
"""Return the ``ItemType`` member name for a number, or ``None`` when the table does not list it."""
Expand Down
3 changes: 2 additions & 1 deletion src/swgoh_comlink/helpers/_territory_battle.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
# Over a third of the game's categories key their name as the literal 'PLACEHOLDER'; none is a real name.
_PLACEHOLDER = "PLACEHOLDER"
_SCORE_ROW = "GALACTIC_SCORE"
# The dump of the game data spells the flag with an underscore; Comlink sends it without.
# The game data dump and current servers spell the flag with an underscore; some older servers sent it
# without.
_VERSION_3_KEYS = ("territoryBattleVersion3", "territoryBattleVersion_3")
# int32 max: the game's "no limit" for maxUnitCountPerPlayer and maxAttemptsAllowed.
_UNLIMITED = 2**31 - 1
Expand Down
24 changes: 19 additions & 5 deletions tests/unit/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,10 @@ def test_members(self):
("GUILD_MEMBER", (2, "Member")),
("GUILD_OFFICER", (3, "Officer")),
("GUILD_LEADER", (4, "Leader")),
# The type-prefixed spelling some servers send; another enum's prefix is not read.
("GUILDMEMBERLEVEL_GUILDMEMBER", (2, "Member")),
("GUILDMEMBERLEVEL_GUILDLEADER", (4, "Leader")),
("RARITY_GUILDMEMBER", (None, None)),
(0, (None, None)),
(None, (None, None)),
([4], (None, None)),
Expand Down Expand Up @@ -1806,6 +1810,9 @@ def test_wire_docstring_examples():
# Game data fetched with enums=True carries enum names in place of the numbers.
{"id": "enum", "slot": ["STATMOD_SLOT_02"], "setId": "4", "minRarity": "SIX_STAR", "maxRarity": "SIX_STAR",
"minTier": "STATMOD_TIER_05", "maxTier": "STATMOD_TIER_05"},
# Some servers spell them prefixed with their type and without inner underscores.
{"id": "enum_prefixed", "slot": ["STATMODSLOT_STATMODSLOT02"], "setId": "4", "minRarity": "RARITY_SIXSTAR",
"maxRarity": "RARITY_SIXSTAR", "minTier": "STATMODTIER_STATMODTIER05", "maxTier": "STATMODTIER_STATMODTIER05"},
# Unreadable rarities are shown as "?".
{"id": "unreadable", "slot": [2], "setId": "4", "minRarity": True, "maxRarity": None, "minTier": 1,
"maxTier": 1},
Expand Down Expand Up @@ -1863,6 +1870,8 @@ class TestGetModCatalog:
_STAT_MODS: list[dict[str, Any]] = [
{"id": "451", "setId": "4", "slot": 2, "rarity": 5},
{"id": "137", "setId": "3", "slot": "STATMOD_SLOT_06", "rarity": "SEVEN_STAR"},
{"id": "138", "setId": "3", "slot": "STATMODSLOT_STATMODSLOT06", "rarity": "RARITY_SEVENSTAR"},
{"id": "139", "setId": "3", "slot": "RARITY_STATMODSLOT06", "rarity": "STATMODSLOT_SEVENSTAR"},
{"id": "999", "setId": "9", "slot": 4, "rarity": 1},
]

Expand All @@ -1882,6 +1891,9 @@ def test_sets_and_definitions(self):
# Enum names (enums=True) are read as their numbers.
assert catalog["definitions"]["137"]["slot"] == 7
assert catalog["definitions"]["137"]["rarity"] == 7
# So are the type-prefixed spellings, but only under their own type's prefix.
assert (catalog["definitions"]["138"]["slot"], catalog["definitions"]["138"]["rarity"]) == (7, 7)
assert (catalog["definitions"]["139"]["slot"], catalog["definitions"]["139"]["rarity"]) == (0, 0)
# A set statModSet does not list keeps its id as its name.
assert catalog["definitions"]["999"]["set_name"] == "9"

Expand Down Expand Up @@ -1924,6 +1936,8 @@ class TestItemNames:
("MYSTERY_STAT_MOD", "11112", "1-2-dot Speed any-slot mod (E-D)"),
(16, "two", "5-dot Speed Square or Arrow mod (E)"),
(16, "enum", "6-dot Speed Arrow mod (A)"),
(16, "enum_prefixed", "6-dot Speed Arrow mod (A)"),
("ITEMTYPE_MYSTERYSTATMOD", "enum_prefixed", "6-dot Speed Arrow mod (A)"),
(16, "unreadable", "?-dot Speed Square mod (E)"),
],
)
Expand Down Expand Up @@ -2178,8 +2192,8 @@ def _tb_platoon(platoon_id: str, points: str, reward_type: Any = 1) -> dict[str,
},
{
"id": "t05D",
# Comlink's spelling; the on-disk dump of the game data spells it territoryBattleVersion_3.
"territoryBattleVersion3": True,
# The current spelling; some older servers sent territoryBattleVersion3.
"territoryBattleVersion_3": True,
"conflictZoneDefinition": [
{
"zoneDefinition": _tb_zone("tb3_phase01_conflict01", name_key="PLANET_CORUSCANT"),
Expand Down Expand Up @@ -2448,12 +2462,12 @@ def test_hidden_reasons(self):
# Not a version 3 map, so a special mission in the strike array is a normal mission.
assert missions["geo_phase01_conflict01_strike01"]["hidden_reason"] is None

def test_dump_spelling_of_the_version_3_flag(self):
def test_legacy_spelling_of_the_version_3_flag(self):

definition = {k: v for k, v in _TB_DEFS[1].items() if k != "territoryBattleVersion3"}
definition = {k: v for k, v in _TB_DEFS[1].items() if k != "territoryBattleVersion_3"}
missions = get_tb_mission_requirements([definition], _TB_CAMPAIGNS, _TB_CATEGORIES)
assert sum(m["hidden_reason"] == "special" for m in missions) == 0
definition["territoryBattleVersion_3"] = True
definition["territoryBattleVersion3"] = True
missions = get_tb_mission_requirements([definition], _TB_CAMPAIGNS, _TB_CATEGORIES)
assert sum(m["hidden_reason"] == "special" for m in missions) == 1

Expand Down
Loading