async def async_setup_entry(hass, entry) -> bool:
    """Set up Trakt from config entry."""

    config_flow.TraktOAuth2FlowHandler.async_register_implementation(
        hass,
        config_entry_oauth2_flow.LocalOAuth2Implementation(
            hass,
            DOMAIN,
            entry.data[CONF_CLIENT_ID],
            entry.data[CONF_CLIENT_SECRET],
            OAUTH2_AUTHORIZE,
            OAUTH2_TOKEN,
        ),
    )

    implementation = await config_entry_oauth2_flow.async_get_config_entry_implementation(
        hass, entry
    )

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
    await session.async_ensure_token_valid()

    coordinator = Trakt_Data(hass, entry, session)
    if not await coordinator.async_setup():
        return False

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

    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(entry, "sensor")
    )

    return True
Esempio n. 2
0
    def __init__(
        self,
        hass: core.HomeAssistant,
        config_entry: config_entries.ConfigEntry,
        implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation,
    ) -> None:
        """Initialize the HomePlusControlAsyncApi object.

        Initialize the authenticated API for the Legrand Home+ Control component.

        Args:.
            hass (HomeAssistant): HomeAssistant core object.
            config_entry (ConfigEntry): ConfigEntry object that configures this API.
            implementation (AbstractOAuth2Implementation): OAuth2 implementation that handles AA
                                                           and token refresh.
        """
        self._oauth_session = config_entry_oauth2_flow.OAuth2Session(
            hass, config_entry, implementation)

        # Create the API authenticated client - external library
        super().__init__(
            subscription_key=implementation.subscription_key,
            oauth_client=aiohttp_client.async_get_clientsession(hass),
            update_intervals=DEFAULT_UPDATE_INTERVALS,
        )
