FEED2EXEC-PLUGINS(1)

✨ NAME ✨

feed2exec-plugins β€” feed2exec plugin documentation πŸ’–

So this is the FEED2EXEC-PLUGINS(1) page from the feed2exec manual, and bestie, it's just a quick overview of all the plugins you can plug into feed2exec. That's it. That's the vibe. 🌸


πŸŽ€ OUTPUT PLUGINS πŸŽ€

These are the lil guys that actually do stuff when a feed item shows up. Pick one, drop it in your config, go off. 🫢

πŸ“¦ Archive

  • feed2exec.plugins.archive.DEFAULT_ARCHIVE_DIR = '/run/user/1000/' β€” the default archive directory, no cap.
  • feed2exec.plugins.archive.output(*args, feed=None, item=None, session=None, **kwargs) β€” the archive plugin saves the feed's item.link URLs into a directory. Which directory? Either the one from DEFAULT_ARCHIVE_DIR, or whatever you hand it through the output args value. You decide, queen. πŸ‘‘

Example time:

[NASA breaking news]
url = https://www.nasa.gov/rss/dyn/breaking_news.rss
output = archive
args = /srv/archive/nasa/

What that does is save the "NASA breaking news" into the /srv/archive/nasa directory. ✨

🚨 OK IMPORTANT: do not use interpolation here, because the feed's variable could be used to mount a directory transversal attack. Like, absolutely not. Keep it static, bestie.

πŸ“£ Echo

  • class feed2exec.plugins.echo.output(*args, feed=None, **kwargs) β€” this plugin outputs, to standard output, the arguments it receives. It's lowkey perfect for testing your configuration. It also creates a side effect so the test suite can figure out whether the plugin was actually called. And when it's acting as a filter, it does a similar thing. πŸ‘€
  • feed2exec.plugins.echo.filter β€” this filter just keeps the feed unmodified. It literally exists for testing purposes. That's its whole character arc. πŸ’…

πŸ’€ 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. Like, it is doing exactly what it says on the tin. 😭

🚨 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 calling the shell and executes the command directly, however. Feed contents are also somewhat sanitized by the feedparser module β€” see the Sanitization documentation for more info on that: https://pythonhosted.org/feedparser/html-sanitization.html. That is limited to stripping out hostile HTML tags, however. So like… barely. πŸ™ˆ

You should be careful when sending arbitrary parameters to other programs. Even if we do not use the shell to execute the program, a 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, because you can sanitize the arguments yourself. Big brain move. 🧠✨

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. Slay. πŸŽ€

πŸ“¬ Maildir

  • class feed2exec.plugins.maildir.output(to_addr=None, feed=None, item=None, lock=None, *args, **kwargs) β€” the maildir plugin will save a feed item into a Maildir folder. The configuration is a little clunky, but it should be safe against hostile feeds. Bestie it's giving "ugly but trustworthy". 🫢

Parameters:

Example:

[NASA breaking news]
url = https://www.nasa.gov/rss/dyn/breaking_news.rss
mailbox = ~/Maildir/
folder = nasa
args = me@example.com

The above will save new feed items from the NASA feed into the ~/Maildir/nasa/ maildir folder, and will set the To field of the email to me@example.com. So organized. So iconic. πŸ’œ

πŸ—„οΈ Mbox

  • class feed2exec.plugins.mbox.output(to_addr=None, feed=None, item=None, lock=None, *args, **kwargs) β€” the mbox plugin will save a feed item in a Mbox mailbox. This is mostly for testing purposes, but can of course be used in the unlikely event where you prefer mbox folders over the feed2exec.plugins.maildir plugin. Unlikely event fr fr. 😌

Parameters:

Todo πŸ“ β€” There is some overlap between the code here and the maildir implementation. Refactoring may be in order, particularly if we add another mailbox format, though that is unlikely. The devs are aware, okay? They said "unlikely". Leave them alone. πŸ™ˆ

πŸ•³οΈ 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. Doing nothing is a whole personality and honestly? Valid. πŸ’…
  • feed2exec.plugins.null.filter(item=None, *args, **kwargs) β€” the null filter removes all elements from a feed item. Poof. Gone. ✨

