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
2 changes: 2 additions & 0 deletions api/src/sidequest_api/domain/characters/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ def _reputations(reputations: CharacterReputations | None) -> list[CharacterRepu
standing=reputation.standing.name,
value=reputation.standing.value,
max=reputation.standing.max,
faction_id=reputation.faction.id,
tier=reputation.standing.tier,
)
for reputation in ordered
]
Expand Down
78 changes: 66 additions & 12 deletions api/src/sidequest_api/domain/epgp/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import secrets
import string
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any

from litestar.exceptions import HTTPException, NotFoundException, PermissionDeniedException, ValidationException
from litestar.status_codes import HTTP_409_CONFLICT, HTTP_429_TOO_MANY_REQUESTS
Expand Down Expand Up @@ -152,6 +152,8 @@
GameImportOfficerRecruit,
GameImportPayload,
GameImportPrice,
GameImportProfession,
GameImportReputation,
GameImportSheet,
GameImportSignup,
GameImportStandingsRow,
Expand Down Expand Up @@ -240,6 +242,54 @@ def decayed_amount(amount: int, at: datetime, now: datetime) -> float:
return amount * ((1 - DECAY_PERCENT / 100) ** resets_since(at, now))


def _import_professions(sheet: dict[str, Any] | None) -> list[GameImportProfession]:
"""A character's professions from its stored Battle.net sheet, for the addon's item-level-style fallback."""
if sheet is None:
return []
return [
GameImportProfession(name=profession["name"], skill=profession["skill"], max_skill=profession["max_skill"])
for profession in sheet.get("professions", [])
]


def _import_reputations(sheet: dict[str, Any] | None) -> list[GameImportReputation]:
"""A character's tracked reputations from its stored Battle.net sheet.

Lines stored before ``faction_id``/``tier`` were added (refreshed within 6h) are skipped.
"""
if sheet is None:
return []
reputations = []
for reputation in sheet.get("reputations", []):
faction_id = reputation.get("faction_id")
tier = reputation.get("tier")
if faction_id is None or tier is None:
continue
reputations.append(
GameImportReputation(
faction_id=faction_id, standing=tier + 1, value=reputation["value"], max=reputation["max"]
)
)
return reputations


def _game_import_character(
character: WowCharacter, level: int, battlenet: tuple[int | None, str | None, dict[str, Any] | None] | None
) -> GameImportCharacter:
"""One character's game-import row: live roster data plus its stored Battle.net fallback fields."""
item_level, spec, sheet = battlenet if battlenet is not None else (None, None, None)
return GameImportCharacter(
name=character.key,
wow_class=WowClass(character.wow_class) if character.wow_class else None,
level=level,
is_main=character.is_main,
item_level=item_level,
spec=spec,
professions=_import_professions(sheet),
reputations=_import_reputations(sheet),
)


_character_key = character_key


