Source code for wow._sync._client

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