🌊 Transmission

  • feed2exec.plugins.transmission.sanitize(text, repl='-') β€” like utils.slug, but without lowercase and it allows a custom replacement. Cute.
>>> sanitize('test')
'test'
>>> sanitize('../../../etc/password')
'etc-password'
>>> sanitize('Foo./.bar', repl='.')
'Foo.bar'
  • feed2exec.plugins.transmission.output(hostname='localhost', *args, feed=None, item=None, **kwargs) β€” the transmission plugin will send feed items to a transmission instance (http://www.transmissionbt.com/). πŸ”₯

It assumes the transmission-remote command is already installed and configured to talk with transmission.

The hostname is passed in the args configuration and defaults to localhost. The folder parameter is also used to determine where to save the actual torrents files.

Note that this will also append a sanitized version of the item title, if a folder is provided. This is to allow saving series in the same folder. The way that works is genuinely so handy. πŸ¦‹

If the title is unique for each torrent, you may use a filter to set the title to the right location.

πŸ•°οΈ Wayback

  • feed2exec.plugins.wayback.output(*args, feed=None, item=None, session=None, **kwargs) β€” this plugin saves the feed items link element to the wayback machine. It will retry URLs that fail, so it may be necessary to manually catchup feeds if they have broken link fields. 😭

There are two wayback machine APIs that can be used β€” the default one archives the full page, while the other one archives only the page URLs.

The mechanism for archiving the full page uses a browser on the server to download all the resources used by the page including img/CSS/JS/etc:

https://blog.archive.org/2019/10/23/the-wayback-machines-save-page-now-is-new-and-improved/

Unfortunately the SPN2 page is just a HTML form, the response code is always 200 OK, any errors are returned in a HTML page and there are no easily machine-readable ways to find the errors on the page β€” so we have to parse the HTML and query it using XPath based heuristics. But if there are errors in a form that is not yet known then the unknown errors will not be detected properly. πŸ’€ Like, we're doing our best here.

Example:

[NASA IOTD wayback]
url = https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss
output = feed2exec.plugins.wayback
args = full

The above will save the Image of the day updates to the wayback machine. Since the page has images and everything is loaded by JS, using the SPN2 API is necessary to capture the useful information. πŸ‘‘

Example:

[ikiwiki RecentChanges wayback]
url = https://ikiwiki.info/recentchanges/index.rss
output = feed2exec.plugins.wayback
args = page

The above will save the ikiwiki RecentChanges to the wayback machine. Since the page is plain text, saving the full page resources is not really necessary β€” the CSS does not add information to the page. 🌈

🌸 FILTER PLUGINS 🌸

These are the little bouncers standing at the door of your feed, deciding which items get in and which get ✨left on read✨.


πŸ’… 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. regex girlies, this one's for you πŸ’–

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". no ham titles allowed in this house 🚫🐷


πŸ«™ 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. it's giving "the feed is broken but we're resourceful" πŸ’…


πŸ¦‹ Html2text

class feed2exec.plugins.html2text.filter(*args, feed=None, item=None, **kwargs)

This filter plugin takes a given feed item and adds a content_plain field with the HTML parsed as text. raw HTML ➑️ cute plain text, the glow up is real.

Important: the html2text plugin is called automatically from the email output plugins and should normally not be called directly. don't @ her, she's booked and busy πŸ™ˆ

static parse(html=None)

parse html to text according to our preferences. this is where subclasses can override the HTML2Text settings or use a completely different parser. very customizable, very main character energy πŸ‘‘


🌈 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 <link> 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. literally every link leads to the same place, it's giving scam 😐

This parses the recent changes entries and extracts the relevant links from it. slay.

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 <link> 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. no cap, deduplication is not playing around here.


🧿 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. the opposite of droptitle, she's an includer not an excluder 🫢

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".


🧚 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. yes bestie, you too can write one. it's giving DIY era πŸ› οΈβœ¨

πŸŽ€ Basic plugin principles

To write a new plugin, you should start by creating a simple Python module, in your PYTHONPATH (https://docs.python.org/3/using/cmdline.html#envvar-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 convention is loose: as long as the plugin matches the expected API, it should just work. lowkey chaotic but we love her 🌸 For the purpose of this demonstration, we'll call our plugin trumpery (https://en.wiktionary.org/wiki/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 (https://docs.python.org/3/tutorial/modules.html) for more information about this concept in Python. organization is self care πŸ’†β€β™€οΈ

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() (#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! bestie collab when? πŸ«ΆπŸ’–

πŸ”₯ 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 (https://en.wikipedia.org/wiki/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', '')

That may look like complete gibberish to you if you are not familiar with programming or with Python programming in particular. honestly felt 😭 But let's take this from the top and copy that in our own plugin. The first line declares a function (https://en.wikibooks.org/wiki/Python_Programming/Functions) 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. very demure, very mindful debugging πŸ›βœ¨ 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 (https://pythonhosted.org/feedparser/reference-entry-summary.html) field which we can inspect. There's also a content (https://pythonhosted.org/feedparser/reference-entry-content.html#reference-entry-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 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!! πŸŽ€ bestie we literally skipped the two items that contain the fraud we wanted to remove from the world. no cap.

And notice the iconic part: we were able to modify the feed item. Which means we can also use that same trick to change the feed content. Normally you'd whip this out to fix malformed feeds... but let's have some fun instead and rename Trump to Drumpf πŸ’… (https://en.wikipedia.org/wiki/Donald_Trump_(Last_Week_Tonight)):

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',)
arguments received: ('NASA Announces Cassini End-of-Mission Media Activities',)
1 feeds processed

I know, absolutely hilarious, right? 😭 More seriously though β€” this is also exactly 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, ngl πŸ’€. They operate on the same principle as filter plugins (similar search path, similar function signature), but they're designed to actually output something for each new feed item found. This can be anything: a file πŸ“, an email πŸ“§, an HTTP request 🌐, whatever your little heart desires.

If there's a commandline tool that does what you need, it's 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 (which is, honestly, a whole mood πŸ™ˆ). To archive the feed items, we'll need to look at the link element that feedparser gives us (https://pythonhosted.org/feedparser/reference-entry-link.html). 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() (https://docs.python.org/3/library/logging.html#logging.info) to have things show up in --verbose, and logging.debug() (https://docs.python.org/3/library/logging.html#logging.debug) for --debug. But by default your plugin should be silent β€” unless there's an error that requires the user's intervention. In that case you should use logging.warning() (https://docs.python.org/3/library/logging.html#logging.warning) for transient errors that may be automatically recovered, and logging.error() (https://docs.python.org/3/library/logging.html#logging.error) for errors that require user intervention. The whole point is to allow users to ignore warnings safely. 🫢

Note that here we first check to see if the feed item actually has a link β€” because 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:

$ 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'))
    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 (http://knowyourmeme.com/memes/how-to-draw-an-owl) 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! Okay so it works but bestie… it's saving all of this into /run/user/1000. 🫠 That dir was literally just a safe-ish place to write, not a persistent one β€” it gets yeeted on reboot. Not the vibe. So let's make that path configurable, and that's exactly where plugin arguments come in. πŸ’…


πŸ’– User configuration πŸ’–

See that *args parameter? That came straight outta the configuration file, no cap. So you can just set the path in the config file, like:

[NASA]
url = https://www.nasa.gov/rss/dyn/breaking_news.rss
output = trumpery
args = /srv/archives/nasa/
filter = trumpery

And then we gotta teach the plugin to go grab that config, like:

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 🌐

Now, obviously πŸ₯² the plugin has only been saving the link itself, not the link's content. For that we need the requests module to do some heavy lifting, kinda 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 saves the actual link content (result.text) into the file. The line that's doing the most is this one:

# fetch the URL in memory
result = session.get(item.get('link'))

…which fetches the URL into memory and also checks for errors. The other lil glow-up in the final plugin is just:

archive.write(result.text)

…which writes the article content instead of the link. Chef's kiss. πŸ‘‘

And notice how the session argument is used here rather than talking straight to the requests module? That's deliberate β€” it leverages a caching system we already have, plus configuration like user-agent and so on. iykyk 🧚


πŸ” Plugin return values πŸ”

Notice how we return False right here β€” that makes the plugin system not add the item to the cache, so it gets retried on the next run. πŸ” If the plugin returns True or nothing at all (None), the plugin counts as having succeeded and the entry gets added to the cache. That logic is defined in feed2exec.controller.FeedManager.fetch().


πŸƒ Catchup πŸƒ

One last thing that's missing, and it's lowkey critical for literally every plugin: you have to respect the catchup setting. It gets propagated all the way up from the commandline or the configuration, down to the plugins, through the feed parameters. 🌈

How you handle it depends on the plugin, but the basic idea is to give feedback (when verbose) about the activity when the plugin runs, while not actually doing 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'))

See how we still fetch the actual feed content but stop before doing any permanent operation? That's the whole spirit of the "catchup" operation: we don't just skip the "write" operations, we also skip any operation that could slow the "catchup" down. Fetching stuff over the network takes time, and even though it can be considered a "readonly" operation as far as the local machine is concerned, we're effectively writing to the network β€” so that operation shouldn't occur. πŸ’€

Hopefully that should get you going with most of the plugins you're thinking of writing! 🫢


πŸ§ͺ Writing tests πŸ§ͺ

Writing tests is essential if you want the code to stay maintainable in the future. It makes refactoring easy and it can catch bugs that manual testing might not, especially when you hit complete coverage (though honestly, that's no guarantee either πŸ™ˆ).

Let's take our archive plugin as the example. First step: edit the tests/test/test_plugins.py file, where the other plugins are tested too. We start by making a function called test_archive so that Pytest (https://pytest.org/), our test bed, will find it:

def test_archive(tmpdir, betamax):  # noqa
    pass

Notice those two arguments, tmpdir and betamax. Both of those are fixtures (https://docs.pytest.org/en/latest/fixture.html) β€” a pytest concept that lets you simulate an environment. Specifically: the tmpdir fixture ships with pytest and lets you easily manage (and auto-remove) temporary directories, and the betamax fixture uses the betamax module (https://betamax.readthedocs.io/) to record then replay HTTP requests. πŸŽ€

Then we gotta actually do something. We need to build a feed and a feed item that we can send into the plugin. We could also just directly parse an existing feed β€” and yeah, some plugins do exactly that β€” but ours is simple, so 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. That's necessary so the session gets properly re-initialized in the feed item β€” otherwise the betamax fixture will not work, periodt. Then it creates a fake feed entry with just one link and a title. After that we can call our plugin and verify that it saves the file the way 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 running it 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 .........

okay so obvi the coverage report came out looking like this, bestie:

----------- 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%
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 ============================

so like… look at the test coverage, bestie. We only have 78% test coverage for our plugin 😭 which literally means some branches of the code were never even executed. Not a single time. They were just sitting there, unbothered, unexamined. So let's fix that πŸ’…

Peep the code β€” I see there are some conditionals for error handling. So bestie, let's simulate an error, and make sure that we don't create a file on error. Slay:

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 🫢 Now 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%
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 β€” that's it, that's the whole vibe, we're so close πŸŽ€

Note: Notice how I explicitly provided a path to my test. This is entirely optional. You can literally just run pytest-3 and it will run the whole test suite β€” this method is just faster, iykyk. Also notice how the coverage ratio is very low: this is normal, bestie, because 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() <#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 πŸ’Œ

✨ SEE ALSO ✨

πŸ‘‘ Author

Antoine BeauprΓ©

Copyright (C) 2016-2019 Antoine BeauprΓ©


and that's the whole page, bestie!! πŸ¦‹ This was 0.23.0, dated Sep 16, 2026, from FEED2EXEC-PLUGINS(1) β€” go forth and write the most iconic plugins, no cap πŸ’…πŸ‘‘πŸŒΈ

πŸ“¦ where this page comes from