Skip to content

Commit

Permalink
Fix Twitch auth token refresh (#112833)
Browse files Browse the repository at this point in the history
* Fix for expired token

* Add auth token refresh.

* Eliminate extra auth call

* Fixed mock client

---------

Co-authored-by: Jonny Bergdahl <bergdahl@users.noreply.github.com>
  • Loading branch information
2 people authored and frenck committed Mar 14, 2024
1 parent b88cdd7 commit eb04365
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 9 deletions.
7 changes: 5 additions & 2 deletions homeassistant/components/twitch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
async_get_config_entry_implementation,
)

from .const import DOMAIN, OAUTH_SCOPES, PLATFORMS
from .const import CLIENT, DOMAIN, OAUTH_SCOPES, PLATFORMS, SESSION


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
Expand Down Expand Up @@ -45,7 +45,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
client.auto_refresh_auth = False
await client.set_user_authentication(access_token, scope=OAUTH_SCOPES)

hass.data.setdefault(DOMAIN, {})[entry.entry_id] = client
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
CLIENT: client,
SESSION: session,
}

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

Expand Down
2 changes: 2 additions & 0 deletions homeassistant/components/twitch/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,7 @@

DOMAIN = "twitch"
CONF_CHANNELS = "channels"
CLIENT = "client"
SESSION = "session"

OAUTH_SCOPES = [AuthScope.USER_READ_SUBSCRIPTIONS, AuthScope.USER_READ_FOLLOWS]
29 changes: 22 additions & 7 deletions homeassistant/components/twitch/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from .const import CONF_CHANNELS, DOMAIN, LOGGER, OAUTH_SCOPES
from .const import CLIENT, CONF_CHANNELS, DOMAIN, LOGGER, OAUTH_SCOPES, SESSION

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
Expand All @@ -51,6 +52,8 @@
STATE_OFFLINE = "offline"
STATE_STREAMING = "streaming"

PARALLEL_UPDATES = 1


def chunk_list(lst: list, chunk_size: int) -> list[list]:
"""Split a list into chunks of chunk_size."""
Expand Down Expand Up @@ -97,7 +100,8 @@ async def async_setup_entry(
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize entries."""
client = hass.data[DOMAIN][entry.entry_id]
client = hass.data[DOMAIN][entry.entry_id][CLIENT]
session = hass.data[DOMAIN][entry.entry_id][SESSION]

channels = entry.options[CONF_CHANNELS]

Expand All @@ -107,7 +111,7 @@ async def async_setup_entry(
for chunk in chunk_list(channels, 100):
entities.extend(
[
TwitchSensor(channel, client)
TwitchSensor(channel, session, client)
async for channel in client.get_users(logins=chunk)
]
)
Expand All @@ -120,8 +124,11 @@ class TwitchSensor(SensorEntity):

_attr_icon = ICON

def __init__(self, channel: TwitchUser, client: Twitch) -> None:
def __init__(
self, channel: TwitchUser, session: OAuth2Session, client: Twitch
) -> None:
"""Initialize the sensor."""
self._session = session
self._client = client
self._channel = channel
self._enable_user_auth = client.has_required_auth(AuthType.USER, OAUTH_SCOPES)
Expand All @@ -130,9 +137,17 @@ def __init__(self, channel: TwitchUser, client: Twitch) -> None:

async def async_update(self) -> None:
"""Update device state."""
followers = (await self._client.get_channel_followers(self._channel.id)).total
await self._session.async_ensure_token_valid()
await self._client.set_user_authentication(
self._session.token["access_token"],
OAUTH_SCOPES,
self._session.token["refresh_token"],
False,
)
followers = await self._client.get_channel_followers(self._channel.id)

self._attr_extra_state_attributes = {
ATTR_FOLLOWING: followers,
ATTR_FOLLOWING: followers.total,
ATTR_VIEWS: self._channel.view_count,
}
if self._enable_user_auth:
Expand Down Expand Up @@ -166,7 +181,7 @@ async def _async_add_user_attributes(self) -> None:
self._attr_extra_state_attributes[ATTR_SUBSCRIPTION] = True
self._attr_extra_state_attributes[ATTR_SUBSCRIPTION_GIFTED] = sub.is_gift
except TwitchResourceNotFound:
LOGGER.debug("User is not subscribed")
LOGGER.debug("User is not subscribed to %s", self._channel.display_name)
except TwitchAPIException as exc:
LOGGER.error("Error response on check_user_subscription: %s", exc)

Expand Down
1 change: 1 addition & 0 deletions tests/components/twitch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ async def set_user_authentication(
self,
token: str,
scope: list[AuthScope],
refresh_token: str | None = None,
validate: bool = True,
) -> None:
"""Set user authentication."""
Expand Down

0 comments on commit eb04365

Please sign in to comment.