- feed2exec Documentation
- ONE EXAMPLES
- TWO INSTALLATION
- THREE WHY THE NAME?
- 3.1 feed2exec manual page
- 3.1.1 Synopsis
- 3.1.2 Description
- 3.1.3 Options
- 3.1.4 Examples
- 3.1.5 Commands
- 3.1.6 Files
- this section will apply to all feeds [DEFAULT] # special folder location for maildir. I use this when I have multiple # accounts synchronized with Offlineimap mailbox = ~/Maildir/Remote/ # a feed to store NASA breaking news entry in a “nasa” subfolder # this also demonstrates the droptitle filter [NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss folder = nasa filter = feed2exec.plugins.droptitle filter_args = trump # some maildir storage require dots to get subfolders. for example, # this will store messages in INBOX/feeds/images/ on Dovecot [NASA image of the day] url = https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss folder = .feeds.images # same feed, but save to wayback machine [NASA IOTD wayback] url = https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss output = feed2exec.plugins.wayback # this demonstrates the emptysummary filter, which fixes GitHub feeds # that lack a proper summary [restic] url = https://github.com/restic/restic/tags.atom filter = feed2exec.plugins.emptysummary # saving to a mbox folder, one file per feed instead of one file per item [International Space Station Reports] url = http://blogs.nasa.gov/stationreport/feed/ mailbox = ~/Mail/ folder = stationreport.mbx # simple generic exec call example: check for broken links using linkchecker [NASA linkchecker] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = feed2exec.plugins.exec args = linkchecker –check-extern –no-robots –recursion-level 1 –quiet ‘{item.link} ‘
- same, but with a Ikiwiki RSS feed, which needs fixing [Ikiwiki linkchecker] url = http://ikiwiki.info/recentchanges/index.rss output = feed2exec.plugins.exec filter = feed2exec.plugins.ikiwiki_recentchanges
- retweet hurricane news [NASA Hurricane breaking news] url = https://www.nasa.gov/rss/dyn/hurricaneupdate.rss output = feed2exec.plugins.exec args = tweet “{item.title:.40s} {item.link:.100s}” # same, but on the mastodon network ## we can have multiple entries with the same URL without problems, as # long as the feed name is different. it does mean that the feed will # be fetched and parsed multiple times, unfortunately. ## this could be improved to include the ‘{item.summary} ‘ and extra markup, # for example. [NASA Hurricane breaking news - Mastodon] url = https://www.nasa.gov/rss/dyn/hurricaneupdate.rss output = feed2exec.plugins.exec # unfortunately, this will noisily report the URL of the posted link, # which you may not want. to avoid that, encourage upstream to do the # right thing: https://github.com/ihabunek/toot/issues/46 … or use # another tool listed here: # https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/Apps.md args = toot post “{item.title} {item.link}” # output is disabled here. feed will be fetched and parsed, but no # toot will be sent catchup = True # same, but on the Pump.io network [NASA Hurricane breaking news - Pump] url = https://www.nasa.gov/rss/dyn/hurricaneupdate.rss output = feed2exec.plugins.exec args = p post note “{item.title} {item.link}” # crude podcast client [NASA What up?] url = https://www.nasa.gov/rss/dyn/whats_up.rss output = feed2exec.plugins.exec # XXX: this doesn ‘t handle errors properly: if there is a feed without # enclosures, the whole thing will crash. args = wget -P /srv/podcasts/nasa/ “{item.enclosures[0].href}” # feed is paused here. feed will not be fetched and parsed at all and # no post will be sent. pause = True # download torrents linked from a RSS feed [torrents] url = http://example.com/torrents.rss output = feed2exec.plugins.exec args = transmission-remote -a ‘{item.link} ‘ -w ‘/srv/incoming ‘
- same thing with an actual plugin [torrents] url = http://example.com/torrents.rss output = feed2exec.plugins.transmission args = seedbox.example.com folder = /srv/incoming
- 3.1.7 Limitations
- 3.1.8 See also
- 3.2 Design
- 3.2.1 Quick tour
- 3.2.2 Plugin system
- 3.2.3 Concurrent processing
- 3.2.4 Test suite
- 3.2.5 Comparison
- 3.2.6 Related software
- 3.3 API documentation
- 3.3.1 Controller module
- 3.3.2 Model
- 3.3.3 Main entry point
- 3.3.4 Plugins
- 3.3.5 Utilities
- 3.4 Plugins
- 3.4.1 Output plugins
- 3.4.2 Filter plugins
- 3.4.3 Writing new plugins
- only operate on items that actually have a link
- make a safe path from the item name
- put the file in the archive directory
- only operate on items that actually have a link
- tell the user what ‘s going on, if verbose # otherwise, we try to stay silent if all goes well
- open the file
- write the response
- make a safe path from the item name
- take the archive dir from the user or use the default
- put the file in the archive directory
- […] # rest of the function unchanged
- fetch the URL in memory
- make sure we retry next time
- open the file
- write the response
- fetch the URL in memory
- fetch the URL in memory
#feed2exec Documentation
feed2exec is a simple program that runs custom actions on new RSS feed items (or whatever feedparser can read). It currently has support for writing into mailboxes (Maildir folders) or executing commands, but more actions can be easily implemented through plugins. Email are saved as multipart plain/HTML and can be sent to arbitrary folders.
CONTENTS 1feed2exec Documentation, Release ??? 2 CONTENTS CHAPTER
#ONE EXAMPLES
Simple run with no side effects:
feed2exec parse https://www.nasa.gov/rss/dyn/breaking_news.rss –output echo –args ‘
˓→
{item.title} ‘
Saving feed items to a Maildir folder:
feed2exec add “NASA breaking news” https://www.nasa.gov/rss/dyn/breaking_news.rss –
˓→
folder nasa feed2exec fetch
This creates the equivalent of this configuration file in ~/.config/feed2exec.ini :
[DEFAULT] output = feed2exec.plugins.maildir mailbox = ~/Maildir [NASA breaking news] folder = nasa url = https://www.nasa.gov/rss/dyn/breaking_news.rss
Send new feed items to Transmission:
feed2exec add “Example torrent list” http://example.com/torrents/feed –output␣
˓→
transmission –folder /srv/incoming
Send new feed items to Mastodon, using the toot commandline client:
feed2exec add “My site” http://example.com/blog/feed –output exec –args ‘toot post “
˓→
{item.title} {item.link} “’
Send new feed items to Twitter, using the tweet commandline client from python-twitter:
feed2exec add “My site on twitter” http://example.com/blog/feed –output exec –args
˓→
‘tweet “ {item.title:.40s} {item.link:.100s} “’
Show feed contents:
feed2exec add “NASA breaking news” https://www.nasa.gov/rss/dyn/breaking_news.rss –
˓→
output echo –args “ {item.title} {item.link} “feed2exec fetch
3feed2exec Documentation, Release ???
Multiple feeds can also be added with the OPML import command. See the usage document for more information including known issues and limitations.
4 Chapter 1. Examples CHAPTER
#TWO INSTALLATION
This can be installed using the normal Python procedures:
pip install feed2exec
It can also be installed from source, using:
pip install .
It can also be ran straight from the source, using:
python -m feed2exec
Important: feed2exec is explicitly written for Python 3. It may be possible to backport it to Python 2 if there is sufficient demand, but there are too many convenient Python3 constructs to make this useful. Furthermore, all dependencies are well-packaged for Py3 and the platform is widely available. Upgrade already. The program may also be available as an official package from your Linux distribution. Source, documentation and issues are available on GitLab.
Note: feed2exec relies on the feedparser module to parse feeds and as such has all the bugs and limitations of that modules. In particular, feeds with non-standard dates will break the parser, unless the dateparser module is installed.
5feed2exec Documentation, Release ??? 6 Chapter 2. Installation CHAPTER
#THREE WHY THE NAME?
There are already feed2tweet and feed2imap out there so I figured I would just reuse the prefix and extend both programs at once. Contents:
#3.1 feed2exec manual page
#3.1.1 Synopsis
feed2exec {add,ls,rm,fetch,import,export}
#3.1.2 Description
This command will take a configured set of feeds and fire specific plugin for every new item found in the feed.
#3.1.3 Options
–version Show the version and exit.
–loglevel choose specific log level [default: WARNING]
-v, –verbose show what is happening (loglevel: VERBOSE)
-d, –debug show debugging information (loglevel: DEBUG)
–syslog LEVEL send LEVEL logs to syslog
–config TEXT use a different configuration file
–database DB use a different database
-h, –help Show this message and exit.
7feed2exec Documentation, Release ???
#3.1.4 Examples
Simple run with no side effects:
feed2exec parse https://www.nasa.gov/rss/dyn/breaking_news.rss –output echo –args ‘
˓→
{item.title} ‘
Saving feed items to a Maildir folder:
feed2exec add “NASA breaking news” https://www.nasa.gov/rss/dyn/breaking_news.rss –
˓→
folder nasa feed2exec fetch
This creates the equivalent of this configuration file in ~/.config/feed2exec.ini :
[DEFAULT] output = feed2exec.plugins.maildir mailbox = ~/Maildir [NASA breaking news] folder = nasa url = https://www.nasa.gov/rss/dyn/breaking_news.rss
Send new feed items to Transmission:
feed2exec add “Example torrent list” http://example.com/torrents/feed –output␣
˓→
transmission –folder /srv/incoming
Send new feed items to Mastodon, using the toot commandline client:
feed2exec add “My site” http://example.com/blog/feed –output exec –args ‘toot post “
˓→
{item.title} {item.link} “’
Send new feed items to Twitter, using the tweet commandline client from python-twitter:
feed2exec add “My site on twitter” http://example.com/blog/feed –output exec –args
˓→
‘tweet “ {item.title:.40s} {item.link:.100s} “’
Show feed contents:
feed2exec add “NASA breaking news” https://www.nasa.gov/rss/dyn/breaking_news.rss –
˓→
output echo –args “ {item.title} {item.link} “feed2exec fetch
#3.1.5 Commands
• parse
• fetch
• add
• ls
8 Chapter 3. Why the name? feed2exec Documentation, Release ???
• rm
• import
• export
parse
Usage:
parse URL [–output PLUGIN [–args ARG [ARG […]]] [–filter PLUGIN] [–filter_args ARG [ARG […]]] [–mailbox PATH] [–folder PATH]
The parse command loads and parses a single feed, without touching the database. This is similar to calling add then
fetch on a single feed, but the feed is not kept in the configuration. This is designed to make quick tests with a new feed. The arguments are the same as the add command.
fetch
Usage:
fetch [–parallel | -p | –jobs N | -j N] [–force | -f] [–pattern pattern] |
The fetch command iterates through all the configured feeds or those matching the pattern substring if provided. Options:
–pattern TEXT only fetch feeds matching name or URL
–parallel parse feeds in the background to improve performance
-j, –jobs N start N jobs in parallel, implies –parallel which defaults to the number of CPUs detected on the machine
-f, –force skip reading and writing the cache and will consider all entries as new
-n, –catchup tell output plugins plugins to simulate their actions
add
Usage:
add NAME URL [–output PLUGIN [–args ARG [ARG […]]] [–filter PLUGIN] [–filter_args ARG [ARG […]]] [–mailbox PATH] [–folder PATH]
The add command adds the given feed NAME that will be fetched from the provided URL .Options:
3.1. feed2exec manual page 9feed2exec Documentation, Release ???
–output PLUGIN use PLUGIN as an output module. defaults to maildir to store in a mailbox. use null or echo to just fetch the feed without doing any-thing. Modules are searched in the feed2exec.plugins package unless the name contains a dot in which case the whole Python search path is used.
–args ARGS pass arguments ARGS to the output plugin. supports interpolation of feed parameters using, for example {title}
–filter PLUGIN filter feed items through the PLUGIN filter plugin
–filter_args ARGS arguments passed to the filter plugin
–mailbox PATH folder to store email into, defaults to ~/Maildir .
–folder PATH subfolder to store the email into Those parameters are documented more extensively in their equivalent settings in the configuration file, see below.
ls
The ls command lists all configured feeds as JSON packets.
rm
Usage:
rm NAME
Remove the feed named NAME from the configuration.
import
Usage:
import PATH
Import feeds from the file named PATH. The file is expected to have outline elements and only the title and xmlUrl
elements are imported, as NAME and URL parameters, respectively.
export
Usage:
export PATH
Export feeds into the file named PATH. The file will use the feed NAME elements as title and the URL as xmlUrl .
10 Chapter 3. Why the name? feed2exec Documentation, Release ???
#3.1.6 Files
Configuration file
The configuration file is loaded from (and written to, by add ) ~/.config/feed2exec.ini or $XDG_CONFIG_HOME/ feed2exec.ini . It can also be specified with the –config commandline parameter. This is an example configuration snippet:
[NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = feed2exec.plugins.echo args = {title} {link}
Naturally, those settings can be changed directly in the config file. Note that there is a [DEFAULT] section that can be used to apply settings to all feeds. For example, this will make all feeds store new items in a maildir subfolder:
[DEFAULT] output = feed2exec.plugins.maildir folder = feeds
This way individual feeds do not need to be individually configured.
Note: feed2exec does not take care of adding the folder to “subscriptions” in the mailbox. it is assumed that folders are auto-susbcribed or the user ignores subscription. if that is a problem, you should subscribe to the folder by hand in your email client when you add a new config. you can also subscribe to a folder (say feeds above) directly using the
doveadm mailbox subscribe feeds command in Dovecot, for example. The following configuration parameters are supported:
name
Human readable name for the feed. Equivalent to the NAME argument in the add command.
url
Address to fetch the feed from. Can be HTTP or HTTPS, but also file:// resources for test pur-poses.
output
Output plugin to use. Equivalent to the –output option in the add command.
args
Arguments to pass to the output plugin. Equivalent to the –args option in the add command.
filter
Filter plugin to use. Equivalent to the –filter option in the add command.
mailbox
Store emails in that mailbox prefix. Defaults to ~/Maildir .
folder
Subfolder to use when writing to a mailbox. By default, a slugified version of the feed name (where spaces and special character are replaced by -) is used. For example, the feed named “NASA breaking news” would be stored in ~/Maildir/nasa-breaking-news/ . Note that the mailbox prefix is used only if the folder path is relative.
catchup
Skip to the latest feed items. The feed is still read and parsed, and new feed items are added to the database, but output plugins are never called.
3.1. feed2exec manual page 11 feed2exec Documentation, Release ???
pause
Completely skip feed during fetch or parse. Similar to catchup, but doesn’t fetch the feed at all and doesn’t touch the cache. Here is a more complete example configuration with all the settings used:
#this section will apply to all feeds [DEFAULT] # special folder location for maildir. I use this when I have multiple # accounts synchronized with Offlineimap mailbox = ~/Maildir/Remote/ # a feed to store NASA breaking news entry in a “nasa” subfolder # this also demonstrates the droptitle filter [NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss folder = nasa filter = feed2exec.plugins.droptitle filter_args = trump # some maildir storage require dots to get subfolders. for example, # this will store messages in INBOX/feeds/images/ on Dovecot [NASA image of the day] url = https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss folder = .feeds.images # same feed, but save to wayback machine [NASA IOTD wayback] url = https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss output = feed2exec.plugins.wayback # this demonstrates the emptysummary filter, which fixes GitHub feeds # that lack a proper summary [restic] url = https://github.com/restic/restic/tags.atom filter = feed2exec.plugins.emptysummary # saving to a mbox folder, one file per feed instead of one file per item [International Space Station Reports] url = http://blogs.nasa.gov/stationreport/feed/ mailbox = ~/Mail/ folder = stationreport.mbx # simple generic exec call example: check for broken links using linkchecker [NASA linkchecker] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = feed2exec.plugins.exec args = linkchecker –check-extern –no-robots –recursion-level 1 –quiet ‘{item.link} ‘
#same, but with a Ikiwiki RSS feed, which needs fixing [Ikiwiki linkchecker] url = http://ikiwiki.info/recentchanges/index.rss output = feed2exec.plugins.exec filter = feed2exec.plugins.ikiwiki_recentchanges
(continues on next page)
12 Chapter 3. Why the name? feed2exec Documentation, Release ???
(continued from previous page)
args = linkchecker –check-extern –no-robots –recursion-level 1 –quiet ‘{item.link} ‘
#retweet hurricane news [NASA Hurricane breaking news] url = https://www.nasa.gov/rss/dyn/hurricaneupdate.rss output = feed2exec.plugins.exec args = tweet “{item.title:.40s} {item.link:.100s}” # same, but on the mastodon network ## we can have multiple entries with the same URL without problems, as # long as the feed name is different. it does mean that the feed will # be fetched and parsed multiple times, unfortunately. ## this could be improved to include the ‘{item.summary} ‘ and extra markup, # for example. [NASA Hurricane breaking news - Mastodon] url = https://www.nasa.gov/rss/dyn/hurricaneupdate.rss output = feed2exec.plugins.exec # unfortunately, this will noisily report the URL of the posted link, # which you may not want. to avoid that, encourage upstream to do the # right thing: https://github.com/ihabunek/toot/issues/46 … or use # another tool listed here: # https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/Apps.md args = toot post “{item.title} {item.link}” # output is disabled here. feed will be fetched and parsed, but no # toot will be sent catchup = True # same, but on the Pump.io network [NASA Hurricane breaking news - Pump] url = https://www.nasa.gov/rss/dyn/hurricaneupdate.rss output = feed2exec.plugins.exec args = p post note “{item.title} {item.link}” # crude podcast client [NASA What up?] url = https://www.nasa.gov/rss/dyn/whats_up.rss output = feed2exec.plugins.exec # XXX: this doesn ‘t handle errors properly: if there is a feed without # enclosures, the whole thing will crash. args = wget -P /srv/podcasts/nasa/ “{item.enclosures[0].href}” # feed is paused here. feed will not be fetched and parsed at all and # no post will be sent. pause = True # download torrents linked from a RSS feed [torrents] url = http://example.com/torrents.rss output = feed2exec.plugins.exec args = transmission-remote -a ‘{item.link} ‘ -w ‘/srv/incoming ‘
(continues on next page)
3.1. feed2exec manual page 13 feed2exec Documentation, Release ???
(continued from previous page)
#same thing with an actual plugin [torrents] url = http://example.com/torrents.rss output = feed2exec.plugins.transmission args = seedbox.example.com folder = /srv/incoming
Cache database
The feeds cache is stored in a feed2exec.db file. It is a SQLite database and can be inspected using standard sqlite tools. It is used to keep track of which feed and items have been processed. To clear the cache, you can simply remove the file, which will make the program process all feeds items from scratch again. In this case, you should use the
–catchup argument to avoid duplicate processing. You can also use the null output plugin to the same effect.
#3.1.7 Limitations
Feed support is only as good as feedparser library which isn’t as solid as I expected. In particular, I had issues with feeds without dates and without guid. Unit test coverage is incomplete, but still pretty decent, above 90%. The exec plugin itself is not well tested and may have serious security issues. API, commandline interface, configuration file syntax and database format can be changed until the 1.0 release is published, at which point normal Semantic Versioning semantics apply. The program is written mainly targeting Python 3.5 and 3.7, but should support later releases as well. See the setup.py
classification for an authoritative reference. Python 2.7 is not supported anymore. The SQL storage layer is badly written and is known to trigger locking issues with SQLite when doing multiprocessing. The global LOCK object could be used to work around this issue but that could mean pretty bad coupling. A good inspiration may be the beets story about this problem. And of course, another alternative would be to considering something like SQLalchemy instead of rolling our own ORM. There has, however, been some improvements to the locking recently, although that has been done with thread instead of process -specific locks. Older feed items are not purged from the database when they disappear from the feed, which may lead to database bloat in the long term. Similarly, there is no way for plugins to remove old entry that expire from the feed.
#3.1.8 See also
feed2exec-plugins(1) , feed2imap(1) , rss2email(1)
14 Chapter 3. Why the name? feed2exec Documentation, Release ???
#3.2 Design
This is a quick prototype that turned out to be quite usable. The design is minimal: some home-made ORM for the feed storage, crude parallelism with the multiprocessing module and a simple plugin API using importlib .More information about known issues and limitations in the feed2exec manual page document.
#3.2.1 Quick tour
The most common workflow is through the fetch subcommand and goes something like this: 1. main.py is the main entrypoint, managed through the click module, which normally calls func-tions defined in controller.py . The base command ( main.main ) creates a feed2exec.controller. FeedManager object which gets passed to subcommands. In our case, it passes the control to the fetch sub-command. 2. The fetch command calls the feed2exec.controller.FeedManager.fetch() function which creates a
feed2exec.model.Feed object that is then used to parse the feed and return it as an opaque data object as returned by feedparser . The feed is parsed (and, below, dispatched) only if it not already present in the cache, managed by the cachecontrol module. 3. fetch then calls the feed2exec.controller.FeedManager.dispatch() function that calls the various filter and output plugins, passing in the feed configuration and one item at a time. The filters can modify the feed items while the output plugins are responsible for writing them somewhere. That distinction is mostly arbitrary, but the return values of the output plugins matter, while filters do not. The feed cache is stored in a minimal sqlite3 database. A table keeps track of which feed item has been seen and another is the backend for the cachecontrol module and has a copy of the actual requests, keyed by URL. Configuration is stored in a .ini file or whatever configparser supports. It was originally stored in the database as well, but it was found inconvenient to modify by hand and a configuration file was used instead. The .ini file format was chosen because it is well supported by Python and allows for default settings. There is the possibility for this project to cover more than RSS/Atom feeds. In theory, the parse function could also be pluggable and support reading from other data sources like Twitter or Facebook, which would bring us closer to the IFTTT concept.
#3.2.2 Plugin system
Plugins are documented in the Plugins section. You can also refer to the Matchtitleregex section if you wish to write a new plugin or extend an existing one. The plugin system uses a simple importlib based architecture where plugin are simple Python modules loaded at runtime based on a module path provided by the user. This pattern was inspired by a StackOverflow discussion. The following options were also considered:
• pluggy: used by py.test, tox and devpi
• yapsy
• PluginBase
• plugnplay
• click-plugins: relevant only to add new commands
• PyPA plugin discovery
3.2. Design 15 feed2exec Documentation, Release ???
Those options were ultimately not used because they add an additional dependency and are more complicated than a simple import . We also did not need plugin listing or discovery, which greatly simplifies our design. There is some code duplication between different parts (e.g. the feed2exec.plugins.output() and feed2exec. plugins.filter() plugin interfaces, the maildir and mbox plugins, etc), but never more than twice.
#3.2.3 Concurrent processing
The threading design may be a little clunky and is certainly less tested, which is why it is disabled by default (use
–parallel to use it). There are known deadlocks issues with high concurrency scenarios (e.g. with catchup en-abled). I had multiple design in minds: the current one ( multiprocessing.Pool and pool.apply_async ) vs aiohttp
(on the asyncio branch) vs pool.map (on the threadpoolmap branch). The aiohttp design was very hard to diagnose and debug, which made me abandon the whole thing. After reading up on Curio and Trio, I’m tempted to give async/await a try again, but that would mean completely dropping 2.7 compatibility. The pool.map design is just badly adapted, as it would load all the feed’s datastructure in memory before processing them. The current parallel design also doesn’t profit much from the caching system. While before we would spend a lot of time parsing all feeds (in parallel), now most feeds are not parsed anymore (because unchanged) so a lot of time is spent doing HTTP requests, which could be done in parallel (but currently isn’t).
#3.2.4 Test suite
The test suite is in feed2exec/tests but also as doctest comments in some functions imported from the ecdysis project. You can run all the tests with pytest, using, for example:
pytest-3
This is also hooked into the setup.py command, so this also works:
python3 setup.py test
Note: It’s recommended to use the tox command to run tests, as some tests are picky about dependencies version numbers. That’s how the Continuous Integration (CI) system runs tests, through the .gitlab-ci.yml file. Enabling the catchlog plugin will also enable logging in the test suite which will help diagnostics. Note that some tests will fail in Python 2, as the code is written and tested in Python3. Furthermore, the feed output is taken from an up to date (5.2.1) feedparser version, so the tests are marked as expected to fail for lower versions. You should, naturally, run and write tests before submitting patches. See the Writing tests section for more information about how to write tests. The test suite also uses the betamax module to cache HTTP requests locally so the test suite can run offline. If a new test requires networking, you can simply add a new test doing requests with the right fixture ( betamax_session() )provided by upstream if you are going to do standalone HTTP request (not going through the feed2exec libraries). But you would more likely use the existing session by using the feed2exec.tests.fixtures.feed_manager() fixture, which has a session member you can use. If a new test is added in an existing test, you may need to configure recording (in feed2exec/tests/conftest.py )to new_episodes :
16 Chapter 3. Why the name? feed2exec Documentation, Release ???
config.default_cassette_options[ ‘record_mode ‘] = ‘none ‘
We commit the recordings in git so the test suite actually runs offline, so be careful about the content added there. Ideally, the license of that content should be documented in debian/copyright .vcrpy was first used for tests since it was simpler and didn’t require using a global requests.session.Session
object. But in the end betamax seems better maintained and more flexible: it supports pytest fixtures, for example, and multiple cassette storage (including vcr backwards compatibility). Configuration is also easier, done in feed2exec/ tests/conftest.py . Using a session also allows us to use a custom user agent.
#3.2.5 Comparison
feed2exec is a fairly new and minimal program, so features you may expect from another feed reader may not be present. I chose to write a new program because, when I started, both existing alternatives were in a questionable state: feed2imap was mostly abandoned and rss2email’s maintainer was also unresponsive. Both were missing the features I was looking for, which was to unify my feed parsers in a single program: i needed something that could deliver mail, run commands and send tweets. The latter isn’t done yet, but I am hoping to complete this eventually. The program may not be for everyone, however, so I made those comparison tables to clarify what feed2exec does compared to the alternatives. General information:
Program Version Date SLOC Language
feed2exec 0.10 2017 989 Python feed2imap 1.2.5 2015 3238 Ruby rss2email 3.9 2014 1754 Python
• version: the version analysed
• date: the date of that release
• SLOC: Source Lines of Codes as counted by sloccount, only counting dominant language (e.g. excluding XML from test feeds) and excluding tests
• Language: primary programming language Delivery options:
Program Maildir Mbox IMAP SMTP sendmail exec
feed2exec ✓ ✓ ✓
feed2imap ✓ ✓
rss2email ✓ ✓ ✓
• maildir: writing to Maildir folders. r2e has a pull request to implement maildir support, but it’s not merged at the time of writing
• IMAP: sending emails to IMAP servers
• SMTP: delivering emails over the SMTP protocol, with authentication
• sendmail: delivering local using the local MTA
• exec: run arbitrary commands to run on new entries. feed2imap has a execurl parameter to execute commands, but it receives an unparsed dump of the feed instead of individual entries. rss2email has a postprocess filter that is a Python plugin that can act on individual (or digest) messages which
3.2. Design 17 feed2exec Documentation, Release ???
could possibly be extended to support arbitrary commands, but that is rather difficult to implement for normal users. Features:
Program Pause OPML Retry Images Filter Reply Digest
feed2exec ✓ ✓ ✓ ✓
feed2imap ✓ ✓ ✓ ✓
rss2email ✓ ✓ ✓ ✓ ✓ ✓
• pause: feed reading can be disabled temporarily by user. in feed2exec, this is implemented with the pause
configuration setting. the catchup option can also be used to catchup with feed entries.
• retry: tolerate temporary errors. For example, feed2imap will report errors only after 10 failures.
• images: download images found in feed. feed2imap can download images and attach them to the email.
• filter: if we can apply arbitrary filters to the feed output. feed2imap can apply filters to the unparsed dump of the feed.
• reply: if the generated email ‘from’ header is usable to make a reply. rss2email has a use-publisher-email
setting (off by default) for this, for example. feed2exec does this by default.
• digest: possibility of sending a single email per run instead of one per entry
Note: feed2imap supports only importing OPML feeds, exporting is supported by a third-party plugin.
Note: feed2exec might one day be expanded to support other feeds than RSS/Atom, and turn into a more generic “if-this-then-that” type of program, to support, say, REST APIs, or Gemini, or whatever. In the meantime, see gmi2email for an alternative supporting Gemini.
#3.2.6 Related software
• rss-bridge can be used to provide RSS feeds for hundreds of sites that do not, including Twitter, Reddit, Youtube, etc
#3.3 API documentation
This is the API documentation of the program. It should explain how to create new plugins and navigate the code.
#3.3.1 Controller module
This is the core modules that processes all feeds and talks to the storage. It’s where most of the logic lies, although the parsing is still currently done inside the model. It dispatches the plugin logic to the plugin module.
18 Chapter 3. Why the name? feed2exec Documentation, Release ???
#3.3.2 Model
The “model” keeps track of feeds and their items. It handles configuration and cache storage.
#3.3.3 Main entry point
The main entry point of the program is in the feed2exec.main module. This is to make it possible to call the program directly from the source code through the Python interpreter with:
python -m feed2exec
All this code is here rather than in init.py to avoid requiring too many dependencies in the base module, which contains useful metadata for setup.py .This uses the click module to define the base command and options.
#3.3.4 Plugins
Plugin interface
In this context, a “plugin” is simply a Python module with a defined interface.
feed2exec.plugins. output (feed , item , lock=None , session=None )
load and run the given plugin with the given arguments an “output plugin” is a simple Python module with an output callable defined which will process arguments and should output them somewhere, for example by email or through another command. the plugin is called (from feed2exec.feeds.parse() ) when a new item is found, unless cache is flushed or ignored. The “callable” can be a class, in which case only the constructor is called or a function. The *args and **kwargs
parameter SHOULD be used in the function definition for forward-compatibility (ie. to make sure new parameters added do not cause a regression). Plugins should also expect to be called in parallel and should use the provided lock (a multiprocessor.Lock object) to acquire and release locks around contentious resources. Finally, the FeedManager will pass along his own session that should be reused by plugins to do requests. This allows plugins to be unit-tested and leverages the built-in cache as well. The following keywords are usually replaced in the arguments:
• {item.link}
• {item.title}
• {item.description}
• {item.published}
• {item.updated}
• {item.guid} The full list of such parameters is determined by the :module:feedparser module. Similarly, feed parameters from the configuration file are accessible.
3.3. API documentation 19 feed2exec Documentation, Release ???
Caution: None of those parameters are sanitized in any way other than what feedparser does, so plugins writing files, executing code or talking to the network should be careful to sanitize the input appropriately. The feed and items are also passed to the plugin as keyword arguments. Plugins should especially respect the
catchup argument that, when set, forbids plugins to do any permanent activity. For example, plugins MUST NOT run commands, write files, or make network requests. In general, “catchup mode” should be fast : it allows users to quickly catchup with new feeds without firing plugins, but it should also allow users to test configura-tions so plugins SHOULD give information to the user about what would have been done by the plugin without
catchup .
Parameters
• feed (dict ) – the feed metadata
• item (dict ) – the updated item
Return object
the loaded plugin
Note: more information about plugin design is in the Matchtitleregex document.
feed2exec.plugins. filter (feed , item , lock=None , session=None )
call filter plugins. very similar to the output plugin, but just calls the filter module member instead of output
Todo: common code with output() should be factored out, but output() takes arguments. . .
feed2exec.plugins. resolve (plugin )
resolve a short plugin name to a loadable plugin path Some parts of feed2exec allow shorter plugin names. For example, on the commandline, users can pass maildir
instead of feed2exec.plugins.maildir .Plugin resolution works like this: 1. search for the module in the feed2exec.plugins namespace 2. if that fails, consider the module to be an absolute path
Note: actual plugins are documented in the Plugins document.
#3.3.5 Utilities
Those are various utilities reused in multiple modules that did not fit anywhere else.
20 Chapter 3. Why the name? feed2exec Documentation, Release ???
#3.4 Plugins
This is a quick overview of the available plugins.
#3.4.1 Output plugins
Archive Echo
class feed2exec.plugins.echo. output (*args , feed=None , **kwargs )
This plugin outputs, to standard output, the arguments it receives. It can be useful to test your configuration. It also creates a side effect for the test suite to determine if the plugin was called. This plugin does a similar thing when acting as a filter.
feed2exec.plugins.echo. filter
This filter just keeps the feed unmodified. It is just there for testing purposes.
Error
feed2exec.plugins.error. output (*args , **kwargs )
The error plugin is a simple plugin which raises an exception when called. It is designed for use in the test suite and should generally not be used elsewhere.
Exec
feed2exec.plugins.exec. output (command , *args , feed=None , **kwargs )
The exec plugin is the ultimate security disaster. It simply executes whatever you feed it without any sort of sanitization. It does avoid to call to the shell and executes the command directly, however. Feed contents are also somewhat sanitized by the feedparser module, see the Sanitization documentation for more information in that regard. That is limited to stripping out hostile HTML tags, however. You should be careful when sending arbitrary parameters to other programs. Even if we do not use the shell to execute the program, an hostile feed could still inject commandline flags to change the program behavior without injecting shell commands themselves. For example, if a program can write files with the -o option, a feed could set their title to -oevil to overwrite the evil file. The only way to workaround that issue is to carefully craft the commandline so that this cannot happen. Alternatively, writing a Python plugin is much safer as you can sanitize the arguments yourself. Example:
[NASA What ‘s up?] url = https://www.nasa.gov/rss/dyn/whats_up.rss output = feed2exec.plugins.exec args = wget -P /srv/archives/nasa/ {item.link}
The above is the equivalent of the archive plugin: it will save feed item links to the given directory.
3.4. Plugins 21 feed2exec Documentation, Release ??? Maildir Mbox Null
feed2exec.plugins.null. output (*args , **kwargs )
This plugin does nothing. It can be useful in cases where you want to catchup with imported feeds.
feed2exec.plugins.null. filter (item=None , *args , **kwargs )
The null filter removes all elements from a feed item
Transmission Wayback
#3.4.2 Filter plugins
Droptitle
feed2exec.plugins.droptitle. filter (*args , feed=None , item=None , **kwargs )
the droptitle filter will drop any feed item with a title matching the given args. Example:
[NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss filter = feed2exec.plugins.droptitle filter_args = Trump
The above will process the feed items according to the global configuration, but will skip any item that has the word “Trump” anywhere in the title field. Arguments are processed as a single string. If you need to match more complex patterns, look at the droptitleregex plugin instead.
Droptitleregex
feed2exec.plugins.droptitleregex. filter (*args , feed=None , item=None , **kwargs )
the droptitleregex filter will drop any feed item with a title matching the given regular expression pattern. Example:
[NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss filter = feed2exec.plugins.droptitleregex filter_args = ^ham
The above configuration processes the feed items based on the global configuration, but it will skip any item whose title starts with the word “ham”.
22 Chapter 3. Why the name? feed2exec Documentation, Release ??? Emptysummary
feed2exec.plugins.emptysummary. filter (*args , feed=None , item=None , **kwargs )
example of fixes for a broken feed, in this case, the GitHub release feed which (sometimes) sends empty contents, in which case the item link field is used as a summary instead.
Html2text Ikiwiki Recentchanges
feed2exec.plugins.ikiwiki_recentchanges. filter (*args , item=None , **kwargs )
the ikiwiki_recentchanges plugin fixes links in ikiwiki feeds Ikiwiki recent changes show all the recent edits to pages, but the element doesn’t point to the edit page: it points to the recent changes page itself, which make them useless for link checking or archival purposes. This parses the recent changes entries and extracts the relevant links from it. An alternative to this is to use the following entry to generate a special feed in Ikiwiki:
[[!inline pages=”*” feeds=yes feedonly=yes feedfile=archive show=10]]
This generates a feed with proper elements but requires write access to the wiki. This will also add the date to the URL GUID so that we refresh when a page is updated. Otherwise feed2exec would think the entry has already been passed.
Matchtitleregex
feed2exec.plugins.matchtitleregex. filter (*args , feed=None , item=None , **kwargs )
The matchtitleregex filter selects only the feed items whose title match the given regular expression pattern. Example:
[NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss filter = feed2exec.plugins.matchtitleregex filter_args = ^spam
The above configuration processes the feed items based on the global configuration, but it will skip any item whose title does not start with the word “spam”.
#3.4.3 Writing new plugins
Most of the actual work in the program is performed by plugins. A plugin is a simple Python module that has a output
or filter “callable” (function or class) with a predefined interface.
3.4. Plugins 23 feed2exec Documentation, Release ??? Basic plugin principles
To write a new plugin, you should start by creating a simple Python module, in your PYTHONPATH. You can find which directories are in the path by calling:
$ python3 -c “import sys; print(sys.path)” [’’ , ‘/usr/lib/python35.zip ‘, ‘/usr/lib/python3.5 ‘, ‘/usr/lib/python3.5/plat-x86_64-
˓→
linux-gnu ‘, ‘/usr/lib/python3.5/lib-dynload ‘, ‘/usr/local/lib/python3.5/dist-packages ‘,
˓→
‘/usr/lib/python3/dist-packages ‘]
In the above example, a good location would be /usr/local/lib/python3.5/dist-packages . The naming con-vention is loose: as long as the plugin matches the expected API, it should just work. For the purpose of this demon-stration, we’ll call our plugin trumpery, so we will create the plugin code like this:
touch /usr/local/lib/python3.5/dist-packages/trumpery.py
Naturally, if you are going to write multiple plugins, you may want to regroup your multiple plugins in a package, see the module documentation for more information about this concept in Python.
Note: There is a rudimentary plugin resolution process that looks for plugins first in the feed2exec.plugins namespace but then globally. This is done in feed2exec.plugins.resolve() , called from the add and parse commands. This means that the absolute path is expected to be used in the configuration file and internally. You are welcome to distribute plugins separately or send them as merge requests, see Contribution guide for more information on how to participate in this project. We of course welcome contributions to this documentation as well!
Filters
Now, you need your plugin to do something. In our case, let’s say we’d like to skip any feed entry that has the word Trump in it. For that purpose, we’ll create a plugin similar to the already existing feed2exec.plugins.droptitle
plugin, but that operates on the body of the feed, but that also hardcodes the word, because this is just a demonstration and we want to keep it simple. Let’s look at the title plugin to see how it works:
def filter(*args, feed= None , item= None , **kwargs):
’’’ the droptitle filter will drop any feed item with a title matching the given args. Example:: [NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss filter = feed2exec.plugins.droptitle filter_args = Trump The above will process the feed items according to the global configuration, but will skip any item that has the word “Trump” anywhere in the title field. Arguments are processed as a single string. If you need to match more complex patterns, look at the droptitleregex plugin instead.
’’’
item[ ‘skip ‘] = ‘ ‘ .join(args) in item.get( ‘title ‘, ‘’ )
24 Chapter 3. Why the name? feed2exec Documentation, Release ???
That may look like complete gibberish to you if you are not familiar with programming or with Python programming in particular. But let’s take this from the top and copy that in our own plugin. The first line declares a function that takes at least a feed and a item argument, but can also accept any other arbitrary argument. This is important because we want to have the plugin keep on working if the plugin API changes in the future. This is called “forward-compatibility”. So let’s copy that in our plugin and add a pass statement to make sure the plugin works (even if it does nothing for now):
def filter(*args, feed= None , item= None , **kwargs):
pass
We can already test our plugin by adding it to our configuration, in ~/.config/feed2exec.ini :
[NASA] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = feed2exec.plugins.echo args = {item.title} filter = trumpery
Notice how we use the output plugin to show the title of feed items selected, as a debugging tool. Let’s fetch this feed in debugging mode to see what happens:
$ python3 -m feed2exec –verbose fetch –force opening local file /home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml parsing feed file:///home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml␣
˓→
(10355 bytes) connecting to database at ./doc/feed2exec.db arguments received: ( ‘President Trump Welcomes Home Record-breaking NASA Astronaut Peggy␣
˓→
Whitson ‘,) arguments received: ( ‘Three International Space Station Crewmates Safely Return to Earth
˓→
’,) arguments received: ( ‘NASA Statement on Nomination for Agency Administrator ‘,) arguments received: ( ‘NASA Television to Air Return of Three International Space Station␣
˓→
Crew Members ‘,) arguments received: ( ‘NASA and Iconic Museum Honor Voyager Spacecraft 40th Anniversary ‘,) arguments received: ( ‘NASA’s Johnson Space Center Closes Through Labor Day for Tropical␣
˓→
Storm Harvey ‘,) arguments received: ( ‘NASA Cancels Planned Media Availabilities with Astronauts ‘,) arguments received: ( ‘NASA Awards $400,000 to Top Teams at Second Phase of 3D-Printing␣
˓→
Competition ‘,) arguments received: ( ‘NASA Awards Contract for Center Protective Services for Glenn␣
˓→
Research Center ‘,) arguments received: ( ‘NASA Announces Cassini End-of-Mission Media Activities ‘,) 1 feeds processed
Good! The feed is fetched and items are displayed. It means our filter didn’t interfere, but now it’s time to make it do
something. To skip items, we need to set the skip attribute for the feed item to True if we want to skip it and False
otherwise. So we’ll use a simple recipe, a bit like droptitle does, but simpler, to look at the feed content to look for our evil word. The feedparser documentation tells us feed items have a summary field which we can inspect. There’s also a content list, but that’s a little more complicated so we’ll skip that for now. So, let’s set the skip parameter to match if there is the evil word in our feed item, like this:
def filter(*args, feed= None , item= None , **kwargs): item[ ‘skip ‘] = ‘Trump ‘ in item.get( ‘summary ‘, ‘’ )
And let’s see the result (note that we use the –force argument here otherwise we would just skip all items because
3.4. Plugins 25 feed2exec Documentation, Release ???
of the cache):
$ python3 -m feed2exec –verbose fetch –force opening local file /home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml parsing feed file:///home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml␣
˓→
(10355 bytes) connecting to database at ./doc/feed2exec.db item President Trump Welcomes Home Record-breaking NASA Astronaut Peggy Whitson of feed␣
˓→
NASA filtered out arguments received: ( ‘Three International Space Station Crewmates Safely Return to Earth
˓→
’,) item NASA Statement on Nomination for Agency Administrator of feed NASA filtered out arguments received: ( ‘NASA Television to Air Return of Three International Space Station␣
˓→
Crew Members ‘,) arguments received: ( ‘NASA and Iconic Museum Honor Voyager Spacecraft 40th Anniversary ‘,) arguments received: ( ‘NASA’s Johnson Space Center Closes Through Labor Day for Tropical␣
˓→
Storm Harvey ‘,) arguments received: ( ‘NASA Cancels Planned Media Availabilities with Astronauts ‘,) arguments received: ( ‘NASA Awards $400,000 to Top Teams at Second Phase of 3D-Printing␣
˓→
Competition ‘,) arguments received: ( ‘NASA Awards Contract for Center Protective Services for Glenn␣
˓→
Research Center ‘,) arguments received: ( ‘NASA Announces Cassini End-of-Mission Media Activities ‘,) 1 feeds processed
Success! We have skipped the two items that contain the fraud we wanted to remove from the world. Notice how we were able to modify the feed item: we can also use that to change the feed content. Normally, we would use this to fix malformed feeds, but let’s have some fun instead and rename Trump to Drumpf:
def filter(*args, feed= None , item= None , **kwargs): item[ ‘title ‘] = item.get( ‘title ‘, ‘’ ).replace( ‘Trump ‘, ‘Drumpf ‘)
And the result:
$ python3 -m feed2exec –verbose fetch –force opening local file /home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml parsing feed file:///home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml␣
˓→
(10355 bytes) connecting to database at ./doc/feed2exec.db arguments received: ( ‘President Drumpf Welcomes Home Record-breaking NASA Astronaut␣
˓→
Peggy Whitson ‘,) arguments received: ( ‘Three International Space Station Crewmates Safely Return to Earth
˓→
’,) arguments received: ( ‘NASA Statement on Nomination for Agency Administrator ‘,) arguments received: ( ‘NASA Television to Air Return of Three International Space Station␣
˓→
Crew Members ‘,) arguments received: ( ‘NASA and Iconic Museum Honor Voyager Spacecraft 40th Anniversary ‘,) arguments received: ( ‘NASA’s Johnson Space Center Closes Through Labor Day for Tropical␣
˓→
Storm Harvey ‘,) arguments received: ( ‘NASA Cancels Planned Media Availabilities with Astronauts ‘,) arguments received: ( ‘NASA Awards $400,000 to Top Teams at Second Phase of 3D-Printing␣
˓→
Competition ‘,) arguments received: ( ‘NASA Awards Contract for Center Protective Services for Glenn␣
˓→
Research Center ‘,)
(continues on next page)
26 Chapter 3. Why the name? feed2exec Documentation, Release ???
(continued from previous page)
arguments received: ( ‘NASA Announces Cassini End-of-Mission Media Activities ‘,) 1 feeds processed
I know, absolutely hilarious, right? More seriously, this is also how the feed2exec.plugins.html2text filter works, which is enabled by default and helps the email output plugin do its job by turning HTML into text. At this point, the only limit is your knowledge of Python programming and your imagination!
Output plugins
Output plugins are another beast entirely. While they operate with the same principle than filter plugins (search path and function signature are similar), they are designed to actually output something for each new feed item found. This can be anything: a file, email, HTTP request, whatever. If there is a commandline tool that does what you need, it is probably simpler to just call the exec plugin and there are numerous examples of this in the sample configuration file. For more complex things, however, it may be easier to actually write this as a Python.
Basic arguments
For our example, we’ll write an archival plugin which writes each new entry to a file hierarchy. First, we start with the same simple function signature as filters, except we name it output:
def output(*args, feed= None , item= None , **kwargs):
pass
This is the equivalent of the null plugin and basically outputs nothing at all. To archive the feed items, we’ll need to look at the link element feedparser gives us. Let’s see what that looks like for the NASA feed:
def output(*args, feed= None , item= None , **kwargs):
#only operate on items that actually have a link
if item.get( ‘link ‘): print(item.get( ‘link ‘, ‘’ ))
else :logging.info( ‘no link for feed item %s , not archiving ‘, item.get( ‘title ‘))
Note: Note that we try to make plugins silent in general. You can use logging.info() to have things show up in
–verbose and logging.debug() for –debug but by default, your plugin should be silent unless there’s an error that requires the user’s intervention, in which case you should use logging.warning() for transient errors that may be automatically recovered and logging.error() for errors that require user intervention. This is to allow users to ignore warnings safely. Note that here we first check to see if the feed item actually has a link - not all feeds do! After adding the above to our
trumpery plugin and adding it as an output plugin:
[NASA] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = trumpery filter = trumpery
We can try to see what happens when we call it:
3.4. Plugins 27 feed2exec Documentation, Release ???
$ python3 -m feed2exec –verbose fetch –force opening local file /home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml parsing feed file:///home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml␣
˓→
(10355 bytes) connecting to database at ./doc/feed2exec.db http://www.nasa.gov/press-release/president-trump-welcomes-home-record-breaking-nasa-
˓→
astronaut-peggy-whitson http://www.nasa.gov/press-release/three-international-space-station-crewmates-safely-
˓→
return-to-earth http://www.nasa.gov/press-release/nasa-statement-on-nomination-for-agency-administrator http://www.nasa.gov/press-release/nasa-television-to-air-return-of-three-international-
˓→
space-station-crew-members http://www.nasa.gov/press-release/nasa-and-iconic-museum-honor-voyager-spacecraft-40th-
˓→
anniversary http://www.nasa.gov/press-release/nasa-s-johnson-space-center-closes-through-labor-day-
˓→
for-tropical-storm-harvey http://www.nasa.gov/press-release/nasa-cancels-planned-media-availabilities-with-
˓→
astronauts http://www.nasa.gov/press-release/nasa-awards-400000-to-top-teams-at-second-phase-of-3d-
˓→
printing-competition http://www.nasa.gov/press-release/nasa-awards-contract-for-center-protective-services-
˓→
for-glenn-research-center http://www.nasa.gov/press-release/nasa-announces-cassini-end-of-mission-media-activities 1 feeds processed
Sanitizing contents
Good. Those are the URLs we want to save to disk. Let’s start by just writing those to a file. We will also use a simple
slug function to make a filesystem-safe name from the feed title and save those files in a pre-determined location:
import logging import os.path from feed2exec.utils import slug ARCHIVE_DIR= ‘/run/user/1000/feed-archives/ ‘
def output(*args, feed= None , item= None , session= None , **kwargs):
#make a safe path from the item name
path = slug(item.get( ‘title ‘, ‘no-name ‘))
#put the file in the archive directory
path = os.path.join(ARCHIVE_DIR, path)
#only operate on items that actually have a link
if item.get( ‘link ‘):
#tell the user what ‘s going on, if verbose # otherwise, we try to stay silent if all goes well
logging.info( ‘saving feed item %s to %s from %s ‘,item.get( ‘title ‘), path, item.get( ‘link ‘))
#open the file
with open(path, ‘w’) as archive:
#write the response
archive.write(item.get( ‘link ‘))
(continues on next page)
28 Chapter 3. Why the name? feed2exec Documentation, Release ???
(continued from previous page)
else :logging.info( ‘no link for feed item %s , not archiving ‘, item.get( ‘title ‘))
Now I know this may look like a huge step from the previous one but I’m sorry, I couldn’t find a simpler second step. :) The output now looks like this:
$ python3 -m feed2exec –config ./doc/ –verbose fetch –force opening local file /home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml parsing feed file:///home/anarcat/src/feed2exec/feed2exec/tests/files/breaking_news.xml␣
˓→
(10355 bytes) connecting to database at ./doc/feed2exec.db saving feed item President Drumpf Welcomes Home Record-breaking NASA Astronaut Peggy␣
˓→
Whitson to /run/user/1000/president-drumpf-welcomes-home-record-breaking-nasa-
˓→
astronaut-peggy-whitson from http://www.nasa.gov/press-release/president-trump-
˓→
welcomes-home-record-breaking-nasa-astronaut-peggy-whitson saving feed item Three International Space Station Crewmates Safely Return to Earth to /
˓→
run/user/1000/three-international-space-station-crewmates-safely-return-to-earth from␣
˓→
http://www.nasa.gov/press-release/three-international-space-station-crewmates-safely-
˓→
return-to-earth saving feed item NASA Statement on Nomination for Agency Administrator to /run/user/1000/
˓→
nasa-statement-on-nomination-for-agency-administrator from http://www.nasa.gov/press-
˓→
release/nasa-statement-on-nomination-for-agency-administrator saving feed item NASA Television to Air Return of Three International Space Station Crew␣
˓→
Members to /run/user/1000/nasa-television-to-air-return-of-three-international-space-
˓→
station-crew-members from http://www.nasa.gov/press-release/nasa-television-to-air-
˓→
return-of-three-international-space-station-crew-members saving feed item NASA and Iconic Museum Honor Voyager Spacecraft 40th Anniversary to /
˓→
run/user/1000/nasa-and-iconic-museum-honor-voyager-spacecraft-40th-anniversary from␣
˓→
http://www.nasa.gov/press-release/nasa-and-iconic-museum-honor-voyager-spacecraft-40th-
˓→
anniversary saving feed item NASA’s Johnson Space Center Closes Through Labor Day for Tropical Storm␣
˓→
Harvey to /run/user/1000/nasa-s-johnson-space-center-closes-through-labor-day-for-
˓→
tropical-storm-harvey from http://www.nasa.gov/press-release/nasa-s-johnson-space-
˓→
center-closes-through-labor-day-for-tropical-storm-harvey saving feed item NASA Cancels Planned Media Availabilities with Astronauts to /run/user/
˓→
1000/nasa-cancels-planned-media-availabilities-with-astronauts from http://www.nasa.
˓→
gov/press-release/nasa-cancels-planned-media-availabilities-with-astronauts saving feed item NASA Awards $400,000 to Top Teams at Second Phase of 3D-Printing␣
˓→
Competition to /run/user/1000/nasa-awards-400-000-to-top-teams-at-second-phase-of-3d-
˓→
printing-competition from http://www.nasa.gov/press-release/nasa-awards-400000-to-top-
˓→
teams-at-second-phase-of-3d-printing-competition saving feed item NASA Awards Contract for Center Protective Services for Glenn Research␣
˓→
Center to /run/user/1000/nasa-awards-contract-for-center-protective-services-for-glenn-
˓→
research-center from http://www.nasa.gov/press-release/nasa-awards-contract-for-center-
˓→
protective-services-for-glenn-research-center saving feed item NASA Announces Cassini End-of-Mission Media Activities to /run/user/
˓→
1000/nasa-announces-cassini-end-of-mission-media-activities from http://www.nasa.gov/
˓→
press-release/nasa-announces-cassini-end-of-mission-media-activities
Sweet! Now it’s not really nice to save this in /run/user/1000 . I just chose this directory because it was a safe place to write but it’s not a persistent directory. Best make that configurable, which is where plugin arguments come in.
3.4. Plugins 29 feed2exec Documentation, Release ??? User configuration
You see that *args parameter? That comes straight from the configuration file. So you could set the path in the configuration file, like this:
[NASA] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = trumpery args = /srv/archives/nasa/ filter = trumpery
We also need to modify the plugin to fetch that configuration, like this:
def output(*args, feed= None , item= None , session= None , **kwargs):
#make a safe path from the item name
path = slug(item.get( ‘title ‘, ‘no-name ‘))
#take the archive dir from the user or use the default
archive_dir = ‘ ‘ .join(args) if args else DEFAULT_ARCHIVE_DIR
#put the file in the archive directory
path = os.path.join(archive_dir, path)
#[…] # rest of the function unchanged
Making HTTP requests
And now obviously, we only saved the link itself, not the link content . For that we need some help from the requests
module, and do something like this:
#fetch the URL in memory
result = session.get(item.get( ‘link ‘))
if result.status_code != requests.codes.ok: logging.warning( ‘failed to fetch link %s : %s ‘,item.get( ‘link ‘), result.status_code)
#make sure we retry next time
return False
#open the file
with open(path, ‘w’) as archive:
#write the response
archive.write(result.text)
This will save the actual link content ( result.text ) to the file. The important statement here is:
#fetch the URL in memory
result = session.get(item.get( ‘link ‘))
which fetches the URL in memory and checks for errors. The other change in the final plugin is simply:
archive.write(result.text)
which writes the article content instead of the link. Notice how the session argument is used here instead of talking directly to the requests module. This leverages a caching system we already have, alongside configuration like user-agent and so on.
30 Chapter 3. Why the name? feed2exec Documentation, Release ??? Plugin return values
Notice how we return False here: this makes the plugin system avoid adding the item to the cache, so it is retried on the next run. If the plugin returns True or nothing ( None ), the plugin is considered to have succeeded and the entry is added to the cache. That logic is defined in feed2exec.controller.FeedManager.fetch() .
Catchup
A final thing that is missing that is critical in all plugins is to respect the catchup setting. It is propagated up from the commandline or configuration all the way down to plugins, through the feed parameters. How you handle it varies from plugin to plugin, but the basic idea is to give feedback (when verbose) of activity when the plugin is run but to not actually do anything. In our case, we simply return success, right before we fetch the URL:
if feed.get( ‘catchup ‘):
return True
#fetch the URL in memory
result = session.get(item.get( ‘link ‘))
Notice how we still fetch the actual feed content but stop before doing any permanent operation. That is the spirit of the “catchup” operation: we not only skip “write” operation, but also any operation which could slow down the “catchup”: fetching stuff over the network takes time and while it can be considered a “readonly” operation as far as the local machine is concerned, we are effectively writing to the network so that operation shouldn’t occur. Hopefully that should get you going with most of the plugins you are thinking of writing!
Writing tests
Writing tests is essential in ensuring that the code will stay maintainable in the future. It allows for easy refactoring and can find bugs that manual testing may not, especially when you get complete coverage (although that is no guarantee either). We’ll take our archive plugin as an example. The first step is to edit the tests/test/test_plugins.py file, where other plugins are tests as well. We start by creating a function named test_archive so that Pytest, our test bed, will find it:
def test_archive(tmpdir, betamax): # noqa
pass
Notice the two arguments named tmpdir and betamax . Both of those are fixtures, a pytest concept that allows to simulate an environment. In particular, the tmpdir fixture, shipped with pytest, allows you to easily manage (and automatically remove) temporary directories. The betamax fixtures is a uses the betamax module to record then replay HTTP requests. Then we need to do something. We need to create a feed and a feed item that we can then send into the plugin. We could also directly parse an existing feed and indeed some plugins do exactly that. But our plugin is simple and we can afford to skip full feed parsing and just synthesize what we need:
feed = Feed( ‘test archive ‘, test_sample) item = feedparser.FeedParserDict({ ‘link ‘: ‘http://example.com/ ‘,
‘title ‘: ‘example site ‘})
This creates a new feed based on the test_sample feed. This is necessary so that the session is properly re-initialized in the feed item (otherwise the betamax fixture will not work). Then it creates a fake feed entry simply with one link
3.4. Plugins 31 feed2exec Documentation, Release ???
and a title. Then we can call our plugin, and verify that it saves the file as we expected. The test for the most common case looks like this:
def test_archive(tmpdir, betamax): # noqa
dest = tmpdir.join( ‘archive ‘)feed = Feed( ‘test archive ‘, test_sample) item = feedparser.FeedParserDict({ ‘link ‘: ‘http://example.com/ ‘,
‘title ‘: ‘example site ‘})
assert archive_plugin.output(str(dest), feed=feed, item=item)
assert dest.join( ‘example-site ‘).check()
Then we can try to run this with pytest-3 :
[1084]anarcat@curie:feed2exec$ pytest-3 =============================== test session starts =============================== platform linux – Python 3.5.3, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 rootdir: /home/anarcat/src/feed2exec, inifile: setup.cfg plugins: profiling-1.2.11, cov-2.4.0, betamax-0.8.0 collected 26 items feed2exec/utils.py .. feed2exec/plugins/transmission.py . feed2exec/tests/test_feeds.py …….. feed2exec/tests/test_main.py ….. feed2exec/tests/test_opml.py . feed2exec/tests/test_plugins.py ……… ———– coverage: platform linux, python 3.5.3-final-0 ———–Name Stmts Miss Cover —————————————————————-feed2exec/init.py 12 0 100% feed2exec/main.py 87 1 99% feed2exec/_version.py 1 0 100% feed2exec/email.py 81 7 91% feed2exec/feeds.py 243 8 97% feed2exec/logging.py 31 11 65% feed2exec/plugins/init.py 47 6 87% feed2exec/plugins/archive.py 23 5 78% feed2exec/plugins/droptitle.py 2 0 100% feed2exec/plugins/echo.py 8 0 100% feed2exec/plugins/emptysummary.py 5 0 100% feed2exec/plugins/error.py 2 0 100% feed2exec/plugins/exec.py 7 0 100% feed2exec/plugins/html2text.py 20 4 80% feed2exec/plugins/ikiwiki_recentchanges.py 9 5 44% feed2exec/plugins/maildir.py 28 0 100% feed2exec/plugins/mbox.py 29 1 97% feed2exec/plugins/null.py 5 1 80% feed2exec/plugins/transmission.py 20 0 100% feed2exec/plugins/wayback.py 20 0 100% feed2exec/tests/init.py 0 0 100% feed2exec/tests/conftest.py 3 0 100% feed2exec/tests/fixtures.py 19 0 100% feed2exec/tests/test_feeds.py 124 0 100% (continues on next page)
32 Chapter 3. Why the name? feed2exec Documentation, Release ???
(continued from previous page)
feed2exec/tests/test_main.py 90 0 100% feed2exec/tests/test_opml.py 17 0 100% feed2exec/tests/test_plugins.py 162 0 100% feed2exec/utils.py 41 12 71% —————————————————————-TOTAL 1136 61 95% =========================== 26 passed in 10.83 seconds ============================
Notice the test coverage: we only have 78% test coverage for our plugin. This means that some branches of the code were not executed at all! Let’s see if we can improve that. Looking at the code, I see there are some conditionals for error handling. So let’s simulate an error, and make sure that we don’t create a file on error:
dest.remove() item = feedparser.FeedParserDict({ ‘link ‘: ‘http://example.com/404 ‘,
‘title ‘: ‘example site ‘})
assert not archive_plugin.output(str(dest), feed=feed, item=item)
assert not dest.join( ‘example-site ‘).check()
There. Let’s see the effect on the test coverage:
[1085]anarcat@curie:feed2exec2$ pytest-3 feed2exec/tests/test_plugins.py::test_archive =============================== test session starts =============================== platform linux – Python 3.5.3, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 rootdir: /home/anarcat/src/feed2exec, inifile: setup.cfg plugins: profiling-1.2.11, cov-2.4.0, betamax-0.8.0 collected 10 items feed2exec/tests/test_plugins.py . ———– coverage: platform linux, python 3.5.3-final-0 ———–Name Stmts Miss Cover —————————————————————-feed2exec/init.py 12 0 100% feed2exec/main.py 87 87 0% feed2exec/_version.py 1 0 100% feed2exec/email.py 81 64 21% feed2exec/feeds.py 243 172 29% feed2exec/logging.py 31 31 0% feed2exec/plugins/init.py 47 38 19% feed2exec/plugins/archive.py 23 3 87% feed2exec/plugins/droptitle.py 2 2 0% feed2exec/plugins/echo.py 8 3 62% feed2exec/plugins/emptysummary.py 5 5 0% feed2exec/plugins/error.py 2 2 0% feed2exec/plugins/exec.py 7 7 0% feed2exec/plugins/html2text.py 20 13 35% feed2exec/plugins/ikiwiki_recentchanges.py 9 9 0% feed2exec/plugins/maildir.py 28 19 32% feed2exec/plugins/mbox.py 29 29 0% feed2exec/plugins/null.py 5 5 0%
(continues on next page)
3.4. Plugins 33 feed2exec Documentation, Release ???
(continued from previous page)
feed2exec/plugins/transmission.py 20 12 40% feed2exec/plugins/wayback.py 20 20 0% feed2exec/tests/init.py 0 0 100% feed2exec/tests/conftest.py 3 0 100% feed2exec/tests/fixtures.py 19 6 68% feed2exec/tests/test_feeds.py 124 101 19% feed2exec/tests/test_main.py 90 90 0% feed2exec/tests/test_opml.py 17 17 0% feed2exec/tests/test_plugins.py 166 123 26% feed2exec/utils.py 41 16 61% —————————————————————-TOTAL 1140 874 23% ============================ 1 passed in 2.46 seconds =============================
Much better! Only 3 lines left to cover!
Note: Notice how I explicitly provided a path to my test. This is entirely optional. You can just run pytest-3 and it will run the whole test suite: this method is just faster. Notice also how the coverage ratio is very low: this is normal; we are testing, after all, only one plugin here. The only branches left to test in the code is the other possible error (“no link in the feed”) and to test the “catchup” mode. You can see this in the actual test_plugins.py file distributed with this documentation.
Note: If you discover a bug associated with a single feed, you can use the betamax session and the feed2exec.model. Feed.parse() function to manually parse a feed and fire your plugin. This is how email functionality is tested: see the feed2exec.tests.test_plugins.test_email() function for an example.