Home Assistant Unofficial Reference 2024.12.1
api.py
Go to the documentation of this file.
1 """API for Google Mail bound to Home Assistant OAuth."""
2 
3 from functools import partial
4 
5 from aiohttp.client_exceptions import ClientError, ClientResponseError
6 from google.auth.exceptions import RefreshError
7 from google.oauth2.credentials import Credentials
8 from googleapiclient.discovery import Resource, build
9 
10 from homeassistant.config_entries import ConfigEntryState
11 from homeassistant.const import CONF_ACCESS_TOKEN
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import (
14  ConfigEntryAuthFailed,
15  ConfigEntryNotReady,
16  HomeAssistantError,
17 )
18 from homeassistant.helpers import config_entry_oauth2_flow
19 
20 
22  """Provide Google Mail authentication tied to an OAuth2 based config entry."""
23 
24  def __init__(
25  self,
26  hass: HomeAssistant,
27  oauth2_session: config_entry_oauth2_flow.OAuth2Session,
28  ) -> None:
29  """Initialize Google Mail Auth."""
30  self._hass_hass = hass
31  self.oauth_sessionoauth_session = oauth2_session
32 
33  @property
34  def access_token(self) -> str:
35  """Return the access token."""
36  return self.oauth_sessionoauth_session.token[CONF_ACCESS_TOKEN]
37 
38  async def check_and_refresh_token(self) -> str:
39  """Check the token."""
40  try:
41  await self.oauth_sessionoauth_session.async_ensure_token_valid()
42  except (RefreshError, ClientResponseError, ClientError) as ex:
43  if (
44  self.oauth_sessionoauth_session.config_entry.state
45  is ConfigEntryState.SETUP_IN_PROGRESS
46  ):
47  if isinstance(ex, ClientResponseError) and 400 <= ex.status < 500:
49  "OAuth session is not valid, reauth required"
50  ) from ex
51  raise ConfigEntryNotReady from ex
52  if (
53  isinstance(ex, RefreshError)
54  or hasattr(ex, "status")
55  and ex.status == 400
56  ):
57  self.oauth_sessionoauth_session.config_entry.async_start_reauth(
58  self.oauth_sessionoauth_session.hass
59  )
60  raise HomeAssistantError(ex) from ex
61  return self.access_tokenaccess_token
62 
63  async def get_resource(self) -> Resource:
64  """Get current resource."""
65  credentials = Credentials(await self.check_and_refresh_tokencheck_and_refresh_token())
66  return await self._hass_hass.async_add_executor_job(
67  partial(build, "gmail", "v1", credentials=credentials)
68  )
None __init__(self, HomeAssistant hass, config_entry_oauth2_flow.OAuth2Session oauth2_session)
Definition: api.py:28