.\" Man page generated from reStructuredText. . .TH "FEED2EXEC-PLUGINS" "1" "Feb 04, 2021" "0.17.1" "feed2exec" .SH NAME feed2exec-plugins \- feed2exec plugin documentation . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .sp This is a quick overview of the available plugins. .SH OUTPUT PLUGINS .SS Archive .INDENT 0.0 .TP .B feed2exec.plugins.archive.DEFAULT_ARCHIVE_DIR = \(aq/run/user/1000/\(aq default archive directory .UNINDENT .INDENT 0.0 .TP .B 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, specified by DEFAULT_ARCHIVE_DIR or through the output \fIargs\fP value. .sp Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C [NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = archive args = /srv/archive/nasa/ .ft P .fi .UNINDENT .UNINDENT .sp The above will save the “NASA breaking news” into the \fB/srv/archive/nasa\fP directory. Do \fInot\fP use interpolation here as the feed’s variable could be used to mount a directory transversal attack. .UNINDENT .SS Echo .INDENT 0.0 .TP .B 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. .sp This plugin does a similar thing when acting as a filter. .UNINDENT .INDENT 0.0 .TP .B feed2exec.plugins.echo.filter This filter just keeps the feed unmodified. It is just there for testing purposes. .sp alias of \fI\%feed2exec.plugins.echo.output\fP .UNINDENT .SS Error .INDENT 0.0 .TP .B 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. .UNINDENT .SS Exec .INDENT 0.0 .TP .B 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 \fI\%Sanitization\fP documentation for more information in that regard. That is limited to stripping out hostile HTML tags, however. .sp 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. .sp For example, if a program can write files with the \fB\-o\fP option, a feed could set their title to \fB\-oevil\fP to overwrite the \fBevil\fP file. The only way to workaround that issue is to carefully craft the commandline so that this cannot happen. .sp Alternatively, writing a Python plugin is much safer as you can sanitize the arguments yourself. .sp Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C [NASA Whats up?] url = https://www.nasa.gov/rss/dyn/whats_up.rss output = feed2exec.plugins.exec args = wget \-P /srv/archives/nasa/ {item.link} .ft P .fi .UNINDENT .UNINDENT .sp The above is the equivalent of the archive plugin: it will save feed item links to the given directory. .UNINDENT .SS Maildir .INDENT 0.0 .TP .B 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. .sp The configuration is a little clunky, but it should be safe against hostile feeds. .INDENT 7.0 .TP .B Parameters \fBto_addr\fP (\fI\%str\fP) – the email to use as “to” (defaults to \fI\%USER@localdomain\fP) .UNINDENT .sp Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C [NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss mailbox = ~/Maildir/ folder = nasa args = me@example.com .ft P .fi .UNINDENT .UNINDENT .sp The above will save new feed items from the NASA feed into the ~/Maildir/nasa/ maildir folder, and will set the \fITo\fP field of the email to \fIme@example.com\fP\&. .UNINDENT .SS Mbox .INDENT 0.0 .TP .B 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. .sp This is mostly for testing purposes, but can of course be used in the unlikely event where you prefer mbox folders over the \fI\%feed2exec.plugins.maildir\fP plugin. .INDENT 7.0 .TP .B Parameters \fBto_addr\fP (\fI\%str\fP) – the email to use as “to” (defaults to \fI\%USER@localdomain\fP) .TP .B 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. .UNINDENT .UNINDENT .SS Null .INDENT 0.0 .TP .B feed2exec.plugins.null.output(*args, **kwargs) This plugin does nothing. It can be useful in cases where you want to catchup with imported feeds. .UNINDENT .INDENT 0.0 .TP .B feed2exec.plugins.null.filter(item=None, *args, **kwargs) The null filter removes all elements from a feed item .UNINDENT .SS Transmission .INDENT 0.0 .TP .B feed2exec.plugins.transmission.sanitize(text, repl=\(aq\-\(aq) like utils.slug, but without lowercase and allow custom replacement .sp .nf .ft C >>> sanitize(\(aqtest\(aq) \(aqtest\(aq >>> sanitize(\(aq../../../etc/password\(aq) \(aqetc\-password\(aq >>> sanitize(\(aqFoo./.bar\(aq, repl=\(aq.\(aq) \(aqFoo.bar\(aq .ft P .fi .UNINDENT .INDENT 0.0 .TP .B feed2exec.plugins.transmission.output(hostname=\(aqlocalhost\(aq, *args, feed=None, item=None, **kwargs) the transmission plugin will send feed items to a \fI\%transmission\fP instance .sp it assumes the \fBtransmission\-remote\fP command is already installed and configured to talk with transmission. .sp the hostname is passed in the \fBargs\fP configuration and defaults to localhost. the \fBfolder\fP parameter is also used to determine where to save the actual torrents files. .sp 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. .sp if the title is unique for each torrent, you may use a filter to set the title to the right location. .UNINDENT .SS Wayback .INDENT 0.0 .TP .B feed2exec.plugins.wayback.output(*args, feed=None, item=None, session=None, **kwargs) This plugin saves the feed items \fIlink\fP element to the wayback machine. It will retry URLs that fail, so it may be necessary to manually catchup feeds if they have broken \fIlink\fP fields. .sp Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C [NASA IOTD wayback] url = https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss output = feed2exec.plugins.wayback .ft P .fi .UNINDENT .UNINDENT .sp The above will save the Image of the day updates to the wayback machine. .UNINDENT .SH FILTER PLUGINS .SS Droptitle .INDENT 0.0 .TP .B 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. .sp Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C [NASA breaking news] url = https://www.nasa.gov/rss/dyn/breaking_news.rss filter = feed2exec.plugins.droptitle filter_args = Trump .ft P .fi .UNINDENT .UNINDENT .sp 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. .UNINDENT .SS Emptysummary .INDENT 0.0 .TP .B 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. .UNINDENT .SS Html2text .INDENT 0.0 .TP .B class feed2exec.plugins.html2text.filter(*args, feed=None, item=None, **kwargs) This filter plugin takes a given feed item and adds a \fBcontent_plain\fP field with the HTML parsed as text. .sp \fBIMPORTANT:\fP .INDENT 7.0 .INDENT 3.5 the html2text plugin is called automatically from the email output plugins and should normally not be called directly. .UNINDENT .UNINDENT .INDENT 7.0 .TP .B 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 .UNINDENT .UNINDENT .SS Ikiwiki Recentchanges .INDENT 0.0 .TP .B feed2exec.plugins.ikiwiki_recentchanges.filter(*args, item=None, **kwargs) the ikiwiki_recentchanges plugin fixes links in ikiwiki feeds .sp Ikiwiki recent changes show all the recent edits to pages, but the \fB\fP 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. .sp This parses the recent changes entries and extracts the relevant links from it. .sp An alternative to this is to use the following entry to generate a special feed in Ikiwiki: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C [[!inline pages="*" feeds=yes feedonly=yes feedfile=archive show=10]] .ft P .fi .UNINDENT .UNINDENT .sp This generates a feed with proper \fB\fP elements but requires write access to the wiki. .sp 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. .UNINDENT .SH WRITING NEW PLUGINS .sp Most of the actual work in the program is performed by plugins. A plugin is a simple Python module that has a \fBoutput\fP or \fBfilter\fP “callable” (function or class) with a predefined interface. .SS Basic plugin principles .sp To write a new plugin, you should start by creating a simple Python module, in your \fI\%PYTHONPATH\fP\&. You can find which directories are in the path by calling: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ python3 \-c "import sys; print(sys.path)" [\(aq\(aq, \(aq/usr/lib/python35.zip\(aq, \(aq/usr/lib/python3.5\(aq, \(aq/usr/lib/python3.5/plat\-x86_64\-linux\-gnu\(aq, \(aq/usr/lib/python3.5/lib\-dynload\(aq, \(aq/usr/local/lib/python3.5/dist\-packages\(aq, \(aq/usr/lib/python3/dist\-packages\(aq] .ft P .fi .UNINDENT .UNINDENT .sp In the above example, a good location would be \fB/usr/local/lib/python3.5/dist\-packages\fP\&. The naming convention is loose: as long as the plugin matches the expected API, it should just work. For the purpose of this demonstration, we’ll call our plugin \fI\%trumpery\fP, so we will create the plugin code like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C touch /usr/local/lib/python3.5/dist\-packages/trumpery.py .ft P .fi .UNINDENT .UNINDENT .sp Naturally, if you are going to write multiple plugins, you may want to regroup your multiple plugins in a package, see the \fI\%module documentation\fP for more information about this concept in Python. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 There is a rudimentary plugin resolution process that looks for plugins first in the \fIfeed2exec.plugins\fP namespace but then globally. This is done in \fBfeed2exec.plugins.resolve()\fP, called from the \fBadd\fP and \fBparse\fP commands. This means that the absolute path is expected to be used in the configuration file and internally. .UNINDENT .UNINDENT .sp You are welcome to distribute plugins separately or send them as merge requests, see contribute for more information on how to participate in this project. We of course welcome contributions to this documentation as well! .SS Filters .sp 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 \fI\%Trump\fP in it. For that purpose, we’ll create a plugin similar to the already existing \fI\%feed2exec.plugins.droptitle\fP plugin, but that operates on the \fIbody\fP 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def filter(*args, feed=None, item=None, **kwargs): \(aq\(aq\(aqthe 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. \(aq\(aq\(aq item[\(aqskip\(aq] = \(aq \(aq.join(args) in item.get(\(aqtitle\(aq, \(aq\(aq) .ft P .fi .UNINDENT .UNINDENT .sp 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 \fI\%function\fP that takes at least a \fBfeed\fP and a \fBitem\fP 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 \fBpass\fP statement to make sure the plugin works (even if it does nothing for now): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def filter(*args, feed=None, item=None, **kwargs): pass .ft P .fi .UNINDENT .UNINDENT .sp We can already test our plugin by adding it to our configuration, in \fB~/.config/feed2exec.ini\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [NASA] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = feed2exec.plugins.echo args = {item.title} filter = trumpery .ft P .fi .UNINDENT .UNINDENT .sp Notice how we use the \fBoutput\fP 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ 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: (\(aqPresident Trump Welcomes Home Record\-breaking NASA Astronaut Peggy Whitson\(aq,) arguments received: (\(aqThree International Space Station Crewmates Safely Return to Earth\(aq,) arguments received: (\(aqNASA Statement on Nomination for Agency Administrator\(aq,) arguments received: (\(aqNASA Television to Air Return of Three International Space Station Crew Members\(aq,) arguments received: (\(aqNASA and Iconic Museum Honor Voyager Spacecraft 40th Anniversary\(aq,) arguments received: (\(aqNASA’s Johnson Space Center Closes Through Labor Day for Tropical Storm Harvey\(aq,) arguments received: (\(aqNASA Cancels Planned Media Availabilities with Astronauts\(aq,) arguments received: (\(aqNASA Awards $400,000 to Top Teams at Second Phase of 3D\-Printing Competition\(aq,) arguments received: (\(aqNASA Awards Contract for Center Protective Services for Glenn Research Center\(aq,) arguments received: (\(aqNASA Announces Cassini End\-of\-Mission Media Activities\(aq,) 1 feeds processed .ft P .fi .UNINDENT .UNINDENT .sp Good! The feed is fetched and items are displayed. It means our filter didn’t interfere, but now it’s time to make it \fIdo\fP something. To skip items, we need to set the \fBskip\fP attribute for the feed item to \fITrue\fP if we want to skip it and \fIFalse\fP otherwise. So we’ll use a simple recipe, a bit like \fIdroptitle\fP does, but simpler, to look at the feed content to look for our evil word. The \fBfeedparser\fP documentation tells us feed items have a \fI\%summary\fP field which we can inspect. There’s also a \fI\%content\fP list, but that’s a little more complicated so we’ll skip that for now. So, let’s set the \fBskip\fP parameter to match if there is the evil word in our feed item, like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def filter(*args, feed=None, item=None, **kwargs): item[\(aqskip\(aq] = \(aqTrump\(aq in item.get(\(aqsummary\(aq, \(aq\(aq) .ft P .fi .UNINDENT .UNINDENT .sp And let’s see the result (note that we use the \fB\-\-force\fP argument here otherwise we would just skip all items because of the cache): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ 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: (\(aqThree International Space Station Crewmates Safely Return to Earth\(aq,) item NASA Statement on Nomination for Agency Administrator of feed NASA filtered out arguments received: (\(aqNASA Television to Air Return of Three International Space Station Crew Members\(aq,) arguments received: (\(aqNASA and Iconic Museum Honor Voyager Spacecraft 40th Anniversary\(aq,) arguments received: (\(aqNASA’s Johnson Space Center Closes Through Labor Day for Tropical Storm Harvey\(aq,) arguments received: (\(aqNASA Cancels Planned Media Availabilities with Astronauts\(aq,) arguments received: (\(aqNASA Awards $400,000 to Top Teams at Second Phase of 3D\-Printing Competition\(aq,) arguments received: (\(aqNASA Awards Contract for Center Protective Services for Glenn Research Center\(aq,) arguments received: (\(aqNASA Announces Cassini End\-of\-Mission Media Activities\(aq,) 1 feeds processed .ft P .fi .UNINDENT .UNINDENT .sp Successs! We have skipped the two items that contain the fraud we wanted to remove from the world. Notice how we were able to \fImodify\fP the feed item: we can also use that to \fIchange\fP the feed content. Normally, we would use this to fix malformed feeds, but let’s have some fun instead and \fI\%rename Trump to Drumpf\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def filter(*args, feed=None, item=None, **kwargs): item[\(aqtitle\(aq] = item.get(\(aqtitle\(aq, \(aq\(aq).replace(\(aqTrump\(aq, \(aqDrumpf\(aq) .ft P .fi .UNINDENT .UNINDENT .sp And the result: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ 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: (\(aqPresident Drumpf Welcomes Home Record\-breaking NASA Astronaut Peggy Whitson\(aq,) arguments received: (\(aqThree International Space Station Crewmates Safely Return to Earth\(aq,) arguments received: (\(aqNASA Statement on Nomination for Agency Administrator\(aq,) arguments received: (\(aqNASA Television to Air Return of Three International Space Station Crew Members\(aq,) arguments received: (\(aqNASA and Iconic Museum Honor Voyager Spacecraft 40th Anniversary\(aq,) arguments received: (\(aqNASA’s Johnson Space Center Closes Through Labor Day for Tropical Storm Harvey\(aq,) arguments received: (\(aqNASA Cancels Planned Media Availabilities with Astronauts\(aq,) arguments received: (\(aqNASA Awards $400,000 to Top Teams at Second Phase of 3D\-Printing Competition\(aq,) arguments received: (\(aqNASA Awards Contract for Center Protective Services for Glenn Research Center\(aq,) arguments received: (\(aqNASA Announces Cassini End\-of\-Mission Media Activities\(aq,) 1 feeds processed .ft P .fi .UNINDENT .UNINDENT .sp I know, absolutely hilarious, right? More seriously, this is also how the \fI\%feed2exec.plugins.html2text\fP 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! .SS Output plugins .sp 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 \fBexec\fP 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. .SS Basic arguments .sp 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def output(*args, feed=None, item=None, **kwargs): pass .ft P .fi .UNINDENT .UNINDENT .sp This is the equivalent of the \fBnull\fP plugin and basically outputs nothing at all. To archive the feed items, we’ll need to look at the \fI\%link\fP element feedparser gives us. Let’s see what that looks like for the NASA feed: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def output(*args, feed=None, item=None, **kwargs): # only operate on items that actually have a link if item.get(\(aqlink\(aq): print(item.get(\(aqlink\(aq, \(aq\(aq)) else: logging.info(\(aqno link for feed item %s, not archiving\(aq, item.get(\(aqtitle\(aq)) .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 Note that we try to make plugins silent in general. You can use \fI\%logging.info()\fP to have things show up in \fB\-\-verbose\fP and \fI\%logging.debug()\fP for \fB\-\-debug\fP 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 \fI\%logging.warning()\fP for transient errors that may be automatically recovered and \fI\%logging.error()\fP for errors that require user intervention. This is to allow users to ignore warnings safely. .UNINDENT .UNINDENT .sp Note that here we first check to see if the feed item actually \fIhas\fP a link \- not all feeds do! After adding the above to our \fBtrumpery\fP plugin and adding it as an output plugin: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [NASA] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = trumpery filter = trumpery .ft P .fi .UNINDENT .UNINDENT .sp We can try to see what happens when we call it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ 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 .ft P .fi .UNINDENT .UNINDENT .SS Sanitizing contents .sp 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 \fIslug\fP function to make a filesystem\-safe name from the feed title and save those files in a pre\-determined location: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import logging import os.path from feed2exec.utils import slug ARCHIVE_DIR=\(aq/run/user/1000/feed\-archives/\(aq def output(*args, feed=None, item=None, session=None, **kwargs): # make a safe path from the item name path = slug(item.get(\(aqtitle\(aq, \(aqno\-name\(aq)) # 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(\(aqlink\(aq): # tell the user what\(aqs going on, if verbose # otherwise, we try to stay silent if all goes well logging.info(\(aqsaving feed item %s to %s from %s\(aq, item.get(\(aqtitle\(aq), path, item.get(\(aqlink\(aq)) # open the file with open(path, \(aqw\(aq) as archive: # write the response archive.write(item.get(\(aqlink\(aq)) else: logging.info(\(aqno link for feed item %s, not archiving\(aq, item.get(\(aqtitle\(aq)) .ft P .fi .UNINDENT .UNINDENT .sp Now I know this may look like a \fI\%huge step from the previous one\fP but I’m sorry, I couldn’t find a simpler second step. :) The output now looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ 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 .ft P .fi .UNINDENT .UNINDENT .sp Sweet! Now it’s not really nice to save this in \fB/run/user/1000\fP\&. 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. .SS User configuration .sp You see that \fB*args\fP parameter? That comes straight from the configuration file. So you could set the path in the configuration file, like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [NASA] url = https://www.nasa.gov/rss/dyn/breaking_news.rss output = trumpery args = /srv/archives/nasa/ filter = trumpery .ft P .fi .UNINDENT .UNINDENT .sp We also need to modify the plugin to fetch that configuration, like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def output(*args, feed=None, item=None, session=None, **kwargs): # make a safe path from the item name path = slug(item.get(\(aqtitle\(aq, \(aqno\-name\(aq)) # take the archive dir from the user or use the default archive_dir = \(aq \(aq.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 .ft P .fi .UNINDENT .UNINDENT .SS Making HTTP requests .sp And now obviously, we only saved the link itself, not the link \fIcontent\fP\&. For that we need some help from the \fBrequests\fP module, and do something like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # fetch the URL in memory result = session.get(item.get(\(aqlink\(aq)) if result.status_code != requests.codes.ok: logging.warning(\(aqfailed to fetch link %s: %s\(aq, item.get(\(aqlink\(aq), result.status_code) # make sure we retry next time return False # open the file with open(path, \(aqw\(aq) as archive: # write the response archive.write(result.text) .ft P .fi .UNINDENT .UNINDENT .sp This will save the actual link content (\fBresult.text\fP) to the file. The important statement here is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # fetch the URL in memory result = session.get(item.get(\(aqlink\(aq)) .ft P .fi .UNINDENT .UNINDENT .sp which fetches the URL in memory and checks for errors. The other change in the final plugin is simply: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C archive.write(result.text) .ft P .fi .UNINDENT .UNINDENT .sp which writes the article content instead of the link. .sp Notice how the \fBsession\fP argument is used here instead of talking directly to the \fBrequests\fP module. This leverages a caching system we already have, alongside configuration like user\-agent and so on. .SS Plugin return values .sp Notice how we \fBreturn False\fP 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 \fBTrue\fP or nothing (\fBNone\fP), the plugin is considered to have succeeded and the entry is added to the cache. That logic is defined in \fBfeed2exec.controller.FeedManager.fetch()\fP\&. .SS Catchup .sp A final thing that is missing that is critical in all plugins is to respect the \fBcatchup\fP setting. It is propagated up from the commandline or configuration all the way down to plugins, through the \fBfeed\fP 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 \fIbut\fP to not actually \fIdo\fP anything. In our case, we simply return success, right before we fetch the URL: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C if feed.get(\(aqcatchup\(aq): return True # fetch the URL in memory result = session.get(item.get(\(aqlink\(aq)) .ft P .fi .UNINDENT .UNINDENT .sp 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 \fIwriting\fP to the network so that operation shouldn’t occur. .sp Hopefully that should get you going with most of the plugins you are thinking of writing! .SS Writing tests .sp 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 garantee either). .sp We’ll take our \fIarchive\fP plugin as an example. The first step is to edit the \fBtests/test/test_plugins.py\fP file, where other plugins are tests as well. We start by creating a function named \fBtest_archive\fP so that \fI\%Pytest\fP, our test bed, will find it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def test_archive(tmpdir, betamax): # noqa pass .ft P .fi .UNINDENT .UNINDENT .sp Notice the two arguments named \fBtmpdir\fP and \fBbetamax\fP\&. Both of those are \fI\%fixtures\fP, a pytest concept that allows to simulate an environment. In particular, the \fBtmpdir\fP fixture, shipped with pytest, allows you to easily manage (and automatically remove) temporary directories. The \fBbetamax\fP fixtures is a uses the \fI\%betamax\fP module to record then replay HTTP requests. .sp 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C feed = Feed(\(aqtest archive\(aq, test_sample) item = feedparser.FeedParserDict({\(aqlink\(aq: \(aqhttp://example.com/\(aq, \(aqtitle\(aq: \(aqexample site\(aq}) .ft P .fi .UNINDENT .UNINDENT .sp This creates a new feed based on the \fBtest_sample\fP feed. This is necessary so that the \fBsession\fP is properly re\-initialized in the feed item (otherwise the \fBbetamax\fP fixture will not work). Then it creates a fake feed entry simply with one link 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def test_archive(tmpdir, betamax): # noqa dest = tmpdir.join(\(aqarchive\(aq) feed = Feed(\(aqtest archive\(aq, test_sample) item = feedparser.FeedParserDict({\(aqlink\(aq: \(aqhttp://example.com/\(aq, \(aqtitle\(aq: \(aqexample site\(aq}) assert archive_plugin.output(str(dest), feed=feed, item=item) assert dest.join(\(aqexample\-site\(aq).check() .ft P .fi .UNINDENT .UNINDENT .sp Then we can try to run this with \fBpytest\-3\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [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% 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 ============================ .ft P .fi .UNINDENT .UNINDENT .sp 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C dest.remove() item = feedparser.FeedParserDict({\(aqlink\(aq: \(aqhttp://example.com/404\(aq, \(aqtitle\(aq: \(aqexample site\(aq}) assert not archive_plugin.output(str(dest), feed=feed, item=item) assert not dest.join(\(aqexample\-site\(aq).check() .ft P .fi .UNINDENT .UNINDENT .sp There. Let’s see the effect on the test coverage: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [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 ============================= .ft P .fi .UNINDENT .UNINDENT .sp Much better! Only 3 lines left to cover! .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 Notice how I explicitly provided a path to my test. This is entirely optional. You can just run \fBpytest\-3\fP 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 \fIone\fP plugin here. .UNINDENT .UNINDENT .sp 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 \fBtest_plugins.py\fP file distributed with this documentation. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 If you discover a bug associated with a single feed, you can use the betamax session and the \fBfeed2exec.model.Feed.parse()\fP function to manually parse a feed and fire your plugin. This is how email functionality is tested: see the \fBfeed2exec.tests.test_plugins.test_email()\fP function for an example. .UNINDENT .UNINDENT .SH SEE ALSO .sp \fBfeed2exec(1)\fP .SH AUTHOR Antoine Beaupré .SH COPYRIGHT Copyright (C) 2016-2019 Antoine Beaupré .\" Generated by docutils manpage writer. .