Store runtime data inside the config entry in Google Mail (#119439)

This commit is contained in:
Robert Hillis 2024-06-12 10:49:40 -04:00 committed by GitHub
parent 420ee782ff
commit dc3ade6558
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 25 additions and 20 deletions

View File

@ -16,6 +16,8 @@ from .api import AsyncConfigEntryAuth
from .const import DATA_AUTH, DATA_HASS_CONFIG, DOMAIN from .const import DATA_AUTH, DATA_HASS_CONFIG, DOMAIN
from .services import async_setup_services from .services import async_setup_services
type GoogleMailConfigEntry = ConfigEntry[AsyncConfigEntryAuth]
PLATFORMS = [Platform.NOTIFY, Platform.SENSOR] PLATFORMS = [Platform.NOTIFY, Platform.SENSOR]
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
@ -28,13 +30,13 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: GoogleMailConfigEntry) -> bool:
"""Set up Google Mail from a config entry.""" """Set up Google Mail from a config entry."""
implementation = await async_get_config_entry_implementation(hass, entry) implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation) session = OAuth2Session(hass, entry, implementation)
auth = AsyncConfigEntryAuth(hass, session) auth = AsyncConfigEntryAuth(hass, session)
await auth.check_and_refresh_token() await auth.check_and_refresh_token()
hass.data[DOMAIN][entry.entry_id] = auth entry.runtime_data = auth
hass.async_create_task( hass.async_create_task(
discovery.async_load_platform( discovery.async_load_platform(
@ -55,10 +57,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return True return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: GoogleMailConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)
loaded_entries = [ loaded_entries = [
entry entry
for entry in hass.config_entries.async_entries(DOMAIN) for entry in hass.config_entries.async_entries(DOMAIN)
@ -68,4 +68,4 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
for service_name in hass.services.async_services_for_domain(DOMAIN): for service_name in hass.services.async_services_for_domain(DOMAIN):
hass.services.async_remove(DOMAIN, service_name) hass.services.async_remove(DOMAIN, service_name)
return unload_ok return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@ -9,10 +9,11 @@ from typing import Any, cast
from google.oauth2.credentials import Credentials from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build from googleapiclient.discovery import build
from homeassistant.config_entries import ConfigEntry, ConfigFlowResult from homeassistant.config_entries import ConfigFlowResult
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN
from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers import config_entry_oauth2_flow
from . import GoogleMailConfigEntry
from .const import DEFAULT_ACCESS, DOMAIN from .const import DEFAULT_ACCESS, DOMAIN
@ -23,7 +24,7 @@ class OAuth2FlowHandler(
DOMAIN = DOMAIN DOMAIN = DOMAIN
reauth_entry: ConfigEntry | None = None reauth_entry: GoogleMailConfigEntry | None = None
@property @property
def logger(self) -> logging.Logger: def logger(self) -> logging.Logger:

View File

@ -11,11 +11,10 @@ from homeassistant.components.sensor import (
SensorEntity, SensorEntity,
SensorEntityDescription, SensorEntityDescription,
) )
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import DOMAIN from . import GoogleMailConfigEntry
from .entity import GoogleMailEntity from .entity import GoogleMailEntity
SCAN_INTERVAL = timedelta(minutes=15) SCAN_INTERVAL = timedelta(minutes=15)
@ -28,12 +27,12 @@ SENSOR_TYPE = SensorEntityDescription(
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback hass: HomeAssistant,
entry: GoogleMailConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up the Google Mail sensor.""" """Set up the Google Mail sensor."""
async_add_entities( async_add_entities([GoogleMailSensor(entry.runtime_data, SENSOR_TYPE)], True)
[GoogleMailSensor(hass.data[DOMAIN][entry.entry_id], SENSOR_TYPE)], True
)
class GoogleMailSensor(GoogleMailEntity, SensorEntity): class GoogleMailSensor(GoogleMailEntity, SensorEntity):

View File

@ -3,16 +3,15 @@
from __future__ import annotations from __future__ import annotations
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import TYPE_CHECKING
from googleapiclient.http import HttpRequest from googleapiclient.http import HttpRequest
import voluptuous as vol import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.service import async_extract_config_entry_ids from homeassistant.helpers.service import async_extract_config_entry_ids
from .api import AsyncConfigEntryAuth
from .const import ( from .const import (
ATTR_ENABLED, ATTR_ENABLED,
ATTR_END, ATTR_END,
@ -26,6 +25,9 @@ from .const import (
DOMAIN, DOMAIN,
) )
if TYPE_CHECKING:
from . import GoogleMailConfigEntry
SERVICE_SET_VACATION = "set_vacation" SERVICE_SET_VACATION = "set_vacation"
SERVICE_VACATION_SCHEMA = vol.All( SERVICE_VACATION_SCHEMA = vol.All(
@ -47,7 +49,9 @@ SERVICE_VACATION_SCHEMA = vol.All(
async def async_setup_services(hass: HomeAssistant) -> None: async def async_setup_services(hass: HomeAssistant) -> None:
"""Set up services for Google Mail integration.""" """Set up services for Google Mail integration."""
async def extract_gmail_config_entries(call: ServiceCall) -> list[ConfigEntry]: async def extract_gmail_config_entries(
call: ServiceCall,
) -> list[GoogleMailConfigEntry]:
return [ return [
entry entry
for entry_id in await async_extract_config_entry_ids(hass, call) for entry_id in await async_extract_config_entry_ids(hass, call)
@ -57,10 +61,11 @@ async def async_setup_services(hass: HomeAssistant) -> None:
async def gmail_service(call: ServiceCall) -> None: async def gmail_service(call: ServiceCall) -> None:
"""Call Google Mail service.""" """Call Google Mail service."""
auth: AsyncConfigEntryAuth
for entry in await extract_gmail_config_entries(call): for entry in await extract_gmail_config_entries(call):
if not (auth := hass.data[DOMAIN].get(entry.entry_id)): try:
raise ValueError(f"Config entry not loaded: {entry.entry_id}") auth = entry.runtime_data
except AttributeError as ex:
raise ValueError(f"Config entry not loaded: {entry.entry_id}") from ex
service = await auth.get_resource() service = await auth.get_resource()
_settings = { _settings = {