Home Assistant Unofficial Reference 2024.12.1
api.py
Go to the documentation of this file.
1 """API for YouTube bound to Home Assistant OAuth."""
2 
3 from youtubeaio.types import AuthScope
4 from youtubeaio.youtube import YouTube
5 
6 from homeassistant.const import CONF_ACCESS_TOKEN
7 from homeassistant.core import HomeAssistant
8 from homeassistant.helpers import config_entry_oauth2_flow
9 from homeassistant.helpers.aiohttp_client import async_get_clientsession
10 
11 
13  """Provide Google authentication tied to an OAuth2 based config entry."""
14 
15  youtube: YouTube | None = None
16 
17  def __init__(
18  self,
19  hass: HomeAssistant,
20  oauth2_session: config_entry_oauth2_flow.OAuth2Session,
21  ) -> None:
22  """Initialize YouTube Auth."""
23  self.oauth_sessionoauth_session = oauth2_session
24  self.hasshass = hass
25 
26  @property
27  def access_token(self) -> str:
28  """Return the access token."""
29  return self.oauth_sessionoauth_session.token[CONF_ACCESS_TOKEN] # type: ignore[no-any-return]
30 
31  async def check_and_refresh_token(self) -> str:
32  """Check the token."""
33  await self.oauth_sessionoauth_session.async_ensure_token_valid()
34  return self.access_tokenaccess_token
35 
36  async def get_resource(self) -> YouTube:
37  """Create resource."""
38  token = await self.check_and_refresh_tokencheck_and_refresh_token()
39  if self.youtubeyoutube is None:
40  self.youtubeyoutube = YouTube(session=async_get_clientsession(self.hasshass))
41  await self.youtubeyoutube.set_user_authentication(token, [AuthScope.READ_ONLY])
42  return self.youtubeyoutube
None __init__(self, HomeAssistant hass, config_entry_oauth2_flow.OAuth2Session oauth2_session)
Definition: api.py:21
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)