Example #1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Spotify from a config entry."""
    implementation = await async_get_config_entry_implementation(hass, entry)
    session = OAuth2Session(hass, entry, implementation)

    try:
        await session.async_ensure_token_valid()
    except aiohttp.ClientError as err:
        raise ConfigEntryNotReady from err

    spotify = Spotify(auth=session.token["access_token"])

    try:
        current_user = await hass.async_add_executor_job(spotify.me)
    except SpotifyException as err:
        raise ConfigEntryNotReady from err

    if not current_user:
        raise ConfigEntryNotReady

    async def _update_devices() -> list[dict[str, Any]]:
        if not session.valid_token:
            await session.async_ensure_token_valid()
            await hass.async_add_executor_job(spotify.set_auth,
                                              session.token["access_token"])

        try:
            devices: dict[str, Any] | None = await hass.async_add_executor_job(
                spotify.devices)
        except (requests.RequestException, SpotifyException) as err:
            raise UpdateFailed from err

        if devices is None:
            return []

        return devices.get("devices", [])

    device_coordinator: DataUpdateCoordinator[list[dict[
        str, Any]]] = DataUpdateCoordinator(
            hass,
            LOGGER,
            name=f"{entry.title} Devices",
            update_interval=timedelta(minutes=5),
            update_method=_update_devices,
        )
    await device_coordinator.async_config_entry_first_refresh()

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = HomeAssistantSpotifyData(
        client=spotify,
        current_user=current_user,
        devices=device_coordinator,
        session=session,
    )

    if not set(session.token["scope"].split(" ")).issuperset(SPOTIFY_SCOPES):
        raise ConfigEntryAuthFailed

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
    return True
Example #2
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Spotify from a config entry."""
    implementation = await async_get_config_entry_implementation(hass, entry)
    session = OAuth2Session(hass, entry, implementation)

    try:
        await session.async_ensure_token_valid()
    except aiohttp.ClientError as err:
        raise ConfigEntryNotReady from err

    spotify = Spotify(auth=session.token["access_token"])

    try:
        current_user = await hass.async_add_executor_job(spotify.me)
    except SpotifyException as err:
        raise ConfigEntryNotReady from err

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        DATA_SPOTIFY_CLIENT: spotify,
        DATA_SPOTIFY_ME: current_user,
        DATA_SPOTIFY_SESSION: session,
    }

    if not set(session.token["scope"].split(" ")).issuperset(SPOTIFY_SCOPES):
        raise ConfigEntryAuthFailed

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)
    return True
Example #3
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Spotify from a config entry."""
    implementation = await async_get_config_entry_implementation(hass, entry)
    session = OAuth2Session(hass, entry, implementation)
    await session.async_ensure_token_valid()
    spotify = Spotify(auth=session.token["access_token"])

    try:
        current_user = await hass.async_add_executor_job(spotify.me)
    except SpotifyException as err:
        raise ConfigEntryNotReady from err

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        DATA_SPOTIFY_CLIENT: spotify,
        DATA_SPOTIFY_ME: current_user,
        DATA_SPOTIFY_SESSION: session,
    }

    if not set(session.token["scope"].split(" ")).issuperset(SPOTIFY_SCOPES):
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN,
                context={"source": "reauth"},
                data=entry.data,
            ))

    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(entry,
                                                      MEDIA_PLAYER_DOMAIN))
    return True
Example #4
0
 def __init__(
     self,
     hass: HomeAssistant,
     config_entry: ConfigEntry,
     implementation: AbstractOAuth2Implementation,
 ):
     """Initialize object."""
     self._hass = hass
     self._config_entry = config_entry
     self._implementation = implementation
     self.session = OAuth2Session(hass, config_entry, implementation)
Example #5
0
 def __init__(
     self,
     hass: core.HomeAssistant,
     config_entry: config_entries.ConfigEntry,
     implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation,
 ):
     self.hass = hass
     self.config_entry = config_entry
     self.session = OAuth2Session(hass, config_entry, implementation)
     self._oauth = RequestOAuth2Session(token=self.session.token)
     self.organization_id = hass.data[DOMAIN].get(CONF_ORGANIZATION_ID,
                                                  None)
     self.locations = []
     self.devices = []
Example #6
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Geocaching from a config entry."""
    implementation = await async_get_config_entry_implementation(hass, entry)

    oauth_session = OAuth2Session(hass, entry, implementation)
    coordinator = GeocachingDataUpdateCoordinator(hass,
                                                  entry=entry,
                                                  session=oauth_session)

    await coordinator.async_config_entry_first_refresh()

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = coordinator
    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Example #7
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Toon from a config entry."""
    implementation = await async_get_config_entry_implementation(hass, entry)
    session = OAuth2Session(hass, entry, implementation)

    coordinator = ToonDataUpdateCoordinator(hass, entry=entry, session=session)
    await coordinator.toon.activate_agreement(
        agreement_id=entry.data[CONF_AGREEMENT_ID]
    )
    await coordinator.async_refresh()

    if not coordinator.last_update_success:
        raise ConfigEntryNotReady

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = coordinator

    # Register device for the Meter Adapter, since it will have no entities.
    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=entry.entry_id,
        identifiers={
            (DOMAIN, coordinator.data.agreement.agreement_id, "meter_adapter")
        },
        manufacturer="Eneco",
        name="Meter Adapter",
        via_device=(DOMAIN, coordinator.data.agreement.agreement_id),
    )

    # Spin up the platforms
    for component in ENTITY_COMPONENTS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component)
        )

    # If Home Assistant is already in a running state, register the webhook
    # immediately, else trigger it after Home Assistant has finished starting.
    if hass.state == CoreState.running:
        await coordinator.register_webhook()
    else:
        hass.bus.async_listen_once(
            EVENT_HOMEASSISTANT_STARTED, coordinator.register_webhook
        )

    return True
Example #8
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Spotify from a config entry."""
    implementation = await async_get_config_entry_implementation(hass, entry)
    session = OAuth2Session(hass, entry, implementation)
    await session.async_ensure_token_valid()
    spotify = Spotify(auth=session.token["access_token"])

    try:
        current_user = await hass.async_add_executor_job(spotify.me)
    except SpotifyException:
        raise ConfigEntryNotReady

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        DATA_SPOTIFY_CLIENT: spotify,
        DATA_SPOTIFY_ME: current_user,
        DATA_SPOTIFY_SESSION: session,
    }

    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(entry,
                                                      MEDIA_PLAYER_DOMAIN))
    return True