diff --git a/README.md b/README.md index 3af7b89f..a3941f08 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Feeds can be set up in the UI, in `configuration.yaml`, or both. Feeds from YAML 1. Go to **Settings** -> **Devices & Services** -> **Integrations**. 2. Click **Add Integration** and search for **Feedparser**. -3. Fill in at least `Name` and `Feed URL`. +3. Fill in `Name` and either `Feed URL` or `Feed URL entity` (see [Feed URLs that change](#feed-urls-that-change)). 4. Set the refresh interval with the duration field (minimum 1 minute). 5. Optional include/exclude fields are entered as comma-separated values. @@ -42,6 +42,30 @@ To fix the sensor name or feed URL, open the entry's menu (⋮) and choose **Rec - The same feed URL can be added more than once (for example, once with all fields and once with only titles), as long as each sensor has a different name. - If a feed cannot be reached when Home Assistant starts, the entry is retried automatically in the background. If a later refresh fails, the sensor becomes `unavailable` until the feed responds again. +#### Feed URLs that change + +Some feeds publish a new URL every day, such as `.../programme-tv-rss_15-11-2026.xml`. Instead of typing a URL, choose a **Feed URL entity**: an `input_text`, `text` or template `sensor` whose state is the feed URL. The URL is read from that entity on every refresh, and the feed is fetched again as soon as its value changes. + +To build a URL with today's date, create a template sensor helper (**Settings** -> **Devices & Services** -> **Helpers** -> **Create helper** -> **Template** -> **Template a sensor**) with a state template like: + +```jinja +https://example.com/epg/programme-tv-rss_{{ now().strftime('%d-%m-%Y') }}.xml +``` + +Then pick that sensor as the feed's **Feed URL entity**. To switch feeds from an automation or script instead, use an `input_text` helper and set its value with `input_text.set_value`. + +- Home Assistant limits entity states to 255 characters, so longer URLs can't be passed this way. `input_text` helpers default to a maximum of 100 characters; raise their maximum length if needed. +- While the entity is missing, `unknown`, `unavailable` or holds something that is not an `http`, `https` or `file` URL, the feed can't be refreshed and the sensor becomes `unavailable`. + +In YAML, use `feed_url_entity` instead of `feed_url`: + +```yaml +sensor: + - platform: feedparser + name: TV Tonight + feed_url_entity: sensor.todays_tv_feed_url +``` + ### YAML configuration Add `sensor:` entries with `platform: feedparser` to `configuration.yaml` (example below) and restart Home Assistant. YAML is handy when you copy a setup between Home Assistant instances or keep it in version control. @@ -160,7 +184,8 @@ The integration supports both UI and YAML setup. Most options are the same in bo | :-- | :-- | :-- | :-- | :-- | :-- | | `platform` (YAML only) | Yes (YAML) | string | - | `feedparser` | Home Assistant platform name used in YAML mode. | | `name` | Yes | string | - | `Engineering Feed` | Name shown for the sensor entity. | -| `feed_url` | Yes | URL string | - | `https://www.nu.nl/rss/Algemeen` | RSS/Atom feed URL to fetch and parse. Supports `http`, `https`, and `file` in dev/testing. | +| `feed_url` | Yes (unless `feed_url_entity` is set) | URL string | - | `https://www.nu.nl/rss/Algemeen` | RSS/Atom feed URL to fetch and parse. Supports `http`, `https`, and `file` in dev/testing. | +| `feed_url_entity` | Yes (unless `feed_url` is set) | entity ID | - | `sensor.todays_tv_feed_url` | Entity (`input_text`, `text` or `sensor`) whose state is the feed URL, read on every refresh. See [Feed URLs that change](#feed-urls-that-change). | | `date_format` | No | string (`strftime`) | `%a, %b %d %I:%M %p` | `%a, %d %b %Y %H:%M:%S %Z` | Output format for date fields in feed entries. | | `local_time` | No | boolean | `false` | `true` | Converts parsed date values from feed timezone to Home Assistant local timezone. | | `scan_interval` | No | duration object | `1 hour` | `{ hours: 1, minutes: 30 }` | Polling interval for refreshing feed data. UI input must be at least 1 minute. | diff --git a/custom_components/feedparser/__init__.py b/custom_components/feedparser/__init__.py index ee3cc0a7..e02b9960 100644 --- a/custom_components/feedparser/__init__.py +++ b/custom_components/feedparser/__init__.py @@ -94,6 +94,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: FeedparserConfigEntry) - coordinator = FeedparserCoordinator(hass, entry) await coordinator.async_config_entry_first_refresh() entry.runtime_data = coordinator + if (stop_tracking := coordinator.async_track_url_entity()) is not None: + entry.async_on_unload(stop_tracking) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) return True diff --git a/custom_components/feedparser/config_flow.py b/custom_components/feedparser/config_flow.py index 4988830a..9088b97f 100644 --- a/custom_components/feedparser/config_flow.py +++ b/custom_components/feedparser/config_flow.py @@ -19,7 +19,6 @@ ) from homeassistant.const import CONF_NAME from homeassistant.helpers import selector -from yarl import URL from .compat import vol from .const import ( @@ -27,6 +26,7 @@ CONF_EXCLUDE_MATCH, CONF_EXCLUSIONS, CONF_FEED_URL, + CONF_FEED_URL_ENTITY, CONF_INCLUSIONS, CONF_LOCAL_TIME, CONF_MANAGED_BY_YAML, @@ -47,6 +47,13 @@ ) from .fetch import USER_AGENT, fetch_feed, is_valid_proxy from .reader import compile_filter +from .source import ( + URL_ENTITY_DOMAINS, + InvalidFeedUrlError, + NoFeedUrlError, + feed_url_from_entity, + is_supported_url, +) from .yaml_import import ( REASON_MANAGED_IN_UI, REASON_SYNCED, @@ -151,12 +158,40 @@ def _as_str_list(value: object) -> list[str]: return [] -def _is_supported_url(feed_url: str) -> bool: - """Return whether the URL is well-formed with a supported scheme.""" - try: - return URL(feed_url).scheme in ("http", "https", "file") - except ValueError: - return False +def _source_from_input( + user_input: Mapping[str, object], +) -> tuple[dict[str, str], dict[str, str]]: + """Return the feed source to store, and form errors, from a submission. + + The source is either a typed URL ({feed_url}) or an entity whose state is + the URL ({feed_url_entity}); exactly one of the two must be filled in. + """ + feed_url = str(user_input.get(CONF_FEED_URL) or "").strip() + entity_id = str(user_input.get(CONF_FEED_URL_ENTITY) or "").strip() + if bool(feed_url) == bool(entity_id): + return {}, {"base": "url_or_entity"} + if entity_id: + return {CONF_FEED_URL_ENTITY: entity_id}, {} + if not is_supported_url(feed_url): + return {}, {CONF_FEED_URL: "invalid_url"} + return {CONF_FEED_URL: feed_url}, {} + + +def _source_of(data: Mapping[str, object]) -> dict[str, object]: + """Return the feed source fields stored in an entry's data.""" + return { + key: data[key] for key in (CONF_FEED_URL, CONF_FEED_URL_ENTITY) if data.get(key) + } + + +def _feed_source_schema() -> dict[Any, Any]: + """Return the form fields for a feed URL or a URL entity.""" + return { + vol.Optional(CONF_FEED_URL): str, + vol.Optional(CONF_FEED_URL_ENTITY): selector.EntitySelector( + selector.EntitySelectorConfig(domain=URL_ENTITY_DOMAINS), + ), + } def _options_from_input(user_input: Mapping[str, object]) -> dict[str, object]: @@ -238,7 +273,6 @@ def _user_agent_from_input(user_input: Mapping[str, object]) -> str: def _schema_with_defaults( # noqa: PLR0913 - one keyword per form field *, name: str = DEFAULT_NAME, - feed_url: str = "", date_format: str = DEFAULT_DATE_FORMAT, local_time: bool = DEFAULT_LOCAL_TIME, show_topn: int = DEFAULT_TOPN, @@ -294,7 +328,7 @@ def _schema_with_defaults( # noqa: PLR0913 - one keyword per form field if include_feed_identity: schema = { vol.Required(CONF_NAME, default=name): str, - vol.Required(CONF_FEED_URL, default=feed_url): str, + **_feed_source_schema(), **schema, } @@ -319,8 +353,8 @@ async def async_step_user( errors: dict[str, str] = {} if user_input is not None: - feed_url = str(user_input[CONF_FEED_URL]).strip() name = str(user_input[CONF_NAME]).strip() + source, errors = _source_from_input(user_input) options: dict[str, object] = {} try: @@ -329,16 +363,14 @@ async def async_step_user( errors[CONF_SCAN_INTERVAL] = "scan_interval_too_short" else: errors.update(_option_errors(options)) - if not _is_supported_url(feed_url): - errors[CONF_FEED_URL] = "invalid_url" - elif self._is_configured(feed_url, name): + if source and self._is_configured(source, name): # The same feed may be added more than once (e.g. with different # filters) as long as each sensor has its own name. errors[CONF_NAME] = "already_configured" if not errors: - errors = await self._async_validate_feed( - feed_url, + errors = await self._async_validate_source( + source, str(options[CONF_USER_AGENT]) or USER_AGENT, str(options[CONF_PROXY]), ) @@ -347,7 +379,7 @@ async def async_step_user( "ConfigFlowResult", self.async_create_entry( title=name, - data={CONF_NAME: name, CONF_FEED_URL: feed_url}, + data={CONF_NAME: name, **source}, options=options, ), ) @@ -379,9 +411,16 @@ async def async_step_import( must not stop the import, and the entry setup retries on its own. """ name = str(import_data[CONF_NAME]).strip() - feed_url = str(import_data[CONF_FEED_URL]).strip() + feed_url = str(import_data.get(CONF_FEED_URL) or "").strip() + url_entity = str(import_data.get(CONF_FEED_URL_ENTITY) or "").strip() + # the YAML schema guarantees exactly one of the two + source = ( + {CONF_FEED_URL_ENTITY: url_entity} + if url_entity + else {CONF_FEED_URL: feed_url} + ) unique_id = yaml_unique_id(name) - data = {CONF_NAME: name, CONF_FEED_URL: feed_url, CONF_MANAGED_BY_YAML: True} + data = {CONF_NAME: name, **source, CONF_MANAGED_BY_YAML: True} options = _options_from_import(import_data) entry = self._yaml_entry(unique_id, feed_url, name) @@ -405,7 +444,7 @@ async def async_step_import( ), ) - if self._is_configured(feed_url, name): + if self._is_configured(source, name): # the same feed and name were added in the UI return cast( "ConfigFlowResult", @@ -436,39 +475,42 @@ async def async_step_reconfigure( errors: dict[str, str] = {} if user_input is not None: - feed_url = str(user_input[CONF_FEED_URL]).strip() name = str(user_input[CONF_NAME]).strip() + source, errors = _source_from_input(user_input) - if not _is_supported_url(feed_url): - errors[CONF_FEED_URL] = "invalid_url" - elif self._is_configured(feed_url, name, exclude_entry_id=entry.entry_id): + if source and self._is_configured( + source, + name, + exclude_entry_id=entry.entry_id, + ): errors[CONF_NAME] = "already_configured" if not errors: - errors = await self._async_validate_feed( - feed_url, + errors = await self._async_validate_source( + source, str(entry.options.get(CONF_USER_AGENT) or "") or USER_AGENT, str(entry.options.get(CONF_PROXY) or ""), ) if not errors: # The sensor's unique ID is the entry ID, so the entity ID and - # history are kept; only its name and source change. + # history are kept; only its name and source change. The old + # source is dropped, so switching between URL and entity works. + data = { + key: value + for key, value in entry.data.items() + if key not in (CONF_FEED_URL, CONF_FEED_URL_ENTITY) + } return cast( "ConfigFlowResult", self.async_update_reload_and_abort( entry, title=name, - data_updates={CONF_NAME: name, CONF_FEED_URL: feed_url}, + data={**data, CONF_NAME: name, **source}, ), ) data_schema = self.add_suggested_values_to_schema( - vol.Schema( - { - vol.Required(CONF_NAME): str, - vol.Required(CONF_FEED_URL): str, - }, - ), + vol.Schema({vol.Required(CONF_NAME): str, **_feed_source_schema()}), user_input or entry.data, ) return cast( @@ -489,14 +531,16 @@ def _yaml_entry( """Return the entry that belongs to a YAML sensor, if there is one. Entries imported by 1.0.0 have no unique ID; they are matched by feed URL - and name, then linked to the YAML again. + and name, then linked to the YAML again. (1.0.0 had no URL entities, so a + YAML sensor using one only matches by unique ID.) """ for entry in self._async_current_entries(include_ignore=False): if entry.unique_id == unique_id: return entry for entry in self._async_current_entries(include_ignore=False): if ( - entry.source == SOURCE_IMPORT + feed_url + and entry.source == SOURCE_IMPORT and entry.unique_id is None and CONF_MANAGED_BY_YAML not in entry.data and entry.data.get(CONF_FEED_URL) == feed_url @@ -507,24 +551,55 @@ def _yaml_entry( def _is_configured( self, - feed_url: str, + source: Mapping[str, object], name: str, *, exclude_entry_id: str | None = None, ) -> bool: - """Return whether another entry with this feed URL and name exists.""" + """Return whether another entry with this feed source and name exists.""" return any( entry.entry_id != exclude_entry_id - and entry.data.get(CONF_FEED_URL) == feed_url + and _source_of(entry.data) == source and str(entry.data.get(CONF_NAME, "")).casefold() == name.casefold() for entry in self._async_current_entries(include_ignore=False) ) + async def _async_validate_source( + self, + source: Mapping[str, object], + user_agent: str, + proxy: str = "", + ) -> dict[str, str]: + """Fetch the feed a source points to and return form errors. + + For a URL entity, the URL it holds right now is fetched. + """ + entity_id = source.get(CONF_FEED_URL_ENTITY) + if not isinstance(entity_id, str): + return await self._async_validate_feed( + str(source[CONF_FEED_URL]), + user_agent, + proxy, + ) + try: + feed_url = feed_url_from_entity(self.hass, entity_id) + except NoFeedUrlError: + return {CONF_FEED_URL_ENTITY: "entity_no_url"} + except InvalidFeedUrlError: + return {CONF_FEED_URL_ENTITY: "entity_invalid_url"} + return await self._async_validate_feed( + feed_url, + user_agent, + proxy, + CONF_FEED_URL_ENTITY, + ) + async def _async_validate_feed( self, feed_url: str, user_agent: str, proxy: str = "", + field: str = CONF_FEED_URL, ) -> dict[str, str]: """Fetch the feed and return form errors (empty if it is usable).""" try: @@ -537,7 +612,7 @@ async def _async_validate_feed( except requests.RequestException: return {"base": "cannot_connect"} except InvalidFeedError: - return {CONF_FEED_URL: "invalid_feed"} + return {field: "invalid_feed"} return {} @staticmethod diff --git a/custom_components/feedparser/const.py b/custom_components/feedparser/const.py index 35d36700..9ad05719 100644 --- a/custom_components/feedparser/const.py +++ b/custom_components/feedparser/const.py @@ -9,6 +9,8 @@ PLATFORMS: list[Platform] = [Platform.SENSOR] CONF_FEED_URL = "feed_url" +# entity whose state is the feed URL, used instead of CONF_FEED_URL +CONF_FEED_URL_ENTITY = "feed_url_entity" CONF_DATE_FORMAT = "date_format" CONF_LOCAL_TIME = "local_time" CONF_INCLUSIONS = "inclusions" diff --git a/custom_components/feedparser/coordinator.py b/custom_components/feedparser/coordinator.py index 79dc3044..bcb0a44b 100644 --- a/custom_components/feedparser/coordinator.py +++ b/custom_components/feedparser/coordinator.py @@ -3,13 +3,15 @@ from __future__ import annotations import logging -from collections.abc import Mapping +from collections.abc import Callable, Mapping from datetime import timedelta from typing import TYPE_CHECKING import requests from homeassistant.config_entries import ConfigEntry -from homeassistant.const import CONF_NAME +from homeassistant.const import CONF_NAME, STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import Event, EventStateChangedData, callback +from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( @@ -17,6 +19,7 @@ CONF_EXCLUDE_MATCH, CONF_EXCLUSIONS, CONF_FEED_URL, + CONF_FEED_URL_ENTITY, CONF_INCLUSIONS, CONF_LOCAL_TIME, CONF_MATCH, @@ -34,6 +37,7 @@ ) from .fetch import USER_AGENT, redact_text from .reader import FeedReader +from .source import FeedUrlError, feed_url_from_entity if TYPE_CHECKING: from homeassistant.core import HomeAssistant @@ -66,8 +70,10 @@ class FeedparserCoordinator(DataUpdateCoordinator[FeedEntries]): def __init__(self, hass: HomeAssistant, entry: FeedparserConfigEntry) -> None: """Initialize the coordinator from the entry's data and options.""" config = {**entry.data, **entry.options} + # set when the feed URL is read from this entity's state on every poll + self.url_entity: str | None = config.get(CONF_FEED_URL_ENTITY) or None self.reader = FeedReader( - feed=config[CONF_FEED_URL], + feed=config.get(CONF_FEED_URL) or "", name=config[CONF_NAME], date_format=config.get(CONF_DATE_FORMAT, DEFAULT_DATE_FORMAT), show_topn=config.get(CONF_SHOW_TOPN, DEFAULT_TOPN), @@ -94,12 +100,59 @@ def __init__(self, hass: HomeAssistant, entry: FeedparserConfigEntry) -> None: ), ) + def feed_url(self) -> str: + """Return the URL to fetch now, reading the URL entity if there is one. + + Raises ``UpdateFailed`` if the URL entity has no usable URL. + """ + if self.url_entity is None: + return self.reader.feed + try: + return feed_url_from_entity(self.hass, self.url_entity) + except FeedUrlError as err: + msg = f"No feed URL to fetch: {err}" + raise UpdateFailed(msg) from err + async def _async_update_data(self) -> FeedEntries: """Fetch the feed in the executor and build its entries.""" + url = self.feed_url() try: - return await self.hass.async_add_executor_job(self.reader.read) + return await self.hass.async_add_executor_job(self.reader.read, url) except requests.RequestException as err: # the error may quote the proxy URL; never log its password reason = redact_text(str(err), self.reader.proxy) - msg = f"Unable to fetch {self.reader.feed}: {reason}" + msg = f"Unable to fetch {url}: {reason}" raise UpdateFailed(msg) from err + + @callback + def async_track_url_entity(self) -> Callable[[], None] | None: + """Refresh as soon as the URL entity's value changes. + + Returns the function that stops tracking, or None without a URL entity. + """ + if self.url_entity is None: + return None + + @callback + def _url_changed(event: Event[EventStateChangedData]) -> None: + new_state = event.data["new_state"] + old_state = event.data["old_state"] + if new_state is None or new_state.state in ( + STATE_UNKNOWN, + STATE_UNAVAILABLE, + ): + # e.g. the helper reloading; keep the entries until the next poll + return + if old_state is not None and old_state.state == new_state.state: + return # only an attribute changed + self.config_entry.async_create_task( + self.hass, + self.async_request_refresh(), + f"{DOMAIN} feed URL changed", + ) + + return async_track_state_change_event( + self.hass, + self.url_entity, + _url_changed, + ) diff --git a/custom_components/feedparser/reader.py b/custom_components/feedparser/reader.py index 209f221f..ad0623f6 100644 --- a/custom_components/feedparser/reader.py +++ b/custom_components/feedparser/reader.py @@ -142,18 +142,22 @@ def __repr__(self: FeedReader) -> str: f"proxy={redact_proxy(self.proxy) if self.proxy else None!r})" ) - def read(self: FeedReader) -> list[dict[str, object]]: + def read(self: FeedReader, url: str | None = None) -> list[dict[str, object]]: """Fetch the feed and return a new list of at most `show_topn` entries. + `url` overrides the reader's `feed` for this call (used when the URL comes + from an entity and may change between polls). + Raises ``requests.RequestException`` if the feed cannot be downloaded. A new list is returned on every call: Home Assistant keeps references to nested attribute values in previous states, so reusing (mutating) a list would hide `entries` changes from state triggers. """ - _LOGGER.debug("Feed %s: Polling feed data from %s", self.name, self.feed) + url = url or self.feed + _LOGGER.debug("Feed %s: Polling feed data from %s", self.name, url) parsed_feed = cast( "ParsedFeed", - feedparser.parse(fetch_feed(self.feed, self._user_agent, self.proxy)), + feedparser.parse(fetch_feed(url, self._user_agent, self.proxy)), ) if not parsed_feed.entries: _LOGGER.warning("Feed %s: No data received.", self.name) diff --git a/custom_components/feedparser/sensor.py b/custom_components/feedparser/sensor.py index 0a557eba..5524f823 100644 --- a/custom_components/feedparser/sensor.py +++ b/custom_components/feedparser/sensor.py @@ -6,7 +6,10 @@ from typing import TYPE_CHECKING import homeassistant.helpers.config_validation as cv -from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity +from homeassistant.components.sensor import ( + PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA, +) +from homeassistant.components.sensor import SensorEntity from homeassistant.const import CONF_NAME from homeassistant.helpers.update_coordinator import CoordinatorEntity @@ -16,6 +19,7 @@ CONF_EXCLUDE_MATCH, CONF_EXCLUSIONS, CONF_FEED_URL, + CONF_FEED_URL_ENTITY, CONF_INCLUSIONS, CONF_LOCAL_TIME, CONF_MATCH, @@ -33,6 +37,7 @@ from .coordinator import FeedEntries, FeedparserConfigEntry, FeedparserCoordinator from .fetch import USER_AGENT, is_valid_proxy from .reader import compile_filter +from .source import URL_ENTITY_DOMAINS from .yaml_import import async_import_yaml_sensor if TYPE_CHECKING: @@ -65,10 +70,17 @@ def _valid_proxy(value: str) -> str: return value -PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( +# A feed's URL is either written out (feed_url) or read from an entity's state +# on every refresh (feed_url_entity), never both. +_FEED_SOURCE = "feed_source" + +_SENSOR_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend( { vol.Required(CONF_NAME): cv.string, - vol.Required(CONF_FEED_URL): cv.string, + vol.Exclusive(CONF_FEED_URL, _FEED_SOURCE): cv.string, + vol.Exclusive(CONF_FEED_URL_ENTITY, _FEED_SOURCE): cv.entity_domain( + URL_ENTITY_DOMAINS, + ), vol.Required(CONF_DATE_FORMAT, default=DEFAULT_DATE_FORMAT): cv.string, vol.Optional(CONF_LOCAL_TIME, default=DEFAULT_LOCAL_TIME): cv.boolean, vol.Optional(CONF_SHOW_TOPN, default=DEFAULT_TOPN): cv.positive_int, @@ -89,6 +101,11 @@ def _valid_proxy(value: str) -> str: }, ) +PLATFORM_SCHEMA = vol.All( + cv.has_at_least_one_key(CONF_FEED_URL, CONF_FEED_URL_ENTITY), + _SENSOR_SCHEMA, +) + async def async_setup_platform( hass: HomeAssistant, diff --git a/custom_components/feedparser/source.py b/custom_components/feedparser/source.py new file mode 100644 index 00000000..6d7f7746 --- /dev/null +++ b/custom_components/feedparser/source.py @@ -0,0 +1,63 @@ +"""Where a feed's URL comes from: typed in, or the state of another entity. + +Taking the URL from an entity (an ``input_text``, ``text`` or template ``sensor`` +helper) lets users build it dynamically, e.g. with today's date, without this +integration rendering templates itself. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN +from yarl import URL + +if TYPE_CHECKING: + from homeassistant.core import HomeAssistant + +URL_SCHEMES = ("http", "https", "file") + +# Entity domains whose state can hold a URL. Entity states are capped at 255 +# characters by Home Assistant, so longer URLs can't be passed this way. +URL_ENTITY_DOMAINS = ["input_text", "text", "sensor"] + + +class FeedUrlError(Exception): + """The URL entity can't provide a feed URL right now.""" + + +class NoFeedUrlError(FeedUrlError): + """The URL entity does not exist or has no value.""" + + +class InvalidFeedUrlError(FeedUrlError): + """The URL entity's value is not a supported feed URL.""" + + +def is_supported_url(feed_url: str) -> bool: + """Return whether the URL is well-formed with a supported scheme.""" + try: + return URL(feed_url).scheme in URL_SCHEMES + except ValueError: + return False + + +def feed_url_from_entity(hass: HomeAssistant, entity_id: str) -> str: + """Return the feed URL currently held in `entity_id`'s state. + + Must run in the event loop. Raises ``NoFeedUrlError`` if the entity is + missing, unknown, unavailable or empty, and ``InvalidFeedUrlError`` if its + value is not an http(s) or file URL. + """ + state = hass.states.get(entity_id) + if state is None: + msg = f"{entity_id} does not exist" + raise NoFeedUrlError(msg) + url = state.state.strip() + if not url or url in (STATE_UNKNOWN, STATE_UNAVAILABLE): + msg = f"{entity_id} has no URL (state: {state.state!r})" + raise NoFeedUrlError(msg) + if not is_supported_url(url): + msg = f"{entity_id} does not hold a valid feed URL: {url!r}" + raise InvalidFeedUrlError(msg) + return url diff --git a/custom_components/feedparser/strings.json b/custom_components/feedparser/strings.json index 7be6480c..e09e46b3 100644 --- a/custom_components/feedparser/strings.json +++ b/custom_components/feedparser/strings.json @@ -7,6 +7,7 @@ "data": { "name": "Name", "feed_url": "Feed URL", + "feed_url_entity": "Feed URL entity", "date_format": "Date format", "local_time": "Convert dates to local time", "scan_interval": "Refresh interval", @@ -21,7 +22,8 @@ }, "data_description": { "name": "Friendly name for the sensor.", - "feed_url": "RSS or Atom feed URL. HTTP, HTTPS, and local file URLs are supported.", + "feed_url": "RSS or Atom feed URL. HTTP, HTTPS, and local file URLs are supported. Leave empty to take the URL from an entity instead.", + "feed_url_entity": "Use instead of a feed URL: an input_text, text or template sensor whose state is the feed URL. Use a template sensor helper to build a URL that changes, e.g. with today's date. The feed is fetched again whenever its value changes. Entity states are limited to 255 characters.", "date_format": "Python strftime format used for feed dates, for example `%a, %d %b %Y %H:%M:%S %Z`.", "local_time": "Convert feed timestamps to Home Assistant's configured local time before formatting.", "scan_interval": "How often to refresh the feed. The minimum interval is 1 minute.", @@ -37,14 +39,16 @@ }, "reconfigure": { "title": "Change feed", - "description": "Change the sensor name or the feed URL. The entity ID and history are kept.", + "description": "Change the sensor name or where the feed URL comes from. The entity ID and history are kept.", "data": { "name": "Name", - "feed_url": "Feed URL" + "feed_url": "Feed URL", + "feed_url_entity": "Feed URL entity" }, "data_description": { "name": "Friendly name for the sensor.", - "feed_url": "RSS or Atom feed URL. HTTP, HTTPS, and local file URLs are supported." + "feed_url": "RSS or Atom feed URL. HTTP, HTTPS, and local file URLs are supported. Leave empty to take the URL from an entity instead.", + "feed_url_entity": "Use instead of a feed URL: an input_text, text or template sensor whose state is the feed URL. Use a template sensor helper to build a URL that changes, e.g. with today's date. The feed is fetched again whenever its value changes. Entity states are limited to 255 characters." } } }, @@ -55,7 +59,10 @@ "invalid_feed": "The URL was downloaded but does not look like an RSS or Atom feed.", "scan_interval_too_short": "Refresh interval must be at least 1 minute.", "invalid_pattern": "Not a valid regular expression.", - "invalid_proxy": "Not a valid proxy URL. Use scheme://host:port, e.g. socks5h://192.168.1.10:1080." + "invalid_proxy": "Not a valid proxy URL. Use scheme://host:port, e.g. socks5h://192.168.1.10:1080.", + "url_or_entity": "Enter a feed URL or choose an entity that holds it, not both.", + "entity_no_url": "This entity has no value right now. Set it to the feed URL first.", + "entity_invalid_url": "This entity's value is not a valid HTTP, HTTPS or file URL." }, "abort": { "already_configured": "This feed is already configured.", diff --git a/custom_components/feedparser/translations/de.json b/custom_components/feedparser/translations/de.json index 7f4cb917..ac5f584c 100644 --- a/custom_components/feedparser/translations/de.json +++ b/custom_components/feedparser/translations/de.json @@ -7,6 +7,7 @@ "data": { "name": "Name", "feed_url": "Feed-URL", + "feed_url_entity": "Entität mit Feed-URL", "date_format": "Datumsformat", "local_time": "Datumsangaben in lokale Zeit umwandeln", "scan_interval": "Aktualisierungsintervall", @@ -21,7 +22,8 @@ }, "data_description": { "name": "Anzeigename für den Sensor.", - "feed_url": "URL eines RSS- oder Atom-Feeds. HTTP, HTTPS und lokale Datei-URLs werden unterstützt.", + "feed_url": "URL eines RSS- oder Atom-Feeds. HTTP, HTTPS und lokale Datei-URLs werden unterstützt. Leer lassen, um die URL stattdessen aus einer Entität zu übernehmen.", + "feed_url_entity": "Alternative zur Feed-URL: ein input_text, text oder Template-Sensor, dessen Zustand die Feed-URL ist. Mit einem Template-Sensor-Helfer lässt sich eine veränderliche URL bauen, z. B. mit dem heutigen Datum. Der Feed wird neu geladen, sobald sich der Wert ändert. Entitätszustände sind auf 255 Zeichen begrenzt.", "date_format": "Python-strftime-Format für Feed-Datumswerte, zum Beispiel `%a, %d %b %Y %H:%M:%S %Z`.", "local_time": "Feed-Zeitstempel vor der Formatierung in die in Home Assistant konfigurierte lokale Zeit umwandeln.", "scan_interval": "Wie oft der Feed aktualisiert wird. Das Mindestintervall beträgt 1 Minute.", @@ -37,14 +39,16 @@ }, "reconfigure": { "title": "Feed ändern", - "description": "Ändere den Sensornamen oder die Feed-URL. Entitäts-ID und Verlauf bleiben erhalten.", + "description": "Ändere den Sensornamen oder die Quelle der Feed-URL. Entitäts-ID und Verlauf bleiben erhalten.", "data": { "name": "Name", - "feed_url": "Feed-URL" + "feed_url": "Feed-URL", + "feed_url_entity": "Entität mit Feed-URL" }, "data_description": { "name": "Anzeigename für den Sensor.", - "feed_url": "URL eines RSS- oder Atom-Feeds. HTTP, HTTPS und lokale Datei-URLs werden unterstützt." + "feed_url": "URL eines RSS- oder Atom-Feeds. HTTP, HTTPS und lokale Datei-URLs werden unterstützt. Leer lassen, um die URL stattdessen aus einer Entität zu übernehmen.", + "feed_url_entity": "Alternative zur Feed-URL: ein input_text, text oder Template-Sensor, dessen Zustand die Feed-URL ist. Mit einem Template-Sensor-Helfer lässt sich eine veränderliche URL bauen, z. B. mit dem heutigen Datum. Der Feed wird neu geladen, sobald sich der Wert ändert. Entitätszustände sind auf 255 Zeichen begrenzt." } } }, @@ -55,7 +59,10 @@ "invalid_feed": "Die URL wurde geladen, scheint aber kein RSS- oder Atom-Feed zu sein.", "scan_interval_too_short": "Das Aktualisierungsintervall muss mindestens 1 Minute betragen.", "invalid_pattern": "Kein gültiger regulärer Ausdruck.", - "invalid_proxy": "Keine gültige Proxy-URL. Verwende schema://host:port, z. B. socks5h://192.168.1.10:1080." + "invalid_proxy": "Keine gültige Proxy-URL. Verwende schema://host:port, z. B. socks5h://192.168.1.10:1080.", + "url_or_entity": "Gib eine Feed-URL ein oder wähle eine Entität, die sie enthält – nicht beides.", + "entity_no_url": "Diese Entität hat derzeit keinen Wert. Setze sie zuerst auf die Feed-URL.", + "entity_invalid_url": "Der Wert dieser Entität ist keine gültige HTTP-, HTTPS- oder Datei-URL." }, "abort": { "already_configured": "Dieser Feed ist bereits konfiguriert.", diff --git a/custom_components/feedparser/translations/el.json b/custom_components/feedparser/translations/el.json index 4fa26a04..0e651f75 100644 --- a/custom_components/feedparser/translations/el.json +++ b/custom_components/feedparser/translations/el.json @@ -7,6 +7,7 @@ "data": { "name": "Όνομα", "feed_url": "URL ροής", + "feed_url_entity": "Οντότητα με URL ροής", "date_format": "Μορφή ημερομηνίας", "local_time": "Μετατροπή ημερομηνιών σε τοπική ώρα", "scan_interval": "Διάστημα ανανέωσης", @@ -21,7 +22,8 @@ }, "data_description": { "name": "Φιλικό όνομα για τον αισθητήρα.", - "feed_url": "URL ροής RSS ή Atom. Υποστηρίζονται HTTP, HTTPS και τοπικά URL αρχείων.", + "feed_url": "URL ροής RSS ή Atom. Υποστηρίζονται HTTP, HTTPS και τοπικά URL αρχείων. Αφήστε το κενό για να ληφθεί το URL από μια οντότητα.", + "feed_url_entity": "Εναλλακτικά του URL ροής: ένα input_text, text ή αισθητήρας προτύπου (template sensor) του οποίου η κατάσταση είναι το URL της ροής. Με έναν βοηθό αισθητήρα προτύπου μπορείτε να δημιουργήσετε URL που αλλάζει, π.χ. με τη σημερινή ημερομηνία. Η ροή ανακτάται ξανά κάθε φορά που αλλάζει η τιμή. Οι καταστάσεις οντοτήτων περιορίζονται σε 255 χαρακτήρες.", "date_format": "Μορφή Python strftime που χρησιμοποιείται για τις ημερομηνίες της ροής, για παράδειγμα `%a, %d %b %Y %H:%M:%S %Z`.", "local_time": "Μετατροπή των χρονικών σημάνσεων της ροής στην τοπική ώρα που έχει ρυθμιστεί στο Home Assistant πριν από τη μορφοποίηση.", "scan_interval": "Πόσο συχνά ανανεώνεται η ροή. Το ελάχιστο διάστημα είναι 1 λεπτό.", @@ -37,14 +39,16 @@ }, "reconfigure": { "title": "Αλλαγή ροής", - "description": "Αλλάξτε το όνομα του αισθητήρα ή τη διεύθυνση URL της ροής. Το αναγνωριστικό οντότητας και το ιστορικό διατηρούνται.", + "description": "Αλλάξτε το όνομα του αισθητήρα ή την πηγή του URL της ροής. Το αναγνωριστικό οντότητας και το ιστορικό διατηρούνται.", "data": { "name": "Όνομα", - "feed_url": "URL ροής" + "feed_url": "URL ροής", + "feed_url_entity": "Οντότητα με URL ροής" }, "data_description": { "name": "Φιλικό όνομα για τον αισθητήρα.", - "feed_url": "URL ροής RSS ή Atom. Υποστηρίζονται HTTP, HTTPS και τοπικά URL αρχείων." + "feed_url": "URL ροής RSS ή Atom. Υποστηρίζονται HTTP, HTTPS και τοπικά URL αρχείων. Αφήστε το κενό για να ληφθεί το URL από μια οντότητα.", + "feed_url_entity": "Εναλλακτικά του URL ροής: ένα input_text, text ή αισθητήρας προτύπου (template sensor) του οποίου η κατάσταση είναι το URL της ροής. Με έναν βοηθό αισθητήρα προτύπου μπορείτε να δημιουργήσετε URL που αλλάζει, π.χ. με τη σημερινή ημερομηνία. Η ροή ανακτάται ξανά κάθε φορά που αλλάζει η τιμή. Οι καταστάσεις οντοτήτων περιορίζονται σε 255 χαρακτήρες." } } }, @@ -55,7 +59,10 @@ "invalid_feed": "Η διεύθυνση URL φορτώθηκε, αλλά δεν φαίνεται να είναι ροή RSS ή Atom.", "scan_interval_too_short": "Το διάστημα ανανέωσης πρέπει να είναι τουλάχιστον 1 λεπτό.", "invalid_pattern": "Δεν είναι έγκυρη κανονική έκφραση.", - "invalid_proxy": "Μη έγκυρο URL διακομιστή μεσολάβησης. Χρησιμοποιήστε scheme://host:port, π.χ. socks5h://192.168.1.10:1080." + "invalid_proxy": "Μη έγκυρο URL διακομιστή μεσολάβησης. Χρησιμοποιήστε scheme://host:port, π.χ. socks5h://192.168.1.10:1080.", + "url_or_entity": "Εισαγάγετε ένα URL ροής ή επιλέξτε μια οντότητα που το περιέχει, όχι και τα δύο.", + "entity_no_url": "Αυτή η οντότητα δεν έχει τιμή αυτή τη στιγμή. Ορίστε πρώτα το URL της ροής.", + "entity_invalid_url": "Η τιμή αυτής της οντότητας δεν είναι έγκυρο URL HTTP, HTTPS ή αρχείου." }, "abort": { "already_configured": "Αυτή η ροή έχει ήδη ρυθμιστεί.", diff --git a/custom_components/feedparser/translations/en.json b/custom_components/feedparser/translations/en.json index 7be6480c..e09e46b3 100644 --- a/custom_components/feedparser/translations/en.json +++ b/custom_components/feedparser/translations/en.json @@ -7,6 +7,7 @@ "data": { "name": "Name", "feed_url": "Feed URL", + "feed_url_entity": "Feed URL entity", "date_format": "Date format", "local_time": "Convert dates to local time", "scan_interval": "Refresh interval", @@ -21,7 +22,8 @@ }, "data_description": { "name": "Friendly name for the sensor.", - "feed_url": "RSS or Atom feed URL. HTTP, HTTPS, and local file URLs are supported.", + "feed_url": "RSS or Atom feed URL. HTTP, HTTPS, and local file URLs are supported. Leave empty to take the URL from an entity instead.", + "feed_url_entity": "Use instead of a feed URL: an input_text, text or template sensor whose state is the feed URL. Use a template sensor helper to build a URL that changes, e.g. with today's date. The feed is fetched again whenever its value changes. Entity states are limited to 255 characters.", "date_format": "Python strftime format used for feed dates, for example `%a, %d %b %Y %H:%M:%S %Z`.", "local_time": "Convert feed timestamps to Home Assistant's configured local time before formatting.", "scan_interval": "How often to refresh the feed. The minimum interval is 1 minute.", @@ -37,14 +39,16 @@ }, "reconfigure": { "title": "Change feed", - "description": "Change the sensor name or the feed URL. The entity ID and history are kept.", + "description": "Change the sensor name or where the feed URL comes from. The entity ID and history are kept.", "data": { "name": "Name", - "feed_url": "Feed URL" + "feed_url": "Feed URL", + "feed_url_entity": "Feed URL entity" }, "data_description": { "name": "Friendly name for the sensor.", - "feed_url": "RSS or Atom feed URL. HTTP, HTTPS, and local file URLs are supported." + "feed_url": "RSS or Atom feed URL. HTTP, HTTPS, and local file URLs are supported. Leave empty to take the URL from an entity instead.", + "feed_url_entity": "Use instead of a feed URL: an input_text, text or template sensor whose state is the feed URL. Use a template sensor helper to build a URL that changes, e.g. with today's date. The feed is fetched again whenever its value changes. Entity states are limited to 255 characters." } } }, @@ -55,7 +59,10 @@ "invalid_feed": "The URL was downloaded but does not look like an RSS or Atom feed.", "scan_interval_too_short": "Refresh interval must be at least 1 minute.", "invalid_pattern": "Not a valid regular expression.", - "invalid_proxy": "Not a valid proxy URL. Use scheme://host:port, e.g. socks5h://192.168.1.10:1080." + "invalid_proxy": "Not a valid proxy URL. Use scheme://host:port, e.g. socks5h://192.168.1.10:1080.", + "url_or_entity": "Enter a feed URL or choose an entity that holds it, not both.", + "entity_no_url": "This entity has no value right now. Set it to the feed URL first.", + "entity_invalid_url": "This entity's value is not a valid HTTP, HTTPS or file URL." }, "abort": { "already_configured": "This feed is already configured.", diff --git a/custom_components/feedparser/yaml_import.py b/custom_components/feedparser/yaml_import.py index 4e0cdc6a..ede83b63 100644 --- a/custom_components/feedparser/yaml_import.py +++ b/custom_components/feedparser/yaml_import.py @@ -19,7 +19,7 @@ from homeassistant.helpers import issue_registry as ir from homeassistant.util import slugify -from .const import CONF_FEED_URL, CONF_MANAGED_BY_YAML, DOMAIN +from .const import CONF_FEED_URL, CONF_FEED_URL_ENTITY, CONF_MANAGED_BY_YAML, DOMAIN if TYPE_CHECKING: from collections.abc import Mapping @@ -66,7 +66,9 @@ async def async_import_yaml_sensor( """ import_data = {key: value for key, value in config.items() if key != CONF_PLATFORM} name = str(import_data.get(CONF_NAME, "")) - feed_url = str(import_data.get(CONF_FEED_URL, "")) + feed_url = str( + import_data.get(CONF_FEED_URL) or import_data.get(CONF_FEED_URL_ENTITY) or "", + ) result = await hass.config_entries.flow.async_init( DOMAIN, diff --git a/tests/test_url_entity.py b/tests/test_url_entity.py new file mode 100644 index 00000000..4308499f --- /dev/null +++ b/tests/test_url_entity.py @@ -0,0 +1,310 @@ +"""Tests for taking the feed URL from an entity's state (issue #60).""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import pytest +from homeassistant import config_entries +from homeassistant.const import CONF_NAME, STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.data_entry_flow import FlowResultType +from pytest_homeassistant_custom_component.common import MockConfigEntry +from test_integration import ( + get_state, + import_yaml, + options, + setup_yaml, + start_reconfigure, + write_feed, +) + +from custom_components.feedparser.compat import vol +from custom_components.feedparser.const import ( + CONF_EXCLUSIONS, + CONF_FEED_URL, + CONF_FEED_URL_ENTITY, + CONF_INCLUSIONS, + CONF_MANAGED_BY_YAML, + DOMAIN, + ENTRY_VERSION, +) +from custom_components.feedparser.sensor import PLATFORM_SCHEMA + +if TYPE_CHECKING: + from homeassistant.config_entries import ConfigFlowResult + from homeassistant.core import HomeAssistant + +pytestmark = pytest.mark.usefixtures("enable_custom_integrations") + +URL_ENTITY = "input_text.feed_url" + + +async def submit_user_form( + hass: HomeAssistant, + name: str = "Test Feed", + **source: str, +) -> ConfigFlowResult: + """Run the setup form with a feed source (feed_url and/or feed_url_entity).""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_USER}, + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_NAME: name, **source} | options(), + ) + await hass.async_block_till_done() + return result + + +async def add_entity_entry(hass: HomeAssistant) -> MockConfigEntry: + """Add and set up an entry that reads its URL from URL_ENTITY.""" + entry = MockConfigEntry( + domain=DOMAIN, + version=ENTRY_VERSION, + title="Test Feed", + data={CONF_NAME: "Test Feed", CONF_FEED_URL_ENTITY: URL_ENTITY}, + options={**options(), CONF_INCLUSIONS: ["title"], CONF_EXCLUSIONS: []}, + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + return entry + + +def titles(hass: HomeAssistant) -> list[Any]: + """Return the titles of the test sensor's entries.""" + return [e["title"] for e in get_state(hass).attributes["entries"]] + + +async def test_user_flow_with_url_entity(hass: HomeAssistant, tmp_path: Path) -> None: + """A feed can be set up from an entity whose state is the URL.""" + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "a.xml", ["one", "two"])) + + result = await submit_user_form(hass, feed_url_entity=URL_ENTITY) + + assert result["type"] is FlowResultType.CREATE_ENTRY + # only the entity is stored, never the URL it held at setup + assert result["data"] == {CONF_NAME: "Test Feed", CONF_FEED_URL_ENTITY: URL_ENTITY} + assert get_state(hass).state == "2" + assert titles(hass) == ["one", "two"] + + +async def test_url_change_refreshes_feed(hass: HomeAssistant, tmp_path: Path) -> None: + """Changing the entity's value fetches the new feed right away.""" + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "a.xml", ["old"])) + await add_entity_entry(hass) + assert titles(hass) == ["old"] + + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "b.xml", ["new", "newer"])) + await hass.async_block_till_done() + + assert titles(hass) == ["new", "newer"] + + +@pytest.mark.parametrize("value", [STATE_UNKNOWN, STATE_UNAVAILABLE]) +async def test_url_entity_without_value_does_not_refresh( + hass: HomeAssistant, + tmp_path: Path, + value: str, +) -> None: + """The entity briefly losing its value (e.g. a reload) keeps the entries.""" + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "a.xml", ["one"])) + entry = await add_entity_entry(hass) + + hass.states.async_set(URL_ENTITY, value) + await hass.async_block_till_done() + assert get_state(hass).state == "1" + + # the next poll can't fetch anything, so the sensor becomes unavailable + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert get_state(hass).state == STATE_UNAVAILABLE + + +async def test_url_entity_missing_at_setup_retries(hass: HomeAssistant) -> None: + """If the URL entity doesn't exist yet at startup, setup is retried.""" + entry = await add_entity_entry(hass) + assert entry.state is config_entries.ConfigEntryState.SETUP_RETRY + + +async def test_unload_stops_tracking(hass: HomeAssistant, tmp_path: Path) -> None: + """After unloading, changes to the URL entity are ignored.""" + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "a.xml", ["one"])) + entry = await add_entity_entry(hass) + assert await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "b.xml", ["x", "y"])) + await hass.async_block_till_done() + assert entry.state is config_entries.ConfigEntryState.NOT_LOADED + assert get_state(hass).state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize( + ("entity_value", "source", "errors"), + [ + (None, {}, {"base": "url_or_entity"}), + ( + None, + {CONF_FEED_URL: "https://e.x/rss", CONF_FEED_URL_ENTITY: URL_ENTITY}, + {"base": "url_or_entity"}, + ), + ( + None, + {CONF_FEED_URL_ENTITY: URL_ENTITY}, + {CONF_FEED_URL_ENTITY: "entity_no_url"}, + ), + ( + STATE_UNKNOWN, + {CONF_FEED_URL_ENTITY: URL_ENTITY}, + {CONF_FEED_URL_ENTITY: "entity_no_url"}, + ), + ( + "ftp://e.x/rss", + {CONF_FEED_URL_ENTITY: URL_ENTITY}, + {CONF_FEED_URL_ENTITY: "entity_invalid_url"}, + ), + ( + "page", + {CONF_FEED_URL_ENTITY: URL_ENTITY}, + {CONF_FEED_URL_ENTITY: "invalid_feed"}, + ), + ], + ids=["neither", "both", "missing", "unknown", "bad_scheme", "not_a_feed"], +) +async def test_user_flow_source_errors( + hass: HomeAssistant, + tmp_path: Path, + entity_value: str | None, + source: dict[str, str], + errors: dict[str, str], +) -> None: + """Problems with the feed source are reported on the right field.""" + if entity_value == "page": + page = tmp_path / "page.html" + page.write_text("hi") + entity_value = page.as_uri() + if entity_value is not None: + hass.states.async_set(URL_ENTITY, entity_value) + + result = await submit_user_form(hass, **source) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == errors + + +async def test_same_entity_and_name_is_rejected( + hass: HomeAssistant, + tmp_path: Path, +) -> None: + """Two sensors on one URL entity need different names, like typed URLs.""" + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "a.xml", ["one"])) + await add_entity_entry(hass) + + result = await submit_user_form(hass, "test feed", feed_url_entity=URL_ENTITY) + assert result["errors"] == {CONF_NAME: "already_configured"} + + result = await submit_user_form(hass, "Other", feed_url_entity=URL_ENTITY) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_reconfigure_switches_between_url_and_entity( + hass: HomeAssistant, + tmp_path: Path, +) -> None: + """Reconfigure can move a feed to a URL entity and back, keeping one source.""" + url = write_feed(tmp_path / "a.xml", ["typed"]) + hass.states.async_set( + URL_ENTITY, + write_feed(tmp_path / "b.xml", ["from", "entity"]), + ) + entry = MockConfigEntry( + domain=DOMAIN, + version=ENTRY_VERSION, + title="Test Feed", + data={CONF_NAME: "Test Feed", CONF_FEED_URL: url}, + options={**options(), CONF_INCLUSIONS: ["title"], CONF_EXCLUSIONS: []}, + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert titles(hass) == ["typed"] + + result = await start_reconfigure(hass, entry) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_NAME: "Test Feed", CONF_FEED_URL_ENTITY: URL_ENTITY}, + ) + assert result["reason"] == "reconfigure_successful" + await hass.async_block_till_done() + assert entry.data == {CONF_NAME: "Test Feed", CONF_FEED_URL_ENTITY: URL_ENTITY} + assert titles(hass) == ["from", "entity"] + + result = await start_reconfigure(hass, entry) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_NAME: "Test Feed", CONF_FEED_URL: url}, + ) + assert result["reason"] == "reconfigure_successful" + await hass.async_block_till_done() + assert entry.data == {CONF_NAME: "Test Feed", CONF_FEED_URL: url} + assert titles(hass) == ["typed"] + + # no longer tracking the entity + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "c.xml", ["ignored"])) + await hass.async_block_till_done() + assert titles(hass) == ["typed"] + + +async def test_yaml_feed_with_url_entity(hass: HomeAssistant, tmp_path: Path) -> None: + """A YAML sensor can read its URL from an entity and follows its changes.""" + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "a.xml", ["one"])) + await setup_yaml(hass, {"name": "Test Feed", "feed_url_entity": URL_ENTITY}) + + entry = hass.config_entries.async_entries(DOMAIN)[0] + assert entry.data == { + CONF_NAME: "Test Feed", + CONF_FEED_URL_ENTITY: URL_ENTITY, + CONF_MANAGED_BY_YAML: True, + } + assert titles(hass) == ["one"] + + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "b.xml", ["two", "x"])) + await hass.async_block_till_done() + assert titles(hass) == ["two", "x"] + + +async def test_yaml_switches_from_url_to_entity( + hass: HomeAssistant, + tmp_path: Path, +) -> None: + """Changing a YAML sensor from feed_url to feed_url_entity replaces the URL.""" + url = write_feed(tmp_path / "a.xml", ["typed"]) + hass.states.async_set(URL_ENTITY, write_feed(tmp_path / "b.xml", ["entity"])) + await setup_yaml(hass, {"name": "Test Feed", "feed_url": url}) + assert titles(hass) == ["typed"] + + await import_yaml(hass, name="Test Feed", feed_url_entity=URL_ENTITY) + + entry = hass.config_entries.async_entries(DOMAIN)[0] + assert CONF_FEED_URL not in entry.data + assert entry.data[CONF_FEED_URL_ENTITY] == URL_ENTITY + assert titles(hass) == ["entity"] + + +@pytest.mark.parametrize( + "source", + [ + {}, + {"feed_url": "https://e.x/rss", "feed_url_entity": URL_ENTITY}, + {"feed_url_entity": "light.kitchen"}, + {"feed_url_entity": "not an entity"}, + ], + ids=["neither", "both", "wrong_domain", "malformed"], +) +def test_yaml_schema_rejects_bad_source(source: dict[str, str]) -> None: + """YAML needs exactly one of feed_url and an input_text/text/sensor entity.""" + with pytest.raises(vol.Invalid): + PLATFORM_SCHEMA({"platform": DOMAIN, "name": "Test Feed", **source})