sab_api Bash Script

Got a program that plays well with SABnzbd? Share it here!
Post Reply
User avatar
abeam89
Newbie
Newbie
Posts: 10
Joined: October 18th, 2009, 2:39 am

sab_api Bash Script

Post by abeam89 »

*UPDATE 2012-03-28*
I have added an installer script, install.sh, that will do all of the dirty work for getting sab_api up and running.
I've also added bash_completion, which makes the script tremendously more useful.
I'll keep updating the project as I can and to resolve any feedback that I receive regarding it.
I'll also post the latest README as the newest post here for anyone that's interested.

https://github.com/abeam89/sab_api

I have created a bash script to perform SABnzbd API calls if anyone is interested. I believe I have supported every documented API functionality. It might not be that useful to many, but hopefully for some it can be helpful. It saves me time performing simple operations and works quite well for me. Any other input or feedback will be taken into consideration as well, as I'm happy to improve the project.

You can download the source here:
https://github.com/abeam89/sab_api

Enjoy!
Last edited by abeam89 on March 28th, 2012, 12:46 am, edited 1 time in total.
User avatar
sander
Release Testers
Release Testers
Posts: 8823
Joined: January 22nd, 2008, 2:22 pm

Re: sab_api Bash Script

Post by sander »

Just a post to let you know I tried it.

I did a

Code: Select all

git clone https://github.com/abeam89/sab_api.git
and it worked. Good. And a beautiful usage:

Code: Select all

sander@R540:~/sab_api/sab_api$ ./sab_api 
Usage: sab_api function[=parameter] [options]

This script allows the user to perform SABnzbd API calls from the command line
easily. The user should provide the function they would like to perform along
with any pertinent parameters as specified in the usage.

Please see http://wiki.sabnzbd.org/api to clear up any questions about the API.

The following functions are supported:
--------------------------------------------------------------------------------
addid=ID              | Add nzb(s) using a Newzbin ID (ID)
--------------------------------------------------------------------------------
addpath=PATH          | Add nzb(s) using a local file path (PATH)
--------------------------------------------------------------------------------
addurl=URL            | Add nzb(s) using a URL (URL)
--------------------------------------------------------------------------------
categories            | Return categories from SABnzbd
--------------------------------------------------------------------------------
chcat=ITEM@CAT        | Change the category for an item (ITEM) to the category
                      | (CAT) that is specified
--------------------------------------------------------------------------------
chname=ITEM@NAME      | Change the name of an item (ITEM) to the name (NAME)
                      | specified. The name is used for the final folder name,
                      | and input for any post-processing sorting, if used.
--------------------------------------------------------------------------------
chpp=ITEM@PP_LEVEL    | Change the post-processing level (PP_LEVEL) for the
                      | specified item (ITEM).
                      | Available post-processing levels are:
                      | Skip: 0
                      | +Repair: 1
                      | +Repair/Unpack: 2
                      | +Repair/Unpack/Delete: 3
--------------------------------------------------------------------------------
chpriority=ITEM@PRI   | Change the priority (PRI) for the specified item (ITEM). 
                      | Available priority levels are:
                      | Default Priority: -100
                      | Paused: -2
                      | Low Priority: -1
                      | Normal Priority: 0
                      | High Priority: 1
--------------------------------------------------------------------------------
chscript=ITEM@SCRIPT  | Change the script for an item (ITEM) to the script 
                      | (SCRIPT) that is specified
--------------------------------------------------------------------------------
completeaction=ACTION | Set the action (ACTION) to be performed upon queue
                      | completion. For a script, prepend "script_" to the
                      | action. An example would be:
                      | "sab_api completeaction=script_examplescript.sh"
--------------------------------------------------------------------------------
custom=MODE           | Allows the user to specify a custom API call which will
                      | be prepended with the core portion of the URL and have
                      | the API key appended as well. MODE represents the API
                      | mode that the user will be implementing (with all its
                      | necessary parameters less the API key)
--------------------------------------------------------------------------------
delete-q=ITEM[,ITEM]  | Delete the specified item(s) (ITEM) from the SABnzbd
                      | queue. To delete the entire queue, use:
                      | "sab_api delete-q=all"
                      | DANGEROUS! An attempt to delete "all" items will warn
                      | you unless the nowarn option is specified at the command
                      | line
--------------------------------------------------------------------------------
delete-h=ITEM[,ITEM]  | Delete the specified item(s) (ITEM) from the SABnzbd
                      | history. To delete the entire history, use:
                      | "sab_api delete-h=all"
                      | DANGEROUS! An attempt to delete "all" items will warn
                      | you unless the nowarn option is specified at the command
                      | line
