init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1,97 @@
"""The GitHub integration."""
from __future__ import annotations
from aiogithubapi import GitHubAPI
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ACCESS_TOKEN, Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.aiohttp_client import (
SERVER_SOFTWARE,
async_get_clientsession,
)
from .const import CONF_REPOSITORIES, DOMAIN, LOGGER
from .coordinator import GitHubDataUpdateCoordinator
PLATFORMS: list[Platform] = [Platform.SENSOR]
type GithubConfigEntry = ConfigEntry[dict[str, GitHubDataUpdateCoordinator]]
async def async_setup_entry(hass: HomeAssistant, entry: GithubConfigEntry) -> bool:
"""Set up GitHub from a config entry."""
client = GitHubAPI(
token=entry.data[CONF_ACCESS_TOKEN],
session=async_get_clientsession(hass),
client_name=SERVER_SOFTWARE,
)
repositories: list[str] = entry.options[CONF_REPOSITORIES]
entry.runtime_data = {}
for repository in repositories:
coordinator = GitHubDataUpdateCoordinator(
hass=hass,
client=client,
repository=repository,
)
await coordinator.async_config_entry_first_refresh()
if not entry.pref_disable_polling:
await coordinator.subscribe()
entry.runtime_data[repository] = coordinator
async_cleanup_device_registry(hass=hass, entry=entry)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
@callback
def async_cleanup_device_registry(
hass: HomeAssistant,
entry: ConfigEntry,
) -> None:
"""Remove entries form device registry if we no longer track the repository."""
device_registry = dr.async_get(hass)
devices = dr.async_entries_for_config_entry(
registry=device_registry,
config_entry_id=entry.entry_id,
)
for device in devices:
for item in device.identifiers:
if item[0] == DOMAIN and item[1] not in entry.options[CONF_REPOSITORIES]:
LOGGER.debug(
(
"Unlinking device %s for untracked repository %s from config"
" entry %s"
),
device.id,
item[1],
entry.entry_id,
)
device_registry.async_update_device(
device.id, remove_config_entry_id=entry.entry_id
)
break
async def async_unload_entry(hass: HomeAssistant, entry: GithubConfigEntry) -> bool:
"""Unload a config entry."""
repositories = entry.runtime_data
for coordinator in repositories.values():
coordinator.unsubscribe()
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)

View File