Expand Down Expand Up @@ -1974,12 +2024,18 @@ async def _build_members_news_sheets_crafters(
for character in characters:
if character.member_id is not None:
chars_by_member.setdefault(character.member_id, []).append(character)
battlenet_item_levels = {
slug: item_level
for slug, item_level in (
await self._session.execute(select(BattlenetCharacter.slug, BattlenetCharacter.item_level))
battlenet_by_slug = {
slug: (item_level, spec, sheet)
for slug, item_level, spec, sheet in (
await self._session.execute(
select(
BattlenetCharacter.slug,
BattlenetCharacter.item_level,
BattlenetCharacter.spec,
BattlenetCharacter.sheet,
)
)
).all()
if item_level is not None
}
snapshots = {
row.character_id: row for row in (await self._session.execute(select(GuildRosterSnapshot))).scalars().all()
Expand Down Expand Up @@ -2034,12 +2090,10 @@ async def _build_members_news_sheets_crafters(
events_attended=events_attended,
badges=badges_by_member.get(member_id, []),
characters=[
GameImportCharacter(
name=character.key,
wow_class=WowClass(character.wow_class) if character.wow_class else None,
level=snapshots[character.id].level if character.id in snapshots else 0,
is_main=character.is_main,
item_level=battlenet_item_levels.get(character.slug or ""),
_game_import_character(
character,
snapshots[character.id].level if character.id in snapshots else 0,
battlenet_by_slug.get(character.slug or ""),
)
for character in member_chars
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""

from datetime import datetime # SQLAlchemy resolves Mapped[] annotations at runtime
from typing import Any

from advanced_alchemy.base import UUIDAuditBase
from advanced_alchemy.types import DateTimeUTC, JsonB
Expand Down Expand Up @@ -46,7 +47,7 @@ class BattlenetCharacter(UUIDAuditBase):
pvp_rank: Mapped[int | None] = mapped_column(Integer, default=None)
spec: Mapped[str | None] = mapped_column(Text, default=None)
last_login_at: Mapped[datetime | None] = mapped_column(DateTimeUTC(timezone=True), default=None)
sheet: Mapped[dict[str, object] | None] = mapped_column(JsonB, default=None)
sheet: Mapped[dict[str, Any] | None] = mapped_column(JsonB, default=None)
fetched_at: Mapped[datetime | None] = mapped_column(DateTimeUTC(timezone=True), index=True, default=None)
"""When the profile was last asked for, found or not. ``None`` until the first try."""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,8 @@
GameImportOfficerNote,
GameImportOfficerPart,
GameImportOfficerRecruit,
GameImportProfession,
GameImportReputation,
GameImportSheet,
GameImportUnseenMember,
GuildAnnouncementCreate,
Expand Down Expand Up @@ -837,6 +839,8 @@
"GameImportOfficerRecruit",
"GameImportPayload",
"GameImportPrice",
"GameImportProfession",
"GameImportReputation",
"GameImportSheet",
"GameImportSignup",
"GameImportStandingsRow",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,17 @@ class CharacterProfessionSkill(BaseModel):


class CharacterReputationLine(BaseModel):
"""Standing with one faction. ``value`` is progress within the standing, out of ``max``."""
"""Standing with one faction. ``value`` is progress within the standing, out of ``max``.

``faction_id`` and ``tier`` are ``None`` for sheets stored before these were added; they refresh within 6h.
"""

faction: str
standing: str
value: int
max: int
faction_id: int | None = Field(default=None, description="Battle.net faction id.")
tier: int | None = Field(default=None, description="Battle.net standing tier, counting up from Hated at 0.")


class CharacterAchievementLine(BaseModel):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,27 @@ class MemberNoteImportCounts(BaseModel):
# --- Site import v2 (``SQI1:``, additions): public, on-demand, and officer-only parts ----------------------------


class GameImportProfession(BaseModel):
"""One character's profession and skill, from its stored Battle.net sheet."""

name: str
skill: int
max_skill: int


class GameImportReputation(BaseModel):
"""One character's standing with a faction, from its stored Battle.net sheet.

``faction_id`` matches the addon's ``SideQuest.Data.REPUTATIONS`` table. ``standing`` is the WoW reaction index
(1 Hated .. 8 Exalted); ``value``/``max`` are progress within that standing.
"""

faction_id: int
standing: int
value: int
max: int


class GameImportCharacter(BaseModel):
"""One of a member's characters in the ``members`` game-import section."""

Expand All @@ -297,6 +318,13 @@ class GameImportCharacter(BaseModel):
item_level: int | None = Field(
default=None, description="Battle.net equipped average item level, when a profile has been fetched."
)
spec: str | None = Field(default=None, description="Battle.net active specialization, when a profile exists.")
professions: list[GameImportProfession] = Field(
default_factory=list, description="Battle.net professions, when a profile exists."
)
reputations: list[GameImportReputation] = Field(
default_factory=list, description="Battle.net tracked reputations, when a profile exists."
)


class GameImportBadgeRef(BaseModel):
Expand Down Expand Up @@ -751,6 +779,8 @@ class AnnouncementPostedResult(BaseModel):
"GameImportOfficerNote",
"GameImportOfficerPart",
"GameImportOfficerRecruit",
"GameImportProfession",
"GameImportReputation",
"GameImportSheet",
"GameImportUnseenMember",
"GuildAnnouncementCreate",
Expand Down
2 changes: 2 additions & 0 deletions tests/unit/api/test_characters.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,8 @@ async def test_a_character_page_is_fetched_once_then_served_from_the_database(
assert sheet["talents"] == [{"name": "Combat", "points": 4}]
assert [line["label"] for line in sheet["stats"]][:2] == ["Health", "Energy"]
assert {skill["name"] for skill in sheet["professions"]} >= {"Leatherworking", "Skinning"}
argent_dawn = next(line for line in sheet["reputations"] if line["faction"] == "Argent Dawn")
assert (argent_dawn["faction_id"], argent_dawn["tier"]) == (529, 3)
assert (sheet["mounts"], sheet["toys"]) == (2, 2)
assert sheet["hunter_pets"] == []

Expand Down
128 changes: 128 additions & 0 deletions tests/unit/api/test_guild_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,134 @@ async def test_game_import_inactive_list_uses_battlenet_last_login(
assert characters_by_name["gone-whitemane"]["item_level"] is None


async def test_game_import_characters_carry_stored_battlenet_spec_professions_and_reputations(
member_client: AsyncTestClient, discord_state: dict, db_sessionmaker: async_sessionmaker[AsyncSession]
) -> None:
"""A character with no addon data falls back to its stored Battle.net spec, professions and reputations;
a character with no stored profile at all gets the defaults."""
async with db_sessionmaker() as session:
member = Member(discord_id=7721, username="profiled-player", is_guild_member=True)
session.add(member)
await session.flush()
session.add(
WowCharacter(
name="Profiled", realm="Whitemane", key="profiled-whitemane", member_id=member.id, slug="profiled"
)
)
session.add(
WowCharacter(
name="Unprofiled",
realm="Whitemane",
key="unprofiled-whitemane",
member_id=member.id,
slug="unprofiled",
)
)
session.add(
BattlenetCharacter(
slug="profiled",
blizzard_id=7721,
name="Profiled",
surname="Whitemane",
level=60,
spec="Fire",
sheet={
"gear": [],
"stats": [],
"talents": [],
"professions": [
{"name": "Tailoring", "skill": 300, "max_skill": 300, "recipes": 0},
{"name": "Cooking", "skill": 150, "max_skill": 300, "recipes": 0},
],
"reputations": [
{
"faction": "Argent Dawn",
"standing": "Neutral",
"value": 686,
"max": 3000,
"faction_id": 529,
"tier": 3,
}
],
"recent_achievements": [],
"hunter_pets": [],
"mounts": 0,
"pets": 0,
"toys": 0,
"quests_completed": None,
},
)
)
await session.commit()
await _login_officer(member_client, discord_state, discord_id=7720)

response = await member_client.get("/api/epgp/game-import")
assert response.status_code == 200, response.text
decoded = json.loads(base64.b64decode(response.json()["payload"].removeprefix("SQI1:")))
characters_by_name = {
character["name"]: character for member in decoded["members"] for character in member["characters"]
}
profiled = characters_by_name["profiled-whitemane"]
assert profiled["spec"] == "Fire"
assert profiled["professions"] == [
{"name": "Tailoring", "skill": 300, "max_skill": 300},
{"name": "Cooking", "skill": 150, "max_skill": 300},
]
assert profiled["reputations"] == [{"faction_id": 529, "standing": 4, "value": 686, "max": 3000}]
unprofiled = characters_by_name["unprofiled-whitemane"]
assert unprofiled["spec"] is None
assert unprofiled["professions"] == []
assert unprofiled["reputations"] == []


async def test_game_import_skips_reputation_lines_missing_faction_id(
member_client: AsyncTestClient, discord_state: dict, db_sessionmaker: async_sessionmaker[AsyncSession]
) -> None:
"""A reputation line stored before ``faction_id``/``tier`` were added (older sheet) is left out of the import,
rather than sent with a wrong standing."""
async with db_sessionmaker() as session:
member = Member(discord_id=7731, username="stale-sheet-player", is_guild_member=True)
session.add(member)
await session.flush()
session.add(
WowCharacter(
name="Stalesheet", realm="Whitemane", key="stalesheet-whitemane", member_id=member.id, slug="stale"
)
)
session.add(
BattlenetCharacter(
slug="stale",
blizzard_id=7731,
name="Stalesheet",
surname="Whitemane",
level=60,
sheet={
"gear": [],
"stats": [],
"talents": [],
"professions": [],
"reputations": [{"faction": "Argent Dawn", "standing": "Neutral", "value": 686, "max": 3000}],
"recent_achievements": [],
"hunter_pets": [],
"mounts": 0,
"pets": 0,
"toys": 0,
"quests_completed": None,
},
)
)
await session.commit()
await _login_officer(member_client, discord_state, discord_id=7730)

response = await member_client.get("/api/epgp/game-import")
assert response.status_code == 200, response.text
decoded = json.loads(base64.b64decode(response.json()["payload"].removeprefix("SQI1:")))
characters_by_name = {
character["name"]: character for member in decoded["members"] for character in member["characters"]
}
assert characters_by_name["stalesheet-whitemane"]["reputations"] == []


async def test_game_import_unseen_member_is_not_listed_inactive(
member_client: AsyncTestClient, discord_state: dict, db_sessionmaker: async_sessionmaker[AsyncSession]
) -> None:
Expand Down
5 changes: 4 additions & 1 deletion website/src/pages/privacy/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ const articles = [
roster, and of any character anyone has looked up by name, and refresh it from Battle.net from time to time. For a
roster member Battle.net also publishes professions and known recipes once the character has logged out; we fill
the crafter directory from this when the addon hasn't already scanned a newer copy, so members without the addon
still show up as crafters. Nothing private is stored; it's the same data the Armory already shows.
still show up as crafters. The officer's addon import also carries a character's spec, professions and tracked
reputations from this stored data, so the Guild tab can show them for a guild member who doesn't run the addon;
live data an addon reports always takes priority over it. Nothing private is stored; it's the same data the Armory
already shows.
</p>
<p>
The <a href="/heroes/">Hall of Heroes</a> page's hero boards are public, no sign-in needed: top-10 lists of roster
Expand Down
Loading