--------------------------------------------------------------------------------
getconfig[=SECTION]   | Get the SABnzbd configuration. Optionally specify the
                      | section (SECTION) to be printed.
--------------------------------------------------------------------------------
history               | History output. This function can be used with the
                      | "start" and "limit" parameters or be used with its
                      | default values for these parameters
--------------------------------------------------------------------------------
help (--help, -h, -H) | Print this help documentation
--------------------------------------------------------------------------------
help=FEATURE          | Print this script's help documentation for a specific
                      | feature (FEATURE) that the script provides. Some
                      | examples are provided below:
                      | "sab_api help=addid"
                      | "sab_api help=categories"
                      | "sab_api help=--cat"
--------------------------------------------------------------------------------
move=ITEM@POSITION    | Move item (ITEM) to a specific position (POSITION) in
                      | the queue
--------------------------------------------------------------------------------
pause                 | Pause the entire SABnzbd queue
--------------------------------------------------------------------------------
pause=ITEM            | Pause the specified item (ITEM) in the queue
--------------------------------------------------------------------------------
pause-for=DURATION    | Pause the SABnzbd queue for the specified duration
                      | (DURATION)
--------------------------------------------------------------------------------
queue                 | Advanced queue output, more verbose than the simple
                      | queue output. This function can be used with the
                      | "start" and "limit" parameters or be used with its
                      | default values for these parameters
--------------------------------------------------------------------------------
regen-api             | Regenerate the SABnzbd API key and return it.
--------------------------------------------------------------------------------
restart               | Restarts SABnzbd
                      | DANGEROUS! This will warn you unless the nowarn option 
                      | is specified at the command line
--------------------------------------------------------------------------------
resume                | Resume the entire SABnzbd queue
--------------------------------------------------------------------------------
resume=ITEM           | Resume the specified item (ITEM) in the queue
--------------------------------------------------------------------------------
retrieve=ITEM         | Retrieve the details for the specified item (ITEM) in
                      | the queue
--------------------------------------------------------------------------------
retry=ITEM            | Retry the item (ITEM) specified
--------------------------------------------------------------------------------
scripts               | Return scripts available in SABnzbd
--------------------------------------------------------------------------------
setconfig=SEC@KW@VAL  | Set the configuration of the specified keyword (KW) in
                      | the specified section (SEC) to the specified value (VAL)
--------------------------------------------------------------------------------
shutdown              | Shut down SABnzbd
                      | DANGEROUS! This will warn you unless the nowarn option 
                      | is specified at the command line
--------------------------------------------------------------------------------
speedlimit=LIMIT      | Set the download speed limit to the specified value 
                      | (LIMIT)
--------------------------------------------------------------------------------
status                | Simple status of SABnzbd. This is now deprecated by the
                      | SABnzbd API in favor of the advanced queue output.
--------------------------------------------------------------------------------
swap=ITEM1@ITEM2      | Swap the queue position of two SABnzbd queue items
                      | which are provided by the user as ITEM1 and ITEM2
--------------------------------------------------------------------------------
toggle-pause          | Toggle the SABnzbd queue paused state
--------------------------------------------------------------------------------
version               | Return the version of SABnzbd that is in use
--------------------------------------------------------------------------------
warning               | Return the current warning data from SABnzbd
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
Additional options:
--------------------------------------------------------------------------------
--cat=CAT             | Specify a category (CAT) for an NZB that is being added.
                      | Note that this option is only pertinent to the various
                      | methods for adding an NZB
--------------------------------------------------------------------------------
--json (-j)           | Change the output type from XML to JSON. The output
                      | defaults to XML. This option only pertinent to functions
                      | which have structured output which can be specified in
                      | the API. XML is specified as the default format simply
                      | because JSON tends to be difficult to parse using bash.
--------------------------------------------------------------------------------
--limit=LIMIT         | Specify the limit parameter (LIMIT) for the queue and
                      | history functions. This value is defaulted to 1
--------------------------------------------------------------------------------
--noaction (-a)       | This parameter ensures the script will not access the
                      | URL that is constructed, but rather simply print the
                      | URL. To print the URL and still access it, use the
                      | "--print-url" option
--------------------------------------------------------------------------------
--nowarn (-w)         | This parameter ensures no warnings will be presented
                      | when attempting to use the script with dangerous API
                      | functions
--------------------------------------------------------------------------------
--pp=PP_LEVEL         | Specify the post-processing level for an NZB that is
                      | being added. Note that this option is only pertinent to
                      | the various methods for adding an NZB.
                      | Available post-processing options are:
                      | Skip: 0
                      | +Repair: 1
                      | +Repair/Unpack: 2
                      | +Repair/Unpack/Delete: 3
