Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added processing of URL as template #87

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions custom_components/feedparser/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_NAME, CONF_SCAN_INTERVAL
from homeassistant.util import dt
from homeassistant.helpers import config_validation as cv, template

if TYPE_CHECKING:
from homeassistant.core import HomeAssistant
Expand Down Expand Up @@ -41,7 +42,7 @@
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_FEED_URL): cv.string,
vol.Required(CONF_FEED_URL): cv.template,
vol.Required(CONF_DATE_FORMAT, default=DEFAULT_DATE_FORMAT): cv.string,
vol.Optional(CONF_LOCAL_TIME, default=False): cv.boolean,
vol.Optional(CONF_SHOW_TOPN, default=DEFAULT_TOPN): cv.positive_int,
Expand All @@ -61,10 +62,16 @@ async def async_setup_platform(
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Feedparser sensor."""
feed_url=config[CONF_FEED_URL]

if isinstance(feed_url, template.Template):
_LOGGER.debug("Feed is template: %s", feed_url)
template.attach(hass, feed_url)

async_add_devices(
[
FeedParserSensor(
feed=config[CONF_FEED_URL],
feed=feed_url,
name=config[CONF_NAME],
date_format=config[CONF_DATE_FORMAT],
show_topn=config[CONF_SHOW_TOPN],
Expand Down Expand Up @@ -106,7 +113,19 @@ def __init__(

def update(self: FeedParserSensor) -> None:
"""Parse the feed and update the state of the sensor."""
parsed_feed: FeedParserDict = feedparser.parse(self._feed)
if isinstance(self._feed, template.Template):
_LOGGER.debug("Evaluating feed template: %s", self._feed)
tmp = self._feed.async_render(None, limited=False, parse_result=False)
if tmp in ['unknown','none','unavailable','null']:
_LOGGER.warn("Template failure: %s; template: %s", tmp, self._feed)
return False
else:
_LOGGER.debug("Feed URL: %s from template: %s", tmp, self._feed)
feed_url = tmp
else:
feed_url = self._feed

parsed_feed: FeedParserDict = feedparser.parse(feed_url)

if not parsed_feed:
self._attr_native_value = None
Expand Down
Loading