@@ -0,0 +1,250 @@
"""Config flow for GitHub integration."""
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Any
from aiogithubapi import (
GitHubAPI,
GitHubDeviceAPI,
GitHubException,
GitHubLoginDeviceModel,
GitHubLoginOauthModel,
)
from aiogithubapi.const import OAUTH_USER_LOGIN
import voluptuous as vol
from homeassistant.config_entries import (
ConfigEntry,
ConfigFlow,
ConfigFlowResult,
OptionsFlow,
)
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import (
SERVER_SOFTWARE,
async_get_clientsession,
)
import homeassistant.helpers.config_validation as cv
from .const import CLIENT_ID, CONF_REPOSITORIES, DEFAULT_REPOSITORIES, DOMAIN, LOGGER
async def get_repositories(hass: HomeAssistant, access_token: str) -> list[str]:
"""Return a list of repositories that the user owns or has starred."""
client = GitHubAPI(token=access_token, session=async_get_clientsession(hass))
repositories = set()
async def _get_starred_repositories() -> None:
response = await client.user.starred(params={"per_page": 100})
if not response.is_last_page:
results = await asyncio.gather(
*(
client.user.starred(
params={"per_page": 100, "page": page_number},
)
for page_number in range(
response.next_page_number, response.last_page_number + 1
)
)
)
for result in results:
response.data.extend(result.data)
repositories.update(response.data)
async def _get_personal_repositories() -> None:
response = await client.user.repos(params={"per_page": 100})
if not response.is_last_page:
results = await asyncio.gather(
*(
client.user.repos(
params={"per_page": 100, "page": page_number},
)
for page_number in range(
response.next_page_number, response.last_page_number + 1
)
)
)
for result in results:
response.data.extend(result.data)
repositories.update(response.data)
try:
await asyncio.gather(
*(
_get_starred_repositories(),
_get_personal_repositories(),
)
)
except GitHubException:
return DEFAULT_REPOSITORIES
if len(repositories) == 0:
return DEFAULT_REPOSITORIES
return sorted(
(repo.full_name for repo in repositories),
key=str.casefold,
)
class GitHubConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for GitHub."""
VERSION = 1
login_task: asyncio.Task | None = None
def __init__(self) -> None:
"""Initialize."""
self._device: GitHubDeviceAPI | None = None
self._login: GitHubLoginOauthModel | None = None
self._login_device: GitHubLoginDeviceModel | None = None
async def async_step_user(
self,
user_input: dict[str, Any] | None = None,
) -> ConfigFlowResult:
"""Handle the initial step."""
if self._async_current_entries():
return self.async_abort(reason="already_configured")
return await self.async_step_device(user_input)
async def async_step_device(
self,
user_input: dict[str, Any] | None = None,
) -> ConfigFlowResult:
"""Handle device steps."""
async def _wait_for_login() -> None:
if TYPE_CHECKING:
# mypy is not aware that we can't get here without having these set already
assert self._device is not None
assert self._login_device is not None
response = await self._device.activation(
device_code=self._login_device.device_code
)
self._login = response.data
if not self._device:
self._device = GitHubDeviceAPI(
client_id=CLIENT_ID,
session=async_get_clientsession(self.hass),
client_name=SERVER_SOFTWARE,
)
try:
response = await self._device.register()
self._login_device = response.data
except GitHubException as exception:
LOGGER.exception(exception)
return self.async_abort(reason="could_not_register")
if self.login_task is None:
self.login_task = self.hass.async_create_task(_wait_for_login())
if self.login_task.done():
if self.login_task.exception():
return self.async_show_progress_done(next_step_id="could_not_register")
return self.async_show_progress_done(next_step_id="repositories")
if TYPE_CHECKING:
# mypy is not aware that we can't get here without having this set already
assert self._login_device is not None
return self.async_show_progress(
step_id="device",
progress_action="wait_for_device",
description_placeholders={
"url": OAUTH_USER_LOGIN,
"code": self._login_device.user_code,
},
progress_task=self.login_task,
)
async def async_step_repositories(
self,
user_input: dict[str, Any] | None = None,
) -> ConfigFlowResult:
"""Handle repositories step."""
if TYPE_CHECKING:
# mypy is not aware that we can't get here without having this set already
assert self._login is not None
if not user_input:
repositories = await get_repositories(self.hass, self._login.access_token)
return self.async_show_form(
step_id="repositories",
data_schema=vol.Schema(
{
vol.Required(CONF_REPOSITORIES): cv.multi_select(
{k: k for k in repositories}
),
}
),
)
return self.async_create_entry(
title="",
data={CONF_ACCESS_TOKEN: self._login.access_token},
options={CONF_REPOSITORIES: user_input[CONF_REPOSITORIES]},
)
async def async_step_could_not_register(
self,
user_input: dict[str, Any] | None = None,
) -> ConfigFlowResult:
"""Handle issues that need transition await from progress step."""
return self.async_abort(reason="could_not_register")
@staticmethod
@callback
def async_get_options_flow(
config_entry: ConfigEntry,
) -> OptionsFlowHandler:
"""Get the options flow for this handler."""
return OptionsFlowHandler()
class OptionsFlowHandler(OptionsFlow):
"""Handle a option flow for GitHub."""
async def async_step_init(
self,
user_input: dict[str, Any] | None = None,
) -> ConfigFlowResult:
"""Handle options flow."""
if not user_input:
configured_repositories: list[str] = self.config_entry.options[
CONF_REPOSITORIES
]
repositories = await get_repositories(
self.hass, self.config_entry.data[CONF_ACCESS_TOKEN]
)
# In case the user has removed a starred repository that is already tracked
for repository in configured_repositories:
if repository not in repositories:
repositories.append(repository)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(
CONF_REPOSITORIES,
default=configured_repositories,
): cv.multi_select({k: k for k in repositories}),
}
),
)
return self.async_create_entry(title="", data=user_input)

View File

@@ -0,0 +1,28 @@
"""Constants for the GitHub integration."""
from __future__ import annotations
from datetime import timedelta
from logging import Logger, getLogger
LOGGER: Logger = getLogger(__package__)
DOMAIN = "github"
CLIENT_ID = "1440cafcc86e3ea5d6a2"
DEFAULT_REPOSITORIES = ["home-assistant/core", "esphome/esphome"]
FALLBACK_UPDATE_INTERVAL = timedelta(hours=1, minutes=30)
CONF_REPOSITORIES = "repositories"
REFRESH_EVENT_TYPES = (
"CreateEvent",
"ForkEvent",
"IssuesEvent",
"PullRequestEvent",
"PushEvent",
"ReleaseEvent",
"WatchEvent",
)

View File

@@ -0,0 +1,165 @@
"""Custom data update coordinator for the GitHub integration."""
from __future__ import annotations
from typing import Any
from aiogithubapi import (
GitHubAPI,
GitHubConnectionException,
GitHubEventModel,
GitHubException,
GitHubRatelimitException,
GitHubResponseModel,
)
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import FALLBACK_UPDATE_INTERVAL, LOGGER, REFRESH_EVENT_TYPES
GRAPHQL_REPOSITORY_QUERY = """
query ($owner: String!, $repository: String!) {
rateLimit {
cost
remaining
}
repository(owner: $owner, name: $repository) {
default_branch_ref: defaultBranchRef {
commit: target {
... on Commit {
message: messageHeadline
url
sha: oid
}
}
}
stargazers_count: stargazerCount
forks_count: forkCount
full_name: nameWithOwner
id: databaseId
watchers(first: 1) {
total: totalCount
}
discussion: discussions(
first: 1
orderBy: {field: CREATED_AT, direction: DESC}
) {
total: totalCount
discussions: nodes {
title
url
number
}
}
issue: issues(
first: 1
states: OPEN
orderBy: {field: CREATED_AT, direction: DESC}
) {
total: totalCount
issues: nodes {
title
url
number
}
}
pull_request: pullRequests(
first: 1
states: OPEN
orderBy: {field: CREATED_AT, direction: DESC}
) {
total: totalCount
pull_requests: nodes {
title
url
number
}
}
release: latestRelease {
name
url
tag: tagName
}
refs(
first: 1
refPrefix: "refs/tags/"
orderBy: {field: TAG_COMMIT_DATE, direction: DESC}
) {
tags: nodes {
name
target {
url: commitUrl
}
}
}
}
}
"""
class GitHubDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Data update coordinator for the GitHub integration."""
def __init__(
self,
hass: HomeAssistant,
client: GitHubAPI,
repository: str,
) -> None:
"""Initialize GitHub data update coordinator base class."""
self.repository = repository
self._client = client
self._last_response: GitHubResponseModel[dict[str, Any]] | None = None
self._subscription_id: str | None = None
self.data = {}
super().__init__(
hass,
LOGGER,
name=repository,
update_interval=FALLBACK_UPDATE_INTERVAL,
)
async def _async_update_data(self) -> GitHubResponseModel[dict[str, Any]]:
"""Update data."""
owner, repository = self.repository.split("/")
try:
response = await self._client.graphql(
query=GRAPHQL_REPOSITORY_QUERY,
variables={"owner": owner, "repository": repository},
)
except (GitHubConnectionException, GitHubRatelimitException) as exception:
# These are expected and we dont log anything extra
raise UpdateFailed(exception) from exception
except GitHubException as exception:
# These are unexpected and we log the trace to help with troubleshooting
LOGGER.exception(exception)
raise UpdateFailed(exception) from exception
self._last_response = response
return response.data["data"]["repository"]
async def _handle_event(self, event: GitHubEventModel) -> None:
"""Handle an event."""
if event.type in REFRESH_EVENT_TYPES:
await self.async_request_refresh()
@staticmethod
async def _handle_error(error: GitHubException) -> None:
"""Handle an error."""
LOGGER.error("An error occurred while processing new events - %s", error)
async def subscribe(self) -> None:
"""Subscribe to repository events."""
self._subscription_id = await self._client.repos.events.subscribe(
self.repository,
event_callback=self._handle_event,
error_callback=self._handle_error,
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.unsubscribe)
def unsubscribe(self, *args) -> None:
"""Unsubscribe to repository events."""
self._client.repos.events.unsubscribe(subscription_id=self._subscription_id)

