1"""The client: configuration, authentication, retries and resource namespaces."""
2
3import os
4import re
5from dataclasses import dataclass, field, replace
6from datetime import timedelta
7from functools import cached_property
8from typing import TYPE_CHECKING, Self
9from urllib.parse import urlencode
10
11import httpx
12from msgspec import Struct
13
14from wow._async.resources.account import AsyncAccount
15from wow._async.resources.achievement import AsyncAchievementCategories, AsyncAchievements
16from wow._async.resources.auction import AsyncAuctions
17from wow._async.resources.character import AsyncCharacters
18from wow._async.resources.creature import AsyncCreatureFamilies, AsyncCreatures, AsyncCreatureTypes
19from wow._async.resources.guild import AsyncGuilds
20from wow._async.resources.guild_crest import AsyncGuildCrests
21from wow._async.resources.item import AsyncItemClasses, AsyncItems, AsyncItemSets
22from wow._async.resources.item_appearance import AsyncItemAppearances
23from wow._async.resources.media import AsyncMedia
24from wow._async.resources.mount import AsyncMounts
25from wow._async.resources.pet import AsyncPets
26from wow._async.resources.playable_class import AsyncPlayableClasses
27from wow._async.resources.playable_race import AsyncPlayableRaces
28from wow._async.resources.playable_specialization import AsyncPlayableSpecializations
29from wow._async.resources.power_type import AsyncPowerTypes
30from wow._async.resources.profession import AsyncProfessions
31from wow._async.resources.quest import AsyncQuestAreas, AsyncQuestCategories, AsyncQuests, AsyncQuestTypes
32from wow._async.resources.realm import AsyncRealms
33from wow._async.resources.recipe import AsyncRecipes
34from wow._async.resources.region import AsyncRegions
35from wow._async.resources.reputation import AsyncReputationFactions, AsyncReputationTiers
36from wow._async.resources.ruleset import AsyncRulesets
37from wow._async.resources.spell import AsyncSpells
38from wow._async.resources.talent import AsyncTalents, AsyncTalentTrees
39from wow._async.resources.title import AsyncTitles
40from wow._async.resources.toy import AsyncToys
41from wow._base import (
42 DEFAULT_MAX_RETRIES,
43 DEFAULT_TIMEOUT,
44 OAUTH_URL,
45 TOKEN_EXPIRY_MARGIN,
46 USER_AGENT,
47 OAuthToken,
48 api_url,
49 backoff,
50 connection_error,
51 is_transient,
52 parse_model,
53 parse_token,
54 raise_for_status,
55 request_params,
56 retry_delay,
57 should_retry,
58)
59from wow._concurrency import AsyncLock, async_sleep
60from wow._exceptions import APIError, WowError
61from wow._response import APIResponse
62from wow._types import DEFAULT_LOCALES, LOCALES, Locale, NamespaceKind, Region, is_locale
63
64if TYPE_CHECKING:
65 from collections.abc import Iterable, Mapping
66 from types import TracebackType
67
68__all__ = ["AsyncClient"]
69
70
71@dataclass(frozen=True, slots=True)
72class _Config:
73 """Per-client settings; :meth:`AsyncClient.with_options` copies and changes these."""
74
75 region: Region
76 locale: Locale
77 locale_is_default: bool
78 access_token: str | None = field(repr=False)
79 timeout: httpx.Timeout
80 max_retries: int
81 base_url: str | None
82 oauth_url: str
83 static_version: str | None
84
85 @property
86 def api_url(self) -> str:
87 return self.base_url or api_url(self.region)
88
89
90@dataclass(slots=True)
91class _Session:
92 """State shared by a client and every copy made with :meth:`AsyncClient.with_options`."""
93
94 http: httpx.AsyncClient
95 client_id: str | None
96 client_secret: str | None = field(repr=False)
97 app_token: OAuthToken | None = None
98 token_lock: AsyncLock = field(default_factory=AsyncLock)
99
100
[docs]
101class AsyncClient:
102 """Async client for the World of Warcraft: Forever API.
103
104 Game data needs app credentials from https://develop.battle.net; the client trades them for an access token and
105 refreshes it before it expires. Profile routes need a user's token instead, from :meth:`exchange_code`.
106
107 Use one client for the life of your program and close it when done; it is a context manager::
108
109 async with AsyncClient(region="eu") as client:
110 druid = await client.playable_classes.get(11)
111
112 Args:
113 client_id: App client id. Defaults to the ``BATTLENET_CLIENT_ID`` environment variable.
114 client_secret: App client secret. Defaults to ``BATTLENET_CLIENT_SECRET``.
115 access_token: A token to send instead of fetching one with the app credentials, such as a user token with
116 the ``wow.profile`` scope.
117 region: The API region to read.
118 locale: The language for names and descriptions. Defaults to the region's main locale.
119 timeout: Seconds, or an ``httpx.Timeout``, applied to every request.
120 max_retries: Retries for connection errors, timeouts, 408, 429 and 5xx responses. ``0`` disables retrying.
121 http_client: An ``httpx.AsyncClient`` to send requests through, for proxies, transports or caching. The
122 caller keeps ownership and must close it.
123 base_url: Override the API host, for example to point at a mock server.
124 oauth_url: Override the OAuth host.
125 static_version: Pin static-data requests (playable classes, items, talents and the rest of game data that
126 only changes with patches) to one build, such as ``"1.60.1_70399"``, instead of Battle.net's current
127 static namespace. Dynamic and profile requests are unaffected.
128
129 Raises:
130 WowError: Neither app credentials nor an access token were given.
131 ValueError: ``locale``, ``max_retries`` or ``access_token`` is invalid.
132 """
133
134 def __init__(
135 self,
136 client_id: str | None = None,
137 client_secret: str | None = None,
138 *,
139 access_token: str | None = None,
140 region: Region | str = Region.US,
141 locale: Locale | None = None,
142 timeout: float | httpx.Timeout = DEFAULT_TIMEOUT,
143 max_retries: int = DEFAULT_MAX_RETRIES,
144 http_client: httpx.AsyncClient | None = None,
145 base_url: str | None = None,
146 oauth_url: str = OAUTH_URL,
147 static_version: str | None = None,
148 ) -> None:
149 client_id = client_id or os.environ.get("BATTLENET_CLIENT_ID")
150 client_secret = client_secret or os.environ.get("BATTLENET_CLIENT_SECRET")
151 if access_token is None and not (client_id and client_secret):
152 msg = (
153 "no credentials: pass client_id and client_secret, set BATTLENET_CLIENT_ID and "
154 "BATTLENET_CLIENT_SECRET, or pass access_token"
155 )
156 raise WowError(msg)
157 resolved_region = Region(region)
158 self._config = _Config(
159 region=resolved_region,
160 locale=_check_locale(locale or DEFAULT_LOCALES[resolved_region]),
161 locale_is_default=locale is None,
162 access_token=None if access_token is None else _check_access_token(access_token),
163 timeout=timeout if isinstance(timeout, httpx.Timeout) else httpx.Timeout(timeout),
164 max_retries=_check_retries(max_retries),
165 base_url=base_url.rstrip("/") if base_url else None,
166 oauth_url=oauth_url.rstrip("/"),
167 static_version=static_version,
168 )
169 self._session = _Session(
170 http=http_client or httpx.AsyncClient(headers={"User-Agent": USER_AGENT}),
171 client_id=client_id,
172 client_secret=client_secret,
173 )
174 self._owns_http = http_client is None
175
176 @classmethod
177 def _from_parts(cls, config: _Config, session: _Session) -> Self:
178 client = cls.__new__(cls)
179 client._config = config # noqa: SLF001 - initialising a copy of this class
180 client._session = session # noqa: SLF001 - initialising a copy of this class
181 client._owns_http = False # noqa: SLF001 - copies never close the shared pool
182 return client
183
184 def __repr__(self) -> str:
185 return f"<{type(self).__name__} region={self.region.value} locale={self.locale}>"
186
187 @property
188 def region(self) -> Region:
189 """The region this client reads."""
190 return self._config.region
191
192 @property
193 def locale(self) -> Locale:
194 """The locale names and descriptions come back in."""
195 return self._config.locale
196
197 @property
198 def static_version(self) -> str | None:
199 """The build static-data requests are pinned to, or ``None`` for Battle.net's current static namespace."""
200 return self._config.static_version
201
202 # Resources, alphabetical. Each is created on first use and bound to this client's settings.
203
204 @cached_property
205 def account(self) -> AsyncAccount:
206 """The authenticated user's WoW Forever accounts and characters."""
207 return AsyncAccount(self)
208
209 @cached_property
210 def achievement_categories(self) -> AsyncAchievementCategories:
211 """The groups achievements are organized into."""
212 return AsyncAchievementCategories(self)
213
214 @cached_property
215 def achievements(self) -> AsyncAchievements:
216 """Achievements such as Explorer and Master of Alterac Valley."""
217 return AsyncAchievements(self)
218
219 @cached_property
220 def auctions(self) -> AsyncAuctions:
221 """The auction houses Forever's rulesets use in place of realm auction houses."""
222 return AsyncAuctions(self)
223
224 @cached_property
225 def characters(self) -> AsyncCharacters:
226 """Any character's public profile: gear, stats, talents, professions and more."""
227 return AsyncCharacters(self)
228
229 @cached_property
230 def creature_families(self) -> AsyncCreatureFamilies:
231 """Pet families such as Bat and Wolf."""
232 return AsyncCreatureFamilies(self)
233
234 @cached_property
235 def creature_types(self) -> AsyncCreatureTypes:
236 """Creature types such as Beast and Dragonkin."""
237 return AsyncCreatureTypes(self)
238
239 @cached_property
240 def creatures(self) -> AsyncCreatures:
241 """Creatures, Forest Spider included."""
242 return AsyncCreatures(self)
243
244 @cached_property
245 def guild_crests(self) -> AsyncGuildCrests:
246 """The emblems, borders and colors guild crests use."""
247 return AsyncGuildCrests(self)
248
249 @cached_property
250 def guilds(self) -> AsyncGuilds:
251 """Guilds and their rosters."""
252 return AsyncGuilds(self)
253
254 @cached_property
255 def item_appearances(self) -> AsyncItemAppearances:
256 """The renders items share, and the slots and sets they group into."""
257 return AsyncItemAppearances(self)
258
259 @cached_property
260 def item_classes(self) -> AsyncItemClasses:
261 """Item classes such as Weapon and Consumable."""
262 return AsyncItemClasses(self)
263
264 @cached_property
265 def item_sets(self) -> AsyncItemSets:
266 """Equipment sets."""
267 return AsyncItemSets(self)
268
269 @cached_property
270 def items(self) -> AsyncItems:
271 """Items."""
272 return AsyncItems(self)
273
274 @cached_property
275 def media(self) -> AsyncMedia:
276 """Media documents across every static type, searchable by tag."""
277 return AsyncMedia(self)
278
279 @cached_property
280 def mounts(self) -> AsyncMounts:
281 """Mounts."""
282 return AsyncMounts(self)
283
284 @cached_property
285 def pets(self) -> AsyncPets:
286 """Battle pet species."""
287 return AsyncPets(self)
288
289 @cached_property
290 def playable_classes(self) -> AsyncPlayableClasses:
291 """Playable classes such as Warrior and Mage."""
292 return AsyncPlayableClasses(self)
293
294 @cached_property
295 def playable_races(self) -> AsyncPlayableRaces:
296 """Playable races such as Human and Orc."""
297 return AsyncPlayableRaces(self)
298
299 @cached_property
300 def playable_specializations(self) -> AsyncPlayableSpecializations:
301 """Class specializations such as Fury or Restoration."""
302 return AsyncPlayableSpecializations(self)
303
304 @cached_property
305 def power_types(self) -> AsyncPowerTypes:
306 """Power types such as Mana and Rage."""
307 return AsyncPowerTypes(self)
308
309 @cached_property
310 def professions(self) -> AsyncProfessions:
311 """Professions such as Tailoring and Cooking."""
312 return AsyncProfessions(self)
313
314 @cached_property
315 def quest_areas(self) -> AsyncQuestAreas:
316 """The zones quests take place in."""
317 return AsyncQuestAreas(self)
318
319 @cached_property
320 def quest_categories(self) -> AsyncQuestCategories:
321 """Quest groupings such as Epic or Seasonal."""
322 return AsyncQuestCategories(self)
323
324 @cached_property
325 def quest_types(self) -> AsyncQuestTypes:
326 """Quest kinds such as Elite, PvP or Raid."""
327 return AsyncQuestTypes(self)
328
329 @cached_property
330 def quests(self) -> AsyncQuests:
331 """Individual quests."""
332 return AsyncQuests(self)
333
334 @cached_property
335 def realms(self) -> AsyncRealms:
336 """WoW Forever realms."""
337 return AsyncRealms(self)
338
339 @cached_property
340 def recipes(self) -> AsyncRecipes:
341 """Profession recipes."""
342 return AsyncRecipes(self)
343
344 @cached_property
345 def regions(self) -> AsyncRegions:
346 """Battle.net API regions."""
347 return AsyncRegions(self)
348
349 @cached_property
350 def reputation_factions(self) -> AsyncReputationFactions:
351 """Reputation factions such as cities, tribes and armies."""
352 return AsyncReputationFactions(self)
353
354 @cached_property
355 def reputation_tiers(self) -> AsyncReputationTiers:
356 """The standing levels a faction's reputation can reach."""
357 return AsyncReputationTiers(self)
358
359 @cached_property
360 def rulesets(self) -> AsyncRulesets:
361 """Rulesets such as Normal and PvP, which Forever has in place of realms."""
362 return AsyncRulesets(self)
363
364 @cached_property
365 def spells(self) -> AsyncSpells:
366 """Spells, such as talents and abilities."""
367 return AsyncSpells(self)
368
369 @cached_property
370 def talent_trees(self) -> AsyncTalentTrees:
371 """Class and specialization talent trees."""
372 return AsyncTalentTrees(self)
373
374 @cached_property
375 def talents(self) -> AsyncTalents:
376 """Individual talents across every class and specialization."""
377 return AsyncTalents(self)
378
379 @cached_property
380 def titles(self) -> AsyncTitles:
381 """Character titles such as Commander."""
382 return AsyncTitles(self)
383
384 @cached_property
385 def toys(self) -> AsyncToys:
386 """Toy-box toys."""
387 return AsyncToys(self)
388
[docs]
389 def with_options(
390 self,
391 *,
392 region: Region | str | None = None,
393 locale: Locale | None = None,
394 access_token: str | None = None,
395 timeout: float | httpx.Timeout | None = None,
396 max_retries: int | None = None,
397 static_version: str | None = None,
398 ) -> Self:
399 """Return a client with some settings changed.
400
401 The copy shares the connection pool and the cached app token, so it is cheap; make one per region, locale
402 or user token as needed. Only the original client closes the pool.
403
404 Args:
405 region: Read another region. The locale follows the region unless one was set explicitly.
406 locale: Use another locale.
407 access_token: Authenticate as a user, for profile routes.
408 timeout: Change the request timeout.
409 max_retries: Change the retry budget.
410 static_version: Pin static-data requests to another build.
411
412 Raises:
413 ValueError: ``locale``, ``max_retries`` or ``access_token`` is invalid.
414 """
415 config = self._config
416 new_region = Region(region) if region is not None else config.region
417 if locale is not None:
418 new_locale, locale_is_default = _check_locale(locale), False
419 elif config.locale_is_default:
420 new_locale, locale_is_default = DEFAULT_LOCALES[new_region], True
421 else:
422 new_locale, locale_is_default = config.locale, False
423 changed = replace(
424 config,
425 region=new_region,
426 locale=new_locale,
427 locale_is_default=locale_is_default,
428 access_token=config.access_token if access_token is None else _check_access_token(access_token),
429 timeout=config.timeout
430 if timeout is None
431 else timeout
432 if isinstance(timeout, httpx.Timeout)
433 else httpx.Timeout(timeout),
434 max_retries=config.max_retries if max_retries is None else _check_retries(max_retries),
435 static_version=static_version if static_version is not None else config.static_version,
436 )
437 return self._from_parts(changed, self._session)
438
[docs]
439 async def aclose(self) -> None:
440 """Close the connection pool, unless it was passed in as ``http_client`` or this client is a copy."""
441 if self._owns_http:
442 await self._session.http.aclose()
443
444 async def __aenter__(self) -> Self:
445 return self
446
447 async def __aexit__(
448 self,
449 exc_type: type[BaseException] | None,
450 exc: BaseException | None,
451 traceback: TracebackType | None,
452 ) -> None:
453 await self.aclose()
454
[docs]
455 async def get(
456 self,
457 path: str,
458 *,
459 namespace: NamespaceKind | None = None,
460 params: Mapping[str, str | int] | None = None,
461 ) -> APIResponse:
462 """GET any document, for routes without a typed method or links followed by hand.
463
464 Args:
465 path: A path such as ``/data/wow/playable-class/1``, or a full ``href`` from a document's links. Hrefs
466 already carry their namespace.
467 namespace: The document family to read. Leave it out for hrefs.
468 params: Extra query parameters.
469
470 Raises:
471 ValueError: ``path`` is a URL on another host; the client never sends its token elsewhere.
472 APIStatusError: Battle.net answered with an error status.
473 APIConnectionError: No response arrived.
474 """
475 api = httpx.URL(self._config.api_url)
476 if path.startswith(("https://", "http://")):
477 url = httpx.URL(path)
478 if (url.scheme, url.host, url.port) != (api.scheme, api.host, api.port):
479 msg = f"refusing to send credentials to {url.scheme}://{url.host}: links must point at {api}"
480 raise ValueError(msg)
481 else:
482 url = httpx.URL(f"{self._config.api_url}/{path.lstrip('/')}")
483 merged = {
484 **dict(url.params),
485 **request_params(namespace, self._config.region, self._config.locale, params, self._config.static_version),
486 }
487 return APIResponse(await self._api_request(str(url.copy_with(query=None)), merged))
488
489 async def _get_model[ModelT: Struct](
490 self,
491 namespace: NamespaceKind,
492 path: str,
493 model: type[ModelT],
494 params: Mapping[str, str | int] | None = None,
495 ) -> ModelT:
496 url = f"{self._config.api_url}{path}"
497 response = await self._api_request(
498 url,
499 request_params(namespace, self._config.region, self._config.locale, params, self._config.static_version),
500 )
501 return parse_model(response, model)
502
[docs]
503 def authorization_url(
504 self,
505 redirect_uri: str,
506 *,
507 state: str,
508 scopes: str | Iterable[str] = ("wow.profile",),
509 ) -> str:
510 """Build the Battle.net login URL for the authorization code flow.
511
512 Send the user here; Battle.net redirects back to ``redirect_uri`` with ``code`` and ``state`` query
513 parameters. Check ``state`` matches, then pass ``code`` to :meth:`exchange_code`.
514
515 Args:
516 redirect_uri: A redirect URL registered for the app.
517 state: An unguessable value tied to the user's session, to stop cross-site request forgery.
518 scopes: Scopes to request, as one string or several. ``wow.profile`` unlocks the account profile; add
519 ``openid`` for an ID token.
520 """
521 query = urlencode(
522 {
523 "response_type": "code",
524 "client_id": self._require_client_id(),
525 "redirect_uri": redirect_uri,
526 "scope": scopes if isinstance(scopes, str) else " ".join(scopes),
527 "state": state,
528 }
529 )
530 return f"{self._config.oauth_url}/authorize?{query}"
531
[docs]
532 async def exchange_code(self, code: str, redirect_uri: str) -> OAuthToken:
533 """Trade an authorization code for the user's access token.
534
535 Use the token with ``client.with_options(access_token=token.access_token)``.
536
537 Args:
538 code: The ``code`` query parameter Battle.net redirected back with.
539 redirect_uri: The same ``redirect_uri`` given to :meth:`authorization_url`.
540
541 Raises:
542 AuthenticationError: The app credentials were rejected.
543 BadRequestError: The code is invalid, expired or already used, or ``redirect_uri`` does not match.
544 """
545 # Never retried: a code is single-use, so a retry after a lost response would only fail with invalid_grant.
546 response = await self._token_request(
547 {"grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri}, max_retries=0
548 )
549 return parse_token(response)
550
551 def _require_client_id(self) -> str:
552 if not self._session.client_id:
553 msg = "this needs app credentials, but the client was created with only an access token"
554 raise WowError(msg)
555 return self._session.client_id
556
557 async def _token_request(self, data: Mapping[str, str], *, max_retries: int | None = None) -> httpx.Response:
558 client_id = self._require_client_id()
559 auth = httpx.BasicAuth(client_id, self._session.client_secret or "")
560 url = f"{self._config.oauth_url}/token"
561 return await self._send("POST", url, data=data, auth=auth, max_retries=max_retries)
562
563 async def _app_token(self) -> OAuthToken:
564 session = self._session
565 token = session.app_token
566 if token is not None and not token.expires_within(TOKEN_EXPIRY_MARGIN):
567 return token
568 async with session.token_lock:
569 current = session.app_token
570 if current is not None and not current.expires_within(TOKEN_EXPIRY_MARGIN):
571 return current
572 try:
573 token = parse_token(await self._token_request({"grant_type": "client_credentials"}))
574 except APIError:
575 # The margin only makes the refresh early. While Battle.net still accepts the current token, a
576 # refresh that fails must not fail the request; the next request tries again.
577 if current is None or current.expires_within(timedelta(0)):
578 raise
579 return current
580 session.app_token = token
581 return token
582
583 async def _api_request(self, url: str, params: Mapping[str, str | int]) -> httpx.Response:
584 """GET an API URL with a bearer token, replacing a rejected app token once."""
585 token_refreshed = False
586 while True:
587 app_token = None if self._config.access_token is not None else await self._app_token()
588 bearer = app_token.access_token if app_token is not None else self._config.access_token
589 response = await self._send("GET", url, params=params, headers={"Authorization": f"Bearer {bearer}"})
590 if response.status_code == httpx.codes.UNAUTHORIZED and app_token is not None and not token_refreshed:
591 # The app token was revoked or expired early. Drop it unless a concurrent request already replaced
592 # it, then fetch (or reuse) a fresh one, once.
593 async with self._session.token_lock:
594 if self._session.app_token is app_token:
595 self._session.app_token = None
596 token_refreshed = True
597 continue
598 raise_for_status(response)
599 return response
600
601 async def _send(
602 self,
603 method: str,
604 url: str,
605 *,
606 params: Mapping[str, str | int] | None = None,
607 data: Mapping[str, str] | None = None,
608 headers: Mapping[str, str] | None = None,
609 auth: httpx.Auth | None = None,
610 max_retries: int | None = None,
611 ) -> httpx.Response:
612 """Send a request, retrying failures without a response, 408, 429 and 5xx; never raises for status."""
613 config = self._config
614 budget = config.max_retries if max_retries is None else max_retries
615 retries_done = 0
616 while True:
617 try:
618 response = await self._session.http.request(
619 method, url, params=params, data=data, headers=headers, auth=auth, timeout=config.timeout
620 )
621 except httpx.RequestError as error:
622 if retries_done >= budget or not is_transient(error):
623 raise connection_error(method, error) from error
624 delay = backoff(retries_done)
625 else:
626 if not should_retry(response) or retries_done >= budget:
627 return response
628 if (delay := retry_delay(retries_done, response)) is None:
629 return response
630 await async_sleep(delay)
631 retries_done += 1
632
633
634# A bearer token is visible ASCII with no whitespace (RFC 6750). No other character can be part of one, and most
635# make the ``Authorization`` header illegal.
636_SENDABLE_TOKEN = re.compile(r"[!-~]+")
637
638
639def _check_access_token(access_token: str) -> str:
640 if not _SENDABLE_TOKEN.fullmatch(access_token):
641 # Never quote the token here: this message is logged. Left unchecked, the HTTP layer would fail on every
642 # attempt and name the whole header, token included, in its error.
643 msg = (
644 "access_token is empty, or has whitespace, control or non-ASCII characters; "
645 "pass the token exactly as Battle.net issued it, without a trailing newline"
646 )
647 raise ValueError(msg)
648 return access_token
649
650
651def _check_locale(locale: str) -> Locale:
652 if not is_locale(locale):
653 msg = f"unknown locale {locale!r}; expected one of {', '.join(sorted(LOCALES))}"
654 raise ValueError(msg)
655 return locale
656
657
658def _check_retries(max_retries: int) -> int:
659 if max_retries < 0:
660 msg = f"max_retries must be 0 or more, got {max_retries}"
661 raise ValueError(msg)
662 return max_retries