--------------------------------------------------------------------------------
--print-url (-u)      | Print the URL that you have constructed using the script
                      | as well as execute it. To print the URL and not access
                      | it, use the "--noaction" option
--------------------------------------------------------------------------------
--priority=PRI        | Specify the priority (PRI) for an NZB that is being
                      | added. Note that this option is only pertinent for the
                      | various methods of adding an NZB.
                      | Available priority levels are:
                      | Default Priority: -100
                      | Paused: -2
                      | Low Priority: -1
                      | Normal Priority: 0
                      | High Priority: 1
--------------------------------------------------------------------------------
--script=SCRIPT       | Specify the script (SCRIPT) to be used for an NZB that
                      | is being added. Note that this option is only pertinent
                      | to the various methods for adding an NZB
--------------------------------------------------------------------------------
--silent (-s)         | Silent operation (no output)
--------------------------------------------------------------------------------
--start=START         | Specify the start parameter (START) for the queue and
                      | history functions. This value is defaulted to 0
--------------------------------------------------------------------------------

sander@R540:~/sab_api/sab_api$ 
I see the output is in XML or JSON. That's quite expect as that's the output by SAB itself, but I wonder if plain text is possible too as that's easier for typical bash script to process ... although a user's oneliner could create that too.

Code: Select all

sander@R540:~/sab_api/sab_api$ ./sab_api status scripts
<?xml version="1.0" encoding="UTF-8" ?>
<scripts><script>None</script>
<script>virusscanner.sh</script>
<script>scriptje-exit-1234.sh</script>
<script>scriptje.sh</script>
</scripts>

sander@R540:~/sab_api/sab_api$ ./sab_api status scripts -j
{"scripts":["None","virusscanner.sh","scriptje-exit-1234.sh","scriptje.sh"]}sander@R540:~/sab_api/sab_api$ 
sander@R540:~/sab_api/sab_api$ 
User avatar
abeam89
Newbie
Newbie
Posts: 10
Joined: October 18th, 2009, 2:39 am

Re: sab_api Bash Script

Post by abeam89 »

Thanks for the feedback sander! I appreciate you taking the time to give it a look.

The only reason I didn't implement plain text output is because everyone would likely want it formatted differently. If there is some type of consensus on how this should be implemented I would be very interested to hear what is recommended. I would be happy to implement this as an additional feature in this case.

However, as you noted, it is very simple to extract XML data in Bash using xpath. That's the main reason I'm using XML as the default output format from sab_api.

Below is a basic example to return the current color scheme of SABnzbd:

Code: Select all

$ sab_api queue | xpath -q -e '//queue/color_scheme/text()'
Returns...

Code: Select all

gold
To take advantage of this for more useful queries just alter the query path as desired. The 'text()' functionality is what extracts the text and drops the tags. To maintain the tags, just leave the 'text()' portion off of the end of the query.

The reason I think this is so nice is because the user stays in control. Let's use the test example you provided to return the scripts.

Code: Select all

$ sab_api scripts | xpath -q -e '//scripts/script/text()'
Returns...(I substituted your output values)

Code: Select all

None
virusscanner.sh
scriptje-exit-1234.sh
scriptje.sh
Hopefully this resolves your concern about plain text output. Let me know what you think.
User avatar
sander
Release Testers
Release Testers
Posts: 8823
Joined: January 22nd, 2008, 2:22 pm

Re: sab_api Bash Script

Post by sander »

I didn't know xpath. Thanks for giving that info.

'//scripts/script/text()' does that mean: find <scripts>, then in there <script>, and then print all text found ... ?

and why the extra / at the beginning?
User avatar
abeam89
Newbie
Newbie
Posts: 10
Joined: October 18th, 2009, 2:39 am

Re: sab_api Bash Script

Post by abeam89 »

So the English definition of the query, I believe, would be the following:
"The text contained by all children of parent 'scripts' named 'script'"

The '//' portion is not necessarily required in these cases the way I defined the paths. Using a single '/' would indicate that the selection should start at the root node (an absolute path). Since both of the queries include an absolute path, they could be successful with a single '/' rather than '//'. One nice thing about '//' is that it allows you to provide a partial path. In other words, the output of:

Code: Select all

$ sab_api scripts | xpath -q -e '//script/text()'
would be the same as the output of:

Code: Select all

$ sab_api scripts | xpath -q -e '//scripts/script/text()'
as well as:

Code: Select all