View File

@@ -0,0 +1,43 @@
"""Diagnostics support for the GitHub integration."""
from __future__ import annotations
from typing import Any
from aiogithubapi import GitHubAPI, GitHubException
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import (
SERVER_SOFTWARE,
async_get_clientsession,
)
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
config_entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
data = {"options": {**config_entry.options}}
client = GitHubAPI(
token=config_entry.data[CONF_ACCESS_TOKEN],
session=async_get_clientsession(hass),
client_name=SERVER_SOFTWARE,
)
try:
rate_limit_response = await client.rate_limit()
except GitHubException as err:
data["rate_limit"] = {"error": str(err)}
else:
data["rate_limit"] = rate_limit_response.data.as_dict
repositories = config_entry.runtime_data
data["repositories"] = {}
for repository, coordinator in repositories.items():
data["repositories"][repository] = coordinator.data
return data

View File

@@ -0,0 +1,42 @@
{
"entity": {
"sensor": {
"discussions_count": {
"default": "mdi:forum"
},
"stargazers_count": {
"default": "mdi:star"
},
"subscribers_count": {
"default": "mdi:glasses"
},
"forks_count": {
"default": "mdi:source-fork"
},
"issues_count": {
"default": "mdi:github"
},
"pulls_count": {
"default": "mdi:source-pull"
},
"latest_commit": {
"default": "mdi:source-commit"
},
"latest_discussion": {
"default": "mdi:forum"
},
"latest_release": {
"default": "mdi:github"
},
"latest_issue": {
"default": "mdi:github"
},
"latest_pull_request": {
"default": "mdi:source-pull"
},
"latest_tag": {
"default": "mdi:tag"
}
}
}
}

