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,63 @@
"""Support for RSS/Atom feeds."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_URL, Platform
from homeassistant.core import HomeAssistant
from homeassistant.util.hass_dict import HassKey
from .const import CONF_MAX_ENTRIES, DOMAIN
from .coordinator import FeedReaderCoordinator, StoredData
type FeedReaderConfigEntry = ConfigEntry[FeedReaderCoordinator]
CONF_URLS = "urls"
MY_KEY: HassKey[StoredData] = HassKey(DOMAIN)
async def async_setup_entry(hass: HomeAssistant, entry: FeedReaderConfigEntry) -> bool:
"""Set up Feedreader from a config entry."""
storage = hass.data.setdefault(MY_KEY, StoredData(hass))
if not storage.is_initialized:
await storage.async_setup()
coordinator = FeedReaderCoordinator(
hass,
entry.data[CONF_URL],
entry.options[CONF_MAX_ENTRIES],
storage,
)
await coordinator.async_setup()
entry.runtime_data = coordinator
# we need to setup event entities before the first coordinator data fetch
# so that the event entities can already fetch the events during the first fetch
await hass.config_entries.async_forward_entry_setups(entry, [Platform.EVENT])
await coordinator.async_config_entry_first_refresh()
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
return True
async def async_unload_entry(hass: HomeAssistant, entry: FeedReaderConfigEntry) -> bool:
"""Unload a config entry."""
entries = hass.config_entries.async_entries(
DOMAIN, include_disabled=False, include_ignore=False
)
# if this is the last entry, remove the storage
if len(entries) == 1:
hass.data.pop(MY_KEY)
return await hass.config_entries.async_unload_platforms(entry, Platform.EVENT)
async def _async_update_listener(
hass: HomeAssistant, entry: FeedReaderConfigEntry
) -> None:
"""Handle reconfiguration."""
await hass.config_entries.async_reload(entry.entry_id)

View File

@@ -0,0 +1,147 @@
"""Config flow for RSS/Atom feeds."""
from __future__ import annotations
import html
import logging
from typing import Any
import urllib.error
import feedparser
import voluptuous as vol
from homeassistant.config_entries import (
ConfigEntry,
ConfigFlow,
ConfigFlowResult,
OptionsFlow,
)
from homeassistant.const import CONF_URL
from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.selector import (
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from .const import CONF_MAX_ENTRIES, DEFAULT_MAX_ENTRIES, DOMAIN
LOGGER = logging.getLogger(__name__)
async def async_fetch_feed(hass: HomeAssistant, url: str) -> feedparser.FeedParserDict:
"""Fetch the feed."""
return await hass.async_add_executor_job(feedparser.parse, url)
class FeedReaderConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow."""
VERSION = 1
@staticmethod
@callback
def async_get_options_flow(
config_entry: ConfigEntry,
) -> OptionsFlow:
"""Get the options flow for this handler."""
return FeedReaderOptionsFlowHandler()
def show_user_form(
self,
user_input: dict[str, Any] | None = None,
errors: dict[str, str] | None = None,
description_placeholders: dict[str, str] | None = None,
step_id: str = "user",
) -> ConfigFlowResult:
"""Show the user form."""
if user_input is None:
user_input = {}
return self.async_show_form(
step_id=step_id,
data_schema=vol.Schema(
{
vol.Required(
CONF_URL, default=user_input.get(CONF_URL, "")
): TextSelector(TextSelectorConfig(type=TextSelectorType.URL))
}
),
description_placeholders=description_placeholders,
errors=errors,
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a flow initialized by the user."""
if not user_input:
return self.show_user_form()
self._async_abort_entries_match({CONF_URL: user_input[CONF_URL]})
feed = await async_fetch_feed(self.hass, user_input[CONF_URL])
if feed.bozo:
LOGGER.debug("feed bozo_exception: %s", feed.bozo_exception)
if isinstance(feed.bozo_exception, urllib.error.URLError):
return self.show_user_form(user_input, {"base": "url_error"})
feed_title = html.unescape(feed["feed"]["title"])
return self.async_create_entry(
title=feed_title,
data=user_input,
options={CONF_MAX_ENTRIES: DEFAULT_MAX_ENTRIES},
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a reconfiguration flow initialized by the user."""
reconfigure_entry = self._get_reconfigure_entry()
if not user_input:
return self.show_user_form(
user_input={**reconfigure_entry.data},
description_placeholders={"name": reconfigure_entry.title},
step_id="reconfigure",
)
feed = await async_fetch_feed(self.hass, user_input[CONF_URL])
if feed.bozo:
LOGGER.debug("feed bozo_exception: %s", feed.bozo_exception)
if isinstance(feed.bozo_exception, urllib.error.URLError):
return self.show_user_form(
user_input=user_input,
description_placeholders={"name": reconfigure_entry.title},
step_id="reconfigure",
errors={"base": "url_error"},
)
self.hass.config_entries.async_update_entry(reconfigure_entry, data=user_input)
return self.async_abort(reason="reconfigure_successful")
class FeedReaderOptionsFlowHandler(OptionsFlow):
"""Handle an options flow."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle options flow."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
data_schema = vol.Schema(
{
vol.Optional(
CONF_MAX_ENTRIES,
default=self.config_entry.options.get(
CONF_MAX_ENTRIES, DEFAULT_MAX_ENTRIES
),
): cv.positive_int,
}
)
return self.async_show_form(step_id="init", data_schema=data_schema)

View File

@@ -0,0 +1,12 @@
"""Constants for RSS/Atom feeds."""
from datetime import timedelta
from typing import Final
DOMAIN: Final[str] = "feedreader"
CONF_MAX_ENTRIES: Final[str] = "max_entries"
DEFAULT_MAX_ENTRIES: Final[int] = 20
DEFAULT_SCAN_INTERVAL: Final[timedelta] = timedelta(hours=1)
EVENT_FEEDREADER: Final[str] = "feedreader"

View File

@@ -0,0 +1,243 @@
"""Data update coordinator for RSS/Atom feeds."""
from __future__ import annotations
from calendar import timegm
from datetime import datetime
import html
from logging import getLogger
from time import gmtime, struct_time
from typing import TYPE_CHECKING
from urllib.error import URLError
import feedparser
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.storage import Store
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import dt as dt_util
from .const import DEFAULT_SCAN_INTERVAL, DOMAIN, EVENT_FEEDREADER
DELAY_SAVE = 30
STORAGE_VERSION = 1
_LOGGER = getLogger(__name__)
class FeedReaderCoordinator(
DataUpdateCoordinator[list[feedparser.FeedParserDict] | None]
):
"""Abstraction over Feedparser module."""
config_entry: ConfigEntry
def __init__(
self,
hass: HomeAssistant,
url: str,
max_entries: int,
storage: StoredData,
) -> None:
"""Initialize the FeedManager object, poll as per scan interval."""
super().__init__(
hass=hass,
logger=_LOGGER,
name=f"{DOMAIN} {url}",
update_interval=DEFAULT_SCAN_INTERVAL,
)
self.url = url
self.feed_author: str | None = None
self.feed_version: str | None = None
self._max_entries = max_entries
self._storage = storage
self._last_entry_timestamp: struct_time | None = None
self._event_type = EVENT_FEEDREADER
self._feed: feedparser.FeedParserDict | None = None
self._feed_id = url
@callback
def _log_no_entries(self) -> None:
"""Send no entries log at debug level."""
_LOGGER.debug("No new entries to be published in feed %s", self.url)
async def _async_fetch_feed(self) -> feedparser.FeedParserDict:
"""Fetch the feed data."""
_LOGGER.debug("Fetching new data from feed %s", self.url)
def _parse_feed() -> feedparser.FeedParserDict:
return feedparser.parse(
self.url,
etag=None if not self._feed else self._feed.get("etag"),
modified=None if not self._feed else self._feed.get("modified"),
)
feed = await self.hass.async_add_executor_job(_parse_feed)
if not feed:
raise UpdateFailed(f"Error fetching feed data from {self.url}")
# The 'bozo' flag really only indicates that there was an issue
# during the initial parsing of the XML, but it doesn't indicate
# whether this is an unrecoverable error. In this case the
# feedparser lib is trying a less strict parsing approach.
# If an error is detected here, log warning message but continue
# processing the feed entries if present.
if feed.bozo != 0:
if isinstance(feed.bozo_exception, URLError):
raise UpdateFailed(
f"Error fetching feed data from {self.url} : {feed.bozo_exception}"
)
# no connection issue, but parsing issue
_LOGGER.warning(
"Possible issue parsing feed %s: %s",
self.url,
feed.bozo_exception,
)
return feed
async def async_setup(self) -> None:
"""Set up the feed manager."""
try:
feed = await self._async_fetch_feed()
except UpdateFailed as err:
raise ConfigEntryNotReady from err
self.logger.debug("Feed data fetched from %s : %s", self.url, feed["feed"])
if feed_author := feed["feed"].get("author"):
self.feed_author = html.unescape(feed_author)
self.feed_version = feedparser.api.SUPPORTED_VERSIONS.get(feed["version"])
self._feed = feed
async def _async_update_data(self) -> list[feedparser.FeedParserDict] | None:
"""Update the feed and publish new entries to the event bus."""
assert self._feed is not None
# _last_entry_timestamp is not set during async_setup, but we have already
# fetched data, so we can use them, instead of fetch again
if self._last_entry_timestamp:
self._feed = await self._async_fetch_feed()
# Using etag and modified, if there's no new data available,
# the entries list will be empty
_LOGGER.debug(
"%s entri(es) available in feed %s",
len(self._feed.entries),
self.url,
)
if not self._feed.entries:
self._log_no_entries()
return None
if TYPE_CHECKING:
assert isinstance(self._feed.entries, list)
self._filter_entries()
self._publish_new_entries()
_LOGGER.debug("Fetch from feed %s completed", self.url)
if self._last_entry_timestamp:
self._storage.async_put_timestamp(self._feed_id, self._last_entry_timestamp)
return self._feed.entries
@callback
def _filter_entries(self) -> None:
"""Filter the entries provided and return the ones to keep."""
assert self._feed is not None
if len(self._feed.entries) > self._max_entries:
_LOGGER.debug(
"Processing only the first %s entries in feed %s",
self._max_entries,
self.url,
)
self._feed.entries = self._feed.entries[0 : self._max_entries]
@callback
def _update_and_fire_entry(self, entry: feedparser.FeedParserDict) -> None:
"""Update last_entry_timestamp and fire entry."""
# Check if the entry has a updated or published date.
# Start from a updated date because generally `updated` > `published`.
if time_stamp := entry.get("updated_parsed") or entry.get("published_parsed"):
self._last_entry_timestamp = time_stamp
else:
_LOGGER.debug(
"No updated_parsed or published_parsed info available for entry %s",
entry,
)
entry["feed_url"] = self.url
self.hass.bus.async_fire(self._event_type, entry)
_LOGGER.debug("New event fired for entry %s", entry.get("link"))
@callback
def _publish_new_entries(self) -> None:
"""Publish new entries to the event bus."""
assert self._feed is not None
new_entry_count = 0
firstrun = False
self._last_entry_timestamp = self._storage.get_timestamp(self._feed_id)
if not self._last_entry_timestamp:
firstrun = True
# Set last entry timestamp as epoch time if not available
self._last_entry_timestamp = dt_util.utc_from_timestamp(0).timetuple()
# locally cache self._last_entry_timestamp so that entries published at identical times can be processed
last_entry_timestamp = self._last_entry_timestamp
for entry in self._feed.entries:
if firstrun or (
(
time_stamp := entry.get("updated_parsed")
or entry.get("published_parsed")
)
and time_stamp > last_entry_timestamp
):
self._update_and_fire_entry(entry)
new_entry_count += 1
else:
_LOGGER.debug("Already processed entry %s", entry.get("link"))
if new_entry_count == 0:
self._log_no_entries()
else:
_LOGGER.debug("%d entries published in feed %s", new_entry_count, self.url)
class StoredData:
"""Represent a data storage."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize data storage."""
self._data: dict[str, struct_time] = {}
self.hass = hass
self._store: Store[dict[str, str]] = Store(hass, STORAGE_VERSION, DOMAIN)
self.is_initialized = False
async def async_setup(self) -> None:
"""Set up storage."""
if (store_data := await self._store.async_load()) is not None:
# Make sure that dst is set to 0, by using gmtime() on the timestamp.
self._data = {
feed_id: gmtime(datetime.fromisoformat(timestamp_string).timestamp())
for feed_id, timestamp_string in store_data.items()
}
self.is_initialized = True
def get_timestamp(self, feed_id: str) -> struct_time | None:
"""Return stored timestamp for given feed id."""
return self._data.get(feed_id)
@callback
def async_put_timestamp(self, feed_id: str, timestamp: struct_time) -> None:
"""Update timestamp for given feed id."""
self._data[feed_id] = timestamp
self._store.async_delay_save(self._async_save_data, DELAY_SAVE)
@callback
def _async_save_data(self) -> dict[str, str]:
"""Save feed data to storage."""
return {
feed_id: dt_util.utc_from_timestamp(timegm(struct_utc)).isoformat()
for feed_id, struct_utc in self._data.items()
}

View File

@@ -0,0 +1,100 @@
"""Event entities for RSS/Atom feeds."""
from __future__ import annotations
import html
import logging
from feedparser import FeedParserDict
from homeassistant.components.event import EventEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import FeedReaderConfigEntry
from .const import DOMAIN, EVENT_FEEDREADER
from .coordinator import FeedReaderCoordinator
LOGGER = logging.getLogger(__name__)
ATTR_CONTENT = "content"
ATTR_DESCRIPTION = "description"
ATTR_LINK = "link"
ATTR_TITLE = "title"
async def async_setup_entry(
hass: HomeAssistant,
entry: FeedReaderConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up event entities for feedreader."""
coordinator = entry.runtime_data
async_add_entities([FeedReaderEvent(coordinator)])
class FeedReaderEvent(CoordinatorEntity[FeedReaderCoordinator], EventEntity):
"""Representation of a feedreader event."""
_attr_event_types = [EVENT_FEEDREADER]
_attr_name = None
_attr_has_entity_name = True
_unrecorded_attributes = frozenset(
{ATTR_CONTENT, ATTR_DESCRIPTION, ATTR_TITLE, ATTR_LINK}
)
coordinator: FeedReaderCoordinator
def __init__(self, coordinator: FeedReaderCoordinator) -> None:
"""Initialize the feedreader event."""
super().__init__(coordinator)
self._attr_unique_id = f"{coordinator.config_entry.entry_id}_latest_feed"
self._attr_translation_key = "latest_feed"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, coordinator.config_entry.entry_id)},
name=coordinator.config_entry.title,
configuration_url=coordinator.url,
manufacturer=coordinator.feed_author,
sw_version=coordinator.feed_version,
entry_type=DeviceEntryType.SERVICE,
)
async def async_added_to_hass(self) -> None:
"""Entity added to hass."""
await super().async_added_to_hass()
self.async_on_remove(
self.coordinator.async_add_listener(self._async_handle_update)
)
@callback
def _async_handle_update(self) -> None:
if (data := self.coordinator.data) is None or not data:
return
# RSS feeds are normally sorted reverse chronologically by published date
# so we always take the first entry in list, since we only care about the latest entry
feed_data: FeedParserDict = data[0]
if description := feed_data.get("description"):
description = html.unescape(description)
if title := feed_data.get("title"):
title = html.unescape(title)
if content := feed_data.get("content"):
if isinstance(content, list) and isinstance(content[0], dict):
content = content[0].get("value")
content = html.unescape(content)
self._trigger_event(
EVENT_FEEDREADER,
{
ATTR_DESCRIPTION: description,
ATTR_TITLE: title,
ATTR_LINK: feed_data.get("link"),
ATTR_CONTENT: content,
},
)
self.async_write_ha_state()

View File

@@ -0,0 +1,9 @@
{
"entity": {
"event": {
"latest_feed": {
"default": "mdi:rss"
}
}
}
}

View File

@@ -0,0 +1,10 @@
{
"domain": "feedreader",
"name": "Feedreader",
"codeowners": ["@mib1185"],
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/feedreader",
"iot_class": "cloud_polling",
"loggers": ["feedparser", "sgmllib3k"],
"requirements": ["feedparser==6.0.11"]
}

View File

@@ -0,0 +1,42 @@
{
"config": {
"step": {
"user": {
"data": {
"url": "[%key:common::config_flow::data::url%]"
}
},
"reconfigure": {
"description": "Update your configuration information for {name}.",
"data": {
"url": "[%key:common::config_flow::data::url%]"
}
}
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]",
"reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]"
},
"error": {
"url_error": "The URL could not be opened."
}
},
"options": {
"step": {
"init": {
"data": {
"max_entries": "Maximum feed entries"
},
"data_description": {
"max_entries": "The maximum number of entries to extract from each feed."
}
}
}
},
"issues": {
"import_yaml_error_url_error": {
"title": "The Feedreader YAML configuration import failed",
"description": "Configuring the Feedreader using YAML is being removed but there was a connection error when trying to import the YAML configuration for `{url}`.\n\nPlease verify that url is reachable and accessable for Home Assistant and restart Home Assistant to try again or remove the Feedreader YAML configuration from your configuration.yaml file and continue to set up the integration manually."
}
}
}