core/homeassistant/components/feedreader/__init__.py

225 lines
8.4 KiB
Python
Raw Normal View History

"""Support for RSS/Atom feeds."""
from datetime import datetime, timedelta
2016-04-19 15:14:36 +00:00
from logging import getLogger
from os.path import exists
import pickle
from threading import Lock
2016-09-02 04:30:49 +00:00
2019-10-08 14:14:50 +00:00
import feedparser
import voluptuous as vol
from homeassistant.const import CONF_SCAN_INTERVAL, EVENT_HOMEASSISTANT_START
2016-09-02 04:30:49 +00:00
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_time_interval
2016-04-19 15:14:36 +00:00
_LOGGER = getLogger(__name__)
2016-09-02 04:30:49 +00:00
2019-07-31 19:25:30 +00:00
CONF_URLS = "urls"
CONF_MAX_ENTRIES = "max_entries"
DEFAULT_MAX_ENTRIES = 20
DEFAULT_SCAN_INTERVAL = timedelta(hours=1)
2016-09-02 04:30:49 +00:00
2019-07-31 19:25:30 +00:00
DOMAIN = "feedreader"
2016-09-02 04:30:49 +00:00
2019-07-31 19:25:30 +00:00
EVENT_FEEDREADER = "feedreader"
2016-09-02 04:30:49 +00:00
2019-07-31 19:25:30 +00:00
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: {
vol.Required(CONF_URLS): vol.All(cv.ensure_list, [cv.url]),
vol.Optional(
CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
): cv.time_period,
vol.Optional(
CONF_MAX_ENTRIES, default=DEFAULT_MAX_ENTRIES
): cv.positive_int,
}
},
extra=vol.ALLOW_EXTRA,
)
2016-09-02 04:30:49 +00:00
def setup(hass, config):
"""Set up the Feedreader component."""
2016-09-02 04:30:49 +00:00
urls = config.get(DOMAIN)[CONF_URLS]
scan_interval = config.get(DOMAIN).get(CONF_SCAN_INTERVAL)
max_entries = config.get(DOMAIN).get(CONF_MAX_ENTRIES)
data_file = hass.config.path(f"{DOMAIN}.pickle")
2016-09-02 04:30:49 +00:00
storage = StoredData(data_file)
2019-07-31 19:25:30 +00:00
feeds = [
FeedManager(url, scan_interval, max_entries, hass, storage) for url in urls
]
2016-09-02 04:30:49 +00:00
return len(feeds) > 0
2016-04-19 15:14:36 +00:00
class FeedManager:
"""Abstraction over Feedparser module."""
2016-04-19 15:14:36 +00:00
def __init__(self, url, scan_interval, max_entries, hass, storage):
"""Initialize the FeedManager object, poll as per scan interval."""
2016-04-19 15:14:36 +00:00
self._url = url
self._scan_interval = scan_interval
self._max_entries = max_entries
2016-04-19 15:14:36 +00:00
self._feed = None
self._hass = hass
self._firstrun = True
self._storage = storage
self._last_entry_timestamp = None
self._last_update_successful = False
self._has_published_parsed = False
self._event_type = EVENT_FEEDREADER
self._feed_id = url
2019-07-31 19:25:30 +00:00
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, lambda _: self._update())
self._init_regular_updates(hass)
2016-04-19 15:14:36 +00:00
def _log_no_entries(self):
"""Send no entries log at debug level."""
_LOGGER.debug("No new entries to be published in feed %s", self._url)
2016-04-19 15:14:36 +00:00
def _init_regular_updates(self, hass):
"""Schedule regular updates at the top of the clock."""
2019-07-31 19:25:30 +00:00
track_time_interval(hass, lambda now: self._update(), self._scan_interval)
@property
def last_update_successful(self):
"""Return True if the last feed update was successful."""
return self._last_update_successful
2016-04-19 15:14:36 +00:00
def _update(self):
"""Update the feed and publish new entries to the event bus."""
_LOGGER.info("Fetching new data from feed %s", self._url)
2019-07-31 19:25:30 +00:00
self._feed = 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"),
)
2016-04-19 15:14:36 +00:00
if not self._feed:
_LOGGER.error("Error fetching feed data from %s", self._url)
self._last_update_successful = False
2016-04-19 15:14:36 +00:00
else:
# 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.
2020-02-28 11:41:21 +00:00
# If an error is detected here, log warning message but continue
# processing the feed entries if present.
2016-04-19 15:14:36 +00:00
if self._feed.bozo != 0:
2020-02-28 11:41:21 +00:00
_LOGGER.warning(
"Possible issue parsing feed %s: %s",
self._url,
self._feed.bozo_exception,
2019-07-31 19:25:30 +00:00
)
2016-04-19 15:14:36 +00:00
# Using etag and modified, if there's no new data available,
# the entries list will be empty
if self._feed.entries:
2019-07-31 19:25:30 +00:00
_LOGGER.debug(
"%s entri(es) available in feed %s",
len(self._feed.entries),
self._url,
)
self._filter_entries()
2016-04-19 15:14:36 +00:00
self._publish_new_entries()
if self._has_published_parsed:
self._storage.put_timestamp(
2019-07-31 19:25:30 +00:00
self._feed_id, self._last_entry_timestamp
)
2016-04-19 15:14:36 +00:00
else:
self._log_no_entries()
self._last_update_successful = True
_LOGGER.info("Fetch from feed %s completed", self._url)
def _filter_entries(self):
"""Filter the entries provided and return the ones to keep."""
if len(self._feed.entries) > self._max_entries:
2019-07-31 19:25:30 +00:00
_LOGGER.debug(
"Processing only the first %s entries in feed %s",
2019-07-31 19:25:30 +00:00
self._max_entries,
self._url,
)
self._feed.entries = self._feed.entries[0 : self._max_entries]
def _update_and_fire_entry(self, entry):
"""Update last_entry_timestamp and fire entry."""
# Check if the entry has a published date.
if "published_parsed" in entry.keys() and entry.published_parsed:
# We are lucky, `published_parsed` data available, let's make use of
# it to publish only new available entries since the last run
self._has_published_parsed = True
self._last_entry_timestamp = max(
2019-07-31 19:25:30 +00:00
entry.published_parsed, self._last_entry_timestamp
)
else:
self._has_published_parsed = False
2019-07-31 19:25:30 +00:00
_LOGGER.debug("No published_parsed info available for entry %s", entry)
entry.update({"feed_url": self._url})
self._hass.bus.fire(self._event_type, entry)
2016-04-19 15:14:36 +00:00
def _publish_new_entries(self):
"""Publish new entries to the event bus."""
new_entries = False
self._last_entry_timestamp = self._storage.get_timestamp(self._feed_id)
if self._last_entry_timestamp:
self._firstrun = False
else:
# Set last entry timestamp as epoch time if not available
2019-07-31 19:25:30 +00:00
self._last_entry_timestamp = datetime.utcfromtimestamp(0).timetuple()
2016-04-19 15:14:36 +00:00
for entry in self._feed.entries:
if self._firstrun or (
2019-07-31 19:25:30 +00:00
"published_parsed" in entry.keys()
and entry.published_parsed > self._last_entry_timestamp
):
self._update_and_fire_entry(entry)
2016-04-19 15:14:36 +00:00
new_entries = True
else:
_LOGGER.debug("Entry %s already processed", entry)
2016-04-19 15:14:36 +00:00
if not new_entries:
self._log_no_entries()
self._firstrun = False
2016-04-19 15:14:36 +00:00
class StoredData:
"""Abstraction over pickle data storage."""
def __init__(self, data_file):
"""Initialize pickle data storage."""
self._data_file = data_file
self._lock = Lock()
self._cache_outdated = True
self._data = {}
self._fetch_data()
def _fetch_data(self):
"""Fetch data stored into pickle file."""
if self._cache_outdated and exists(self._data_file):
try:
_LOGGER.debug("Fetching data from file %s", self._data_file)
2019-07-31 19:25:30 +00:00
with self._lock, open(self._data_file, "rb") as myfile:
self._data = pickle.load(myfile) or {}
self._cache_outdated = False
except: # noqa: E722 pylint: disable=bare-except
2019-07-31 19:25:30 +00:00
_LOGGER.error(
"Error loading data from pickled file %s", self._data_file
)
def get_timestamp(self, feed_id):
"""Return stored timestamp for given feed id (usually the url)."""
self._fetch_data()
return self._data.get(feed_id)
def put_timestamp(self, feed_id, timestamp):
"""Update timestamp for given feed id (usually the url)."""
self._fetch_data()
2019-07-31 19:25:30 +00:00
with self._lock, open(self._data_file, "wb") as myfile:
self._data.update({feed_id: timestamp})
2019-07-31 19:25:30 +00:00
_LOGGER.debug(
"Overwriting feed %s timestamp in storage file %s",
feed_id,
self._data_file,
)
try:
pickle.dump(self._data, myfile)
except: # noqa: E722 pylint: disable=bare-except
2019-07-31 19:25:30 +00:00
_LOGGER.error("Error saving pickled data to %s", self._data_file)
self._cache_outdated = True