$ sab_api scripts | xpath -q -e '/scripts/script/text()'
Hopefully that clears the usage of xpath up a bit. I'm not really an expert myself, but I've found it to be the most useful tool for XML in Bash.

These guys might do a bit better job outlining the syntax than I have:
http://www.w3schools.com/xpath/xpath_syntax.asp

Have a good one!
User avatar
abeam89
Newbie
Newbie
Posts: 10
Joined: October 18th, 2009, 2:39 am

Re: sab_api Bash Script

Post by abeam89 »

Here is the latest version of the README that you can also find on the project web page @ https://github.com/abeam89/sab_api:

Code: Select all

README

sab_api

This bash script performs SABnzbd API calls as specified in the SABnzbd API
documentation. All currently defined API functions are supported by this
script. The script also provides the functionality of returning a query
constructed explicitly by the user without the API key. This script can
also be used with included options to allow the user to construct a valid
API URL with/without accessing it. This could be useful to generate a URL to
use for a separate application. The script attempts to identify common
errors with input values when possible, but is not intended to ensure 
that all API accesses are without flaw. The user should make use of the
script's troubleshooting features if an API access is not working as expected.

I've included some useful things with the script. There is an installer script
that will do all of the dirty work to get you up and running with sab_api, as
well as a bash_completion script which makes the tool tremendously more useful
if you use it directly from the command line like I often do. If you use the
install script, it will link the files in your git directory to the locations
that I've deemed appropriate on your system. This ensures future updates are
smooth and easy for you, and allows easier overall maintenance of sab_api.

Based on a previous discussion regarding what features are most useful to
users, I thought I would provide some insight on how you can make use of the
output of this script. XML is easily parsed in Bash as a result of xpath.
Without it, XML parsing would not be fun, but it allows the process to be
relatively painless. Let's look at some examples.

Say you want to see the current color scheme of SABnzbd (useful, I know):
$ sab_api queue | xpath -q -e '/queue/color_scheme/text()'
  returns...
gold

That's nice, but what's even nicer are relative paths (keeping in mind this
could potentially lead to matches you didn't intend to make). The same result
from above can be obtained with the following query:
$ sab_api queue | xpath -q -e '//color_scheme/text()'
  returns...
gold

Because '//' means that you've provided a relative path. In other words, the
query states, "Print the text of any and all nodes named "color_scheme" within
the output." The single '/' simply indicates an absolute path. This is a nice
functionality that I find very useful. 

The trailing text() that you see in the query provides the user the ability
to print only the text of the node, without the tags. Let's see what happens
if we leave it off.
$ sab_api queue | xpath -q -e '//color_scheme'
  returns...
<color_scheme>gold</color_scheme>

Pretty sweet, right? I mean, I'm demonstrating likely the most useless
functionality of the API, but sab_api with xpath becomes a pretty powerful
tool as you might be able to tell. Anyway, hopefully that helps someone.

More details about the xpath syntax are available here:
http://www.w3schools.com/xpath/xpath_syntax.asp

Please note that there are no warranties of any kind, expressed or implied,
that are provided you as a result of using this script or any of the utilities
provided in this package. In other words, if you use this script and it destroys
your SABnzbd queue or history or does any other type of damage, it's not my
fault. This applies to any outcome of using this script (or its utilities) 
that results in an undesireable impact, regardless of the depth of that impact.
But I'm sure you were already aware of this. That being said, I did my best
to ensure something like that won't happen. However, again, if it does, it's
not my fault, responsibility, or liability in any way whatsoever. That is
the binding agreement you enter into by making any type of use of this
software.

Seriously, though, I hope someone besides me finds this at least slightly
useful. I developed this as a bash script solely because I felt it would be
the quickest thing for me to do. If there are enough requests I might
consider implementing this in something like Python, but I figure for most
this will be perfectly sufficient.


I'm also considering implementing what would effectively be a command-line
based interface to SABnzbd, but that would only be something I'd consider
if there was sufficient interest because I'm not sure I'd use it all that
much myself.

If you have any questions or concerns, feel free to leave some feedback here
to let me know what's up. If I've made any errors or left out and features, I'd
like to know what so I can get it fixed/added. Thanks for looking! Enjoy!
romprod
Newbie
Newbie
Posts: 6
Joined: March 22nd, 2008, 8:25 am

Re: sab_api Bash Script

Post by romprod »

Hi,

I've installed your script successfully but I receive the following error message when I try any of the commands. Can you help?

Code: Select all

root@raspberrypi:~# sab_api
-bash: /usr/bin/sab_api: Permission denied

Edit:
Doh, ignore that. I've just CHMOD 777 the sab-api file and it works.
Post Reply