Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Data update coordinator for the Steam integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 from typing import TYPE_CHECKING
7 
8 import steam
9 from steam.api import _interface_method as INTMethod
10 
11 from homeassistant.const import CONF_API_KEY
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import ConfigEntryAuthFailed
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
15 
16 from .const import CONF_ACCOUNTS, DOMAIN, LOGGER
17 
18 if TYPE_CHECKING:
19  from . import SteamConfigEntry
20 
21 
23  DataUpdateCoordinator[dict[str, dict[str, str | int]]]
24 ):
25  """Data update coordinator for the Steam integration."""
26 
27  config_entry: SteamConfigEntry
28 
29  def __init__(self, hass: HomeAssistant) -> None:
30  """Initialize the coordinator."""
31  super().__init__(
32  hass=hass,
33  logger=LOGGER,
34  name=DOMAIN,
35  update_interval=timedelta(seconds=30),
36  )
37  self.game_iconsgame_icons: dict[int, str] = {}
38  self.player_interfaceplayer_interface: INTMethod = None
39  self.user_interfaceuser_interface: INTMethod = None
40  steam.api.key.set(self.config_entryconfig_entry.data[CONF_API_KEY])
41 
42  def _update(self) -> dict[str, dict[str, str | int]]:
43  """Fetch data from API endpoint."""
44  accounts = self.config_entryconfig_entry.options[CONF_ACCOUNTS]
45  _ids = list(accounts)
46  if not self.user_interfaceuser_interface or not self.player_interfaceplayer_interface:
47  self.user_interfaceuser_interface = steam.api.interface("ISteamUser")
48  self.player_interfaceplayer_interface = steam.api.interface("IPlayerService")
49  if not self.game_iconsgame_icons:
50  for _id in _ids:
51  res = self.player_interfaceplayer_interface.GetOwnedGames(
52  steamid=_id, include_appinfo=1
53  )["response"]
54  self.game_iconsgame_icons = self.game_iconsgame_icons | {
55  game["appid"]: game["img_icon_url"] for game in res.get("games", [])
56  }
57  response = self.user_interfaceuser_interface.GetPlayerSummaries(steamids=_ids)
58  players = {
59  player["steamid"]: player
60  for player in response["response"]["players"]["player"]
61  if player["steamid"] in _ids
62  }
63  for value in players.values():
64  data = self.player_interfaceplayer_interface.GetSteamLevel(steamid=value["steamid"])
65  value["level"] = data["response"].get("player_level")
66  return players
67 
68  async def _async_update_data(self) -> dict[str, dict[str, str | int]]:
69  """Send request to the executor."""
70  try:
71  return await self.hasshass.async_add_executor_job(self._update_update)
72 
73  except (steam.api.HTTPError, steam.api.HTTPTimeoutError) as ex:
74  if "401" in str(ex):
75  raise ConfigEntryAuthFailed from ex
76  raise UpdateFailed(ex) from ex
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88