View File

@@ -0,0 +1,10 @@
{
"domain": "github",
"name": "GitHub",
"codeowners": ["@timmo001", "@ludeeus"],
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/github",
"iot_class": "cloud_polling",
"loggers": ["aiogithubapi"],
"requirements": ["aiogithubapi==24.6.0"]
}

View File

@@ -0,0 +1,200 @@
"""Sensor platform for the GitHub integration."""
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any
from homeassistant.components.sensor import (
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import GithubConfigEntry
from .const import DOMAIN
from .coordinator import GitHubDataUpdateCoordinator
@dataclass(frozen=True, kw_only=True)
class GitHubSensorEntityDescription(SensorEntityDescription):
"""Describes GitHub issue sensor entity."""
value_fn: Callable[[dict[str, Any]], StateType]
attr_fn: Callable[[dict[str, Any]], Mapping[str, Any] | None] = lambda data: None
avabl_fn: Callable[[dict[str, Any]], bool] = lambda data: True
SENSOR_DESCRIPTIONS: tuple[GitHubSensorEntityDescription, ...] = (
GitHubSensorEntityDescription(
key="discussions_count",
translation_key="discussions_count",
entity_category=EntityCategory.DIAGNOSTIC,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data["discussion"]["total"],
),
GitHubSensorEntityDescription(
key="stargazers_count",
translation_key="stargazers_count",
entity_category=EntityCategory.DIAGNOSTIC,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data["stargazers_count"],
),
GitHubSensorEntityDescription(
key="subscribers_count",
translation_key="subscribers_count",
entity_category=EntityCategory.DIAGNOSTIC,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data["watchers"]["total"],
),
GitHubSensorEntityDescription(
key="forks_count",
translation_key="forks_count",
entity_category=EntityCategory.DIAGNOSTIC,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data["forks_count"],
),
GitHubSensorEntityDescription(
key="issues_count",
translation_key="issues_count",
entity_category=EntityCategory.DIAGNOSTIC,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data["issue"]["total"],
),
GitHubSensorEntityDescription(
key="pulls_count",
translation_key="pulls_count",
entity_category=EntityCategory.DIAGNOSTIC,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data["pull_request"]["total"],
),
GitHubSensorEntityDescription(
key="latest_commit",
translation_key="latest_commit",
value_fn=lambda data: data["default_branch_ref"]["commit"]["message"][:255],
attr_fn=lambda data: {
"sha": data["default_branch_ref"]["commit"]["sha"],
"url": data["default_branch_ref"]["commit"]["url"],
},
),
GitHubSensorEntityDescription(
key="latest_discussion",
translation_key="latest_discussion",
avabl_fn=lambda data: data["discussion"]["discussions"],
value_fn=lambda data: data["discussion"]["discussions"][0]["title"][:255],
attr_fn=lambda data: {
"url": data["discussion"]["discussions"][0]["url"],
"number": data["discussion"]["discussions"][0]["number"],
},
),
GitHubSensorEntityDescription(
key="latest_release",
translation_key="latest_release",
avabl_fn=lambda data: data["release"] is not None,
value_fn=lambda data: data["release"]["name"][:255],
attr_fn=lambda data: {
"url": data["release"]["url"],
"tag": data["release"]["tag"],
},
),
GitHubSensorEntityDescription(
key="latest_issue",
translation_key="latest_issue",
avabl_fn=lambda data: data["issue"]["issues"],
value_fn=lambda data: data["issue"]["issues"][0]["title"][:255],
attr_fn=lambda data: {
"url": data["issue"]["issues"][0]["url"],
"number": data["issue"]["issues"][0]["number"],
},
),
GitHubSensorEntityDescription(
key="latest_pull_request",
translation_key="latest_pull_request",
avabl_fn=lambda data: data["pull_request"]["pull_requests"],
value_fn=lambda data: data["pull_request"]["pull_requests"][0]["title"][:255],
attr_fn=lambda data: {
"url": data["pull_request"]["pull_requests"][0]["url"],
"number": data["pull_request"]["pull_requests"][0]["number"],
},
),
GitHubSensorEntityDescription(
key="latest_tag",
translation_key="latest_tag",
avabl_fn=lambda data: data["refs"]["tags"],
value_fn=lambda data: data["refs"]["tags"][0]["name"][:255],
attr_fn=lambda data: {
"url": data["refs"]["tags"][0]["target"]["url"],
},
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: GithubConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up GitHub sensor based on a config entry."""
repositories = entry.runtime_data
async_add_entities(
(
GitHubSensorEntity(coordinator, description)
for description in SENSOR_DESCRIPTIONS
for coordinator in repositories.values()
),
)
class GitHubSensorEntity(CoordinatorEntity[GitHubDataUpdateCoordinator], SensorEntity):
"""Defines a GitHub sensor entity."""
_attr_attribution = "Data provided by the GitHub API"
_attr_has_entity_name = True
entity_description: GitHubSensorEntityDescription
def __init__(
self,
coordinator: GitHubDataUpdateCoordinator,
entity_description: GitHubSensorEntityDescription,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator=coordinator)
self.entity_description = entity_description
self._attr_unique_id = f"{coordinator.data.get('id')}_{entity_description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, coordinator.repository)},
name=coordinator.data.get("full_name"),
manufacturer="GitHub",
configuration_url=f"https://github.com/{coordinator.repository}",
entry_type=DeviceEntryType.SERVICE,
)
@property
def available(self) -> bool:
"""Return True if entity is available."""
return (
super().available
and self.coordinator.data is not None
and self.entity_description.avabl_fn(self.coordinator.data)
)
@property
def native_value(self) -> StateType:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.coordinator.data)
@property
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return the extra state attributes."""
return self.entity_description.attr_fn(self.coordinator.data)

View File

@@ -0,0 +1,65 @@
{
"config": {
"step": {
"repositories": {
"title": "Configure repositories",
"data": {
"repositories": "Select repositories to track."
}
}
},
"progress": {
"wait_for_device": "Open {url}, and paste the following code to authorize the integration: \n```\n{code}\n```"
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]",
"could_not_register": "Could not register integration with GitHub"
}
},
"entity": {
"sensor": {
"discussions_count": {
"name": "Discussions",
"unit_of_measurement": "discussions"
},
"stargazers_count": {
"name": "Stars",
"unit_of_measurement": "stars"
},
"subscribers_count": {
"name": "Watchers",
"unit_of_measurement": "watchers"
},
"forks_count": {
"name": "Forks",
"unit_of_measurement": "forks"
},
"issues_count": {
"name": "Issues",
"unit_of_measurement": "issues"
},
"pulls_count": {
"name": "Pull requests",
"unit_of_measurement": "pull requests"
},
"latest_commit": {
"name": "Latest commit"
},
"latest_discussion": {
"name": "Latest discussion"
},
"latest_release": {
"name": "Latest release"
},
"latest_issue": {
"name": "Latest issue"
},
"latest_pull_request": {
"name": "Latest pull request"
},
"latest_tag": {
"name": "Latest tag"
}
}
}
}