Esempio n. 3
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up yolink from a config entry."""
    hass.data.setdefault(DOMAIN, {})
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)

    auth_mgr = api.ConfigEntryAuth(
        hass, aiohttp_client.async_get_clientsession(hass), session)

    yolink_http_client = YoLinkClient(auth_mgr)
    yolink_mqtt_client = MqttClient(auth_mgr)
    coordinator = YoLinkCoordinator(hass, yolink_http_client,
                                    yolink_mqtt_client)
    await coordinator.init_coordinator()
    try:
        await coordinator.async_config_entry_first_refresh()
    except ConfigEntryNotReady as ex:
        _LOGGER.error("Fetching initial data failed: %s", ex)

    hass.data[DOMAIN][entry.entry_id] = {
        ATTR_CLIENT: yolink_http_client,
        ATTR_MQTT_CLIENT: yolink_mqtt_client,
        ATTR_COORDINATOR: coordinator,
    }
    hass.config_entries.async_setup_platforms(entry, PLATFORMS)
    return True
Esempio n. 4
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Microsoft Graph from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    auth = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass), session)

    client = GraphApiClient(auth)

    coordinator = GraphUpdateCoordinator(hass, client)
    await coordinator.async_refresh()

    hass.data[DOMAIN][entry.entry_id] = {
        "client": GraphApiClient(auth),
        "coordinator": coordinator,
    }

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Esempio n. 5
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Nest from a config entry with dispatch between old/new flows."""

    if DATA_SDM not in entry.data:
        return await async_setup_legacy_entry(hass, entry)

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    config = hass.data[DOMAIN][DATA_NEST_CONFIG]

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    auth = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass),
        session,
        API_URL,
    )
    subscriber = GoogleNestSubscriber(auth, config[CONF_PROJECT_ID],
                                      config[CONF_SUBSCRIBER_ID])
    subscriber.set_update_callback(SignalUpdateCallback(hass))
    asyncio.create_task(subscriber.start_async())
    hass.data[DOMAIN][entry.entry_id] = subscriber

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Esempio n. 6
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up xbox from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry
        )
    )
    session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
    auth = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass), session
    )

    client = XboxLiveClient(auth)
    consoles: SmartglassConsoleList = await client.smartglass.get_console_list()
    _LOGGER.debug(
        "Found %d consoles: %s",
        len(consoles.result),
        consoles.dict(),
    )

    coordinator = XboxUpdateCoordinator(hass, client, consoles)
    await coordinator.async_config_entry_first_refresh()

    hass.data[DOMAIN][entry.entry_id] = {
        "client": XboxLiveClient(auth),
        "consoles": consoles,
        "coordinator": coordinator,
    }

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 7
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up config entry."""
    if CONF_TOKEN not in entry.data:
        raise ConfigEntryAuthFailed

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)

    neato_session = api.ConfigEntryAuth(hass, entry, session)
    hass.data[NEATO_DOMAIN][entry.entry_id] = neato_session
    hub = NeatoHub(hass, Account(neato_session))

    try:
        await hass.async_add_executor_job(hub.update_robots)
    except NeatoException as ex:
        _LOGGER.debug("Failed to connect to Neato API")
        raise ConfigEntryNotReady from ex

    hass.data[NEATO_LOGIN] = hub

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 8
0
async def test_oauth_session_refresh_failure(hass, flow_handler, local_impl,
                                             aioclient_mock):
    """Test the OAuth2 session helper when no refresh is needed."""
    flow_handler.async_register_implementation(hass, local_impl)

    aioclient_mock.post(TOKEN_URL, status=400)

    config_entry = MockConfigEntry(
        domain=TEST_DOMAIN,
        data={
            "auth_implementation": TEST_DOMAIN,
            "token": {
                "refresh_token": REFRESH_TOKEN,
                "access_token": ACCESS_TOKEN_1,
                # Already expired, requires a refresh
                "expires_in": -500,
                "expires_at": time.time() - 500,
                "token_type": "bearer",
                "random_other_data": "should_stay",
            },
        },
    )

    session = config_entry_oauth2_flow.OAuth2Session(hass, config_entry,
                                                     local_impl)
    with pytest.raises(aiohttp.client_exceptions.ClientResponseError):
        await session.async_request("post", "https://example.com")
Esempio n. 9
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Zonneplan from a config entry."""

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    zonneplanApi = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass), session)

    hass.data[DOMAIN][entry.entry_id] = zonneplanApi

    coordinator = ZonneplanUpdateCoordinator(hass, zonneplanApi)
    await coordinator.async_refresh()

    hass.data[DOMAIN][entry.entry_id] = {
        "api": zonneplanApi,
        "coordinator": coordinator,
    }

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Esempio n. 10
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Nest from a config entry with dispatch between old/new flows."""

    if DATA_SDM not in entry.data:
        return await async_setup_legacy_entry(hass, entry)

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry
        )
    )

    config = hass.data[DOMAIN][DATA_NEST_CONFIG]

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
    auth = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass),
        session,
        config[CONF_CLIENT_ID],
        config[CONF_CLIENT_SECRET],
    )
    subscriber = GoogleNestSubscriber(
        auth, config[CONF_PROJECT_ID], config[CONF_SUBSCRIBER_ID]
    )
    callback = SignalUpdateCallback(hass)
    subscriber.set_update_callback(callback.async_handle_event)

    try:
        await subscriber.start_async()
    except AuthException as err:
        _LOGGER.debug("Subscriber authentication error: %s", err)
        raise ConfigEntryAuthFailed from err
    except ConfigurationException as err:
        _LOGGER.error("Configuration error: %s", err)
        subscriber.stop_async()
        return False
    except GoogleNestException as err:
        if DATA_NEST_UNAVAILABLE not in hass.data[DOMAIN]:
            _LOGGER.error("Subscriber error: %s", err)
            hass.data[DOMAIN][DATA_NEST_UNAVAILABLE] = True
        subscriber.stop_async()
        raise ConfigEntryNotReady from err

    try:
        await subscriber.async_get_device_manager()
    except GoogleNestException as err:
        if DATA_NEST_UNAVAILABLE not in hass.data[DOMAIN]:
            _LOGGER.error("Device manager error: %s", err)
            hass.data[DOMAIN][DATA_NEST_UNAVAILABLE] = True
        subscriber.stop_async()
        raise ConfigEntryNotReady from err

    hass.data[DOMAIN].pop(DATA_NEST_UNAVAILABLE, None)
    hass.data[DOMAIN][DATA_SUBSCRIBER] = subscriber

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 11
0
async def test_api(hass):
    """Test API."""
    MOCK_ENTRY.add_to_hass(hass)
    implementation = ZoomOAuth2Implementation(
        hass,
        DOMAIN,
        MOCK_ENTRY.data[CONF_CLIENT_ID],
        MOCK_ENTRY.data[CONF_CLIENT_SECRET],
        OAUTH2_AUTHORIZE,
        OAUTH2_TOKEN,
        MOCK_ENTRY.data[CONF_VERIFICATION_TOKEN],
    )
    api = ZoomAPI(
        config_entry_oauth2_flow.OAuth2Session(hass, MOCK_ENTRY,
                                               implementation))

    assert await api.async_get_access_token() == MOCK_TOKEN

    with patch(
            "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_request",
            return_value=AiohttpClientMockResponse("get",
                                                   "zoom_url",
                                                   status=HTTP_OK,
                                                   json={
                                                       "id": "test",
                                                       "first_name": "test"
                                                   }),
    ):
        await api.async_get_contact_user_profile("test")

    with patch(
            "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_request",
            return_value=AiohttpClientMockResponse(
                "get",
                "zoom_url",
                status=HTTP_OK,
                json={
                    "next_page_token": "",
                    "contacts": [{
                        "id": "test",
                        "first_name": "test"
                    }],
                },
            ),
    ):
        await api.async_get_contacts()

    with patch(
            "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_request",
            return_value=AiohttpClientMockResponse("get",
                                                   "zoom_url",
                                                   status=HTTP_OK,
                                                   json={
                                                       "id": "test",
                                                       "first_name": "test"
                                                   }),
    ):
        await api.async_get_my_user_profile()
 def __init__(
     self,
     hass: core.HomeAssistant,
     config_entry: config_entries.ConfigEntry,
     impl: config_entry_oauth2_flow.AbstractOAuth2Implementation,
 ):
     """Initialize EnerTalk Auth."""
     self.hass = hass
     self.session = config_entry_oauth2_flow.OAuth2Session(
         hass, config_entry, impl)
Esempio n. 13
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Google from a config entry."""
    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {}

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry
        )
    )
    session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
    # Force a token refresh to fix a bug where tokens were persisted with
    # expires_in (relative time delta) and expires_at (absolute time) swapped.
    # A google session token typically only lasts a few days between refresh.
    now = datetime.now()
    if session.token["expires_at"] >= (now + timedelta(days=365)).timestamp():
        session.token["expires_in"] = 0
        session.token["expires_at"] = now.timestamp()
    try:
        await session.async_ensure_token_valid()
    except aiohttp.ClientResponseError as err:
        if 400 <= err.status < 500:
            raise ConfigEntryAuthFailed from err
        raise ConfigEntryNotReady from err
    except aiohttp.ClientError as err:
        raise ConfigEntryNotReady from err

    if not async_entry_has_scopes(hass, entry):
        raise ConfigEntryAuthFailed(
            "Required scopes are not available, reauth required"
        )
    calendar_service = GoogleCalendarService(
        ApiAuthImpl(async_get_clientsession(hass), session)
    )
    hass.data[DOMAIN][entry.entry_id][DATA_SERVICE] = calendar_service

    if entry.unique_id is None:
        try:
            primary_calendar = await calendar_service.async_get_calendar("primary")
        except AuthException as err:
            raise ConfigEntryAuthFailed from err
        except ApiException as err:
            raise ConfigEntryNotReady from err
        else:
            hass.config_entries.async_update_entry(entry, unique_id=primary_calendar.id)

    # Only expose the add event service if we have the correct permissions
    if get_feature_access(hass, entry) is FeatureAccess.read_write:
        await async_setup_add_event_service(hass, calendar_service)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    entry.async_on_unload(entry.add_update_listener(async_reload_entry))

    return True
Esempio n. 14
0
 def __init__(
     self,
     hass: core.HomeAssistant,
     config_entry: config_entries.ConfigEntry,
     implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation,
 ):
     """Initialize Netatmo Auth."""
     self.hass = hass
     self.session = config_entry_oauth2_flow.OAuth2Session(
         hass, config_entry, implementation)
     super().__init__(token=self.session.token)
Esempio n. 15
0
 def __init__(
     self,
     hass: core.HomeAssistant,
     config_entry: config_entries.ConfigEntry,
     implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation,
 ):
     """Initialize the Config Entry Somfy API."""
     self.hass = hass
     self.config_entry = config_entry
     self.session = config_entry_oauth2_flow.OAuth2Session(
         hass, config_entry, implementation)
Esempio n. 16
0
 def __init__(
     self,
     hass: core.HomeAssistant,
     config_entry: config_entries.ConfigEntry,
     implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation,
 ) -> None:
     """Initialize Neato Botvac Auth."""
     self.hass = hass
     self.session = config_entry_oauth2_flow.OAuth2Session(
         hass, config_entry, implementation)
     super().__init__(self.session.token, vendor=pybotvac.Neato())
Esempio n. 17
0
    def __init__(self, hass: core.HomeAssistant,
                 config_entry: config_entries.ConfigEntry,
                 implementation: config_entry_oauth2_flow.
                 AbstractOAuth2Implementation):
        """Initialize Home Connect Auth."""

        self.hass = hass
        self.config_entry = config_entry
        self.session = config_entry_oauth2_flow.OAuth2Session(
            hass, config_entry, implementation)
        super().__init__(self.session.token)
        self.devices = []
Esempio n. 18
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Google from a config entry."""
    hass.data.setdefault(DOMAIN, {})
    async_upgrade_entry(hass, entry)
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry
        )
    )
    session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
    # Force a token refresh to fix a bug where tokens were persisted with
    # expires_in (relative time delta) and expires_at (absolute time) swapped.
    # A google session token typically only lasts a few days between refresh.
    now = datetime.now()
    if session.token["expires_at"] >= (now + timedelta(days=365)).timestamp():
        session.token["expires_in"] = 0
        session.token["expires_at"] = now.timestamp()
    try:
        await session.async_ensure_token_valid()
    except aiohttp.ClientResponseError as err:
        if 400 <= err.status < 500:
            raise ConfigEntryAuthFailed from err
        raise ConfigEntryNotReady from err
    except aiohttp.ClientError as err:
        raise ConfigEntryNotReady from err

    access = FeatureAccess[entry.options[CONF_CALENDAR_ACCESS]]
    token_scopes = session.token.get("scope", [])
    if access.scope not in token_scopes:
        _LOGGER.debug("Scope '%s' not in scopes '%s'", access.scope, token_scopes)
        raise ConfigEntryAuthFailed(
            "Required scopes are not available, reauth required"
        )
    calendar_service = GoogleCalendarService(
        ApiAuthImpl(async_get_clientsession(hass), session)
    )
    hass.data[DOMAIN][DATA_SERVICE] = calendar_service

    await async_setup_services(hass, calendar_service)
    # Only expose the add event service if we have the correct permissions
    if access is FeatureAccess.read_write:
        await async_setup_add_event_service(hass, calendar_service)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    # Reload entry when options are updated
    entry.async_on_unload(entry.add_update_listener(async_reload_entry))

    return True
Esempio n. 19
0
async def async_setup_entry(hass: HomeAssistant,
                            entry: config_entries.ConfigEntry):
    """Set up Almond config entry."""
    websession = aiohttp_client.async_get_clientsession(hass)

    if entry.data["type"] == TYPE_LOCAL:
        auth = AlmondLocalAuth(entry.data["host"], websession)
    else:
        # OAuth2
        implementation = (
            await
            config_entry_oauth2_flow.async_get_config_entry_implementation(
                hass, entry))
        oauth_session = config_entry_oauth2_flow.OAuth2Session(
            hass, entry, implementation)
        auth = AlmondOAuth(entry.data["host"], websession, oauth_session)

    api = WebAlmondAPI(auth)
    agent = AlmondAgent(hass, api, entry)

    # Hass.io does its own configuration.
    if not entry.data.get("is_hassio"):
        # If we're not starting or local, set up Almond right away
        if hass.state != CoreState.not_running or entry.data[
                "type"] == TYPE_LOCAL:
            await _configure_almond_for_ha(hass, entry, api)

        else:
            # OAuth2 implementations can potentially rely on the HA Cloud url.
            # This url is not be available until 30 seconds after boot.

            async def configure_almond(_now):
                try:
                    await _configure_almond_for_ha(hass, entry, api)
                except ConfigEntryNotReady:
                    _LOGGER.warning(
                        "Unable to configure Almond to connect to Home Assistant"
                    )

            async def almond_hass_start(_event):
                event.async_call_later(hass, ALMOND_SETUP_DELAY,
                                       configure_almond)

            hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START,
                                       almond_hass_start)

    conversation.async_set_agent(hass, agent)
    return True
Esempio n. 20
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Honeywell Lyric from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = aiohttp_client.async_get_clientsession(hass)
    oauth_session = config_entry_oauth2_flow.OAuth2Session(
        hass, entry, implementation)

    client = ConfigEntryLyricClient(session, oauth_session)

    client_id = hass.data[DOMAIN][CONF_CLIENT_ID]
    lyric = Lyric(client, client_id)

    async def async_update_data() -> Lyric:
        """Fetch data from Lyric."""
        try:
            async with async_timeout.timeout(60):
                await lyric.get_locations()
            return lyric
        except LYRIC_EXCEPTIONS as exception:
            raise UpdateFailed(exception) from exception

    coordinator = DataUpdateCoordinator(
        hass,
        _LOGGER,
        # Name of the data. For logging purposes.
        name="lyric_coordinator",
        update_method=async_update_data,
        # Polling interval. Will only be polled if there are subscribers.
        update_interval=timedelta(seconds=120),
    )

    hass.data[DOMAIN][entry.entry_id] = coordinator

    # Fetch initial data so we have data when entities subscribe
    await coordinator.async_refresh()
    if not coordinator.last_update_success:
        raise ConfigEntryNotReady

    for platform in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, platform))

    return True
Esempio n. 21
0
async def new_subscriber_with_impl(
    hass: HomeAssistant,
    entry: ConfigEntry,
    subscriber_id: str,
    implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation,
) -> GoogleNestSubscriber:
    """Create a GoogleNestSubscriber, used during ConfigFlow."""
    config = hass.data[DOMAIN][DATA_NEST_CONFIG]
    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    auth = AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass),
        session,
        config[CONF_CLIENT_ID],
        config[CONF_CLIENT_SECRET],
    )
    return GoogleNestSubscriber(auth, config[CONF_PROJECT_ID], subscriber_id)
Esempio n. 22
0
async def test_oauth_session_with_clock_slightly_out_of_sync(
        hass, flow_handler, local_impl, aioclient_mock):
    """Test the OAuth2 session helper when the remote clock is slightly out of sync."""
    flow_handler.async_register_implementation(hass, local_impl)

    aioclient_mock.post(TOKEN_URL,
                        json={
                            "access_token": ACCESS_TOKEN_2,
                            "expires_in": 19
                        })

    aioclient_mock.post("https://example.com", status=201)

    config_entry = MockConfigEntry(
        domain=TEST_DOMAIN,
        data={
            "auth_implementation": TEST_DOMAIN,
            "token": {
                "refresh_token": REFRESH_TOKEN,
                "access_token": ACCESS_TOKEN_1,
                "expires_in": 19,
                "expires_at": time.time() + 19,  # Forces a refresh,
                "token_type": "bearer",
                "random_other_data": "should_stay",
            },
        },
    )

    now = time.time()
    session = config_entry_oauth2_flow.OAuth2Session(hass, config_entry,
                                                     local_impl)
    resp = await session.async_request("post", "https://example.com")
    assert resp.status == 201

    # Refresh token, make request
    assert len(aioclient_mock.mock_calls) == 2

    assert (aioclient_mock.mock_calls[1][3]["authorization"] ==
            f"Bearer {ACCESS_TOKEN_2}")

    assert config_entry.data["token"]["refresh_token"] == REFRESH_TOKEN
    assert config_entry.data["token"]["access_token"] == ACCESS_TOKEN_2
    assert config_entry.data["token"]["expires_in"] == 19
    assert config_entry.data["token"]["random_other_data"] == "should_stay"
    assert round(config_entry.data["token"]["expires_at"] - now) == 19
Esempio n. 23
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Sonos Cloud from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    hass.data[DOMAIN][SESSION] = session

    url = "https://api.ws.sonos.com/control/api/v1/households"
    result = await session.async_request("get", url)
    json = await result.json()
    households = json.get("households")

    async def async_get_available_players(household):
        url = f"https://api.ws.sonos.com/control/api/v1/households/{household}/groups"
        result = await session.async_request("get", url)
        json = await result.json()
        _LOGGER.debug("Result: %s", json)
        all_players = json["players"]
        available_players = []

        for player in all_players:
            if "AUDIO_CLIP" in player["capabilities"]:
                available_players.append(player)
            else:
                _LOGGER.warning("%s (%s) does not support AUDIO_CLIP",
                                player["name"], player["id"])

        return available_players

    for household in households:
        household_id = household["id"]
        players = await async_get_available_players(household_id)
        _LOGGER.debug(
            "Adding players for household %s: %s",
            household_id,
            [player["name"] for player in players],
        )
        hass.data[DOMAIN][PLAYERS].extend(players)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 24
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Honeywell Lyric from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = aiohttp_client.async_get_clientsession(hass)
    oauth_session = config_entry_oauth2_flow.OAuth2Session(
        hass, entry, implementation)

    client = ConfigEntryLyricClient(session, oauth_session)

    client_id = hass.data[DOMAIN][CONF_CLIENT_ID]
    lyric = Lyric(client, client_id)

    async def async_update_data() -> Lyric:
        """Fetch data from Lyric."""
        await oauth_session.async_ensure_token_valid()
        try:
            async with async_timeout.timeout(60):
                await lyric.get_locations()
            return lyric
        except LyricAuthenticationException as exception:
            raise ConfigEntryAuthFailed from exception
        except (LyricException, ClientResponseError) as exception:
            raise UpdateFailed(exception) from exception

    coordinator = DataUpdateCoordinator(
        hass,
        _LOGGER,
        # Name of the data. For logging purposes.
        name="lyric_coordinator",
        update_method=async_update_data,
        # Polling interval. Will only be polled if there are subscribers.
        update_interval=timedelta(seconds=300),
    )

    hass.data[DOMAIN][entry.entry_id] = coordinator

    # Fetch initial data so we have data when entities subscribe
    await coordinator.async_config_entry_first_refresh()

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 25
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Nest from a config entry with dispatch between old/new flows."""

    if DATA_SDM not in entry.data:
        return await async_setup_legacy_entry(hass, entry)

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    config = hass.data[DOMAIN][DATA_NEST_CONFIG]

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    auth = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass),
        session,
        API_URL,
    )
    subscriber = GoogleNestSubscriber(auth, config[CONF_PROJECT_ID],
                                      config[CONF_SUBSCRIBER_ID])
    subscriber.set_update_callback(SignalUpdateCallback(hass))

    try:
        await subscriber.start_async()
    except GoogleNestException as err:
        _LOGGER.error("Subscriber error: %s", err)
        subscriber.stop_async()
        raise ConfigEntryNotReady from err

    try:
        await subscriber.async_get_device_manager()
    except GoogleNestException as err:
        _LOGGER.error("Device Manager error: %s", err)
        subscriber.stop_async()
        raise ConfigEntryNotReady from err

    hass.data[DOMAIN][DATA_SUBSCRIBER] = subscriber

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Esempio n. 26
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up NEW_NAME from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)

    # If using a requests-based API lib
    hass.data[DOMAIN][entry.entry_id] = api.ConfigEntryAuth(hass, session)

    # If using an aiohttp-based API lib
    hass.data[DOMAIN][entry.entry_id] = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass), session)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Home Connect from a config entry."""
    implementation = await config_entry_oauth2_flow.async_get_config_entry_implementation(
        hass, entry
    )

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)

    hc = api.ConfigEntryAuth(hass, entry, session)

    hass.data[DOMAIN][entry.entry_id] = hc

    await update_all_devices(hass, entry)

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component)
        )

    return True
Esempio n. 28
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up SENZ from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))
    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    auth = SENZConfigEntryAuth(httpx_client.get_async_client(hass), session)
    senz_api = SENZAPI(auth)

    async def update_thermostats() -> dict[str, Thermostat]:
        """Fetch SENZ thermostats data."""
        try:
            thermostats = await senz_api.get_thermostats()
        except RequestError as err:
            raise UpdateFailed from err
        return {
            thermostat.serial_number: thermostat
            for thermostat in thermostats
        }

    try:
        account = await senz_api.get_account()
    except RequestError as err:
        raise ConfigEntryNotReady from err

    coordinator = SENZDataUpdateCoordinator(
        hass,
        _LOGGER,
        name=account.username,
        update_interval=UPDATE_INTERVAL,
        update_method=update_thermostats,
    )

    await coordinator.async_config_entry_first_refresh()

    hass.data[DOMAIN][entry.entry_id] = coordinator

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 29
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up NEW_NAME from a config entry."""
    implementation = await config_entry_oauth2_flow.async_get_config_entry_implementation(
        hass, entry)

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)

    # If using a requests-based API lib
    hass.data[DOMAIN][entry.entry_id] = api.ConfigEntryAuth(
        hass, entry, session)

    # If using an aiohttp-based API lib
    hass.data[DOMAIN][entry.entry_id] = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass), session)

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Esempio n. 30
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Google from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))
    assert isinstance(implementation, DeviceAuth)
    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    required_scope = hass.data[DOMAIN][DATA_CONFIG][CONF_CALENDAR_ACCESS].scope
    if required_scope not in session.token.get("scope", []):
        raise ConfigEntryAuthFailed(
            "Required scopes are not available, reauth required")
    calendar_service = GoogleCalendarService(hass, session)
    hass.data[DOMAIN][DATA_SERVICE] = calendar_service

    await async_setup_services(hass, hass.data[DOMAIN][DATA_CONFIG],
                               calendar_service)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True