Skip to content

Instantly share code, notes, and snippets.

@epohs
Last active April 9, 2018 16:46
Show Gist options
  • Save epohs/b6bf8537e17aa7a9198851fc4719c2e0 to your computer and use it in GitHub Desktop.
Save epohs/b6bf8537e17aa7a9198851fc4719c2e0 to your computer and use it in GitHub Desktop.
Add a torrent and a label via one command line script
#!/usr/bin/env python
# USAGE:
#
# ./add-torrent.py -t "https://downloads.raspberrypi.org/raspbian_lite_latest.torrent" -l "app"
# ./add-torrent.py -t "magnet:?xt=urn:btih:3b17032b53cf45fbf6861a7d32f9af5dcae2709b&dn=ipMagnet+Tracking+Link&tr=http%3A%2F%2Fipmagnet.services.cbcdn.com%3A80%2F" -l "app"
import os
import logging
from optparse import OptionParser
from twisted.internet import reactor
from twisted.internet import defer
# Import the Deluge client module
from deluge.ui.client import client
from deluge.common import is_url, is_magnet
import deluge.component as component
from deluge.log import LOG as log
from deluge.log import setupLogger as setup_logger
setup_logger('debug') # 'info'|'warn'|'warning'|'error'|'none'|'debug'|'trace'|'garbage'
parser = OptionParser()
parser.add_option("-t", "--torrent", dest="torrent", help="URL|magnet of torrent", metavar="URL")
parser.add_option("-l", "--label", dest="label", help="Label to apply to download", default=False)
(options, args) = parser.parse_args()
torrent_url = options.torrent
torrent_label = options.label
# Connect to a Deluge daemon running on the localhost
# We get a Deferred object from this method and
# we use this to know if and when
# the connection succeeded or failed.
d = client.connect()
# Set this to true to always attempt to add
# a label even if the plugin may not be enabled.
is_label_plugin_active = True
# Called upon a successful connection to Deluge
def on_connect_success(result):
if (torrent_url):
add_torrent(torrent_url)
# Called when an error is encountered
# trying to connect to local Deluge client
def on_connect_fail(result):
log.error("Connection failed. (%s)" % result)
cleanup_on_done()
def on_get_available_plugins(plugins):
log.info("Available plugins: %s" % plugins)
def on_get_enabled_plugins(plugins):
log.info("I'm in the on_get_enabled_plugins function.")
if 'Label' in plugins:
log.info('Label plugin active.')
is_label_plugin_active = True
else:
log.error('Label plugin not installed.')
def on_get_plugins_fail(result):
log.warn("Getting enabled plugins failed.")
# Called when a new torrent was successfully
# added to the queue.
def on_torrent_added(new_torrent_id):
if ( new_torrent_id ):
log.info("Torrent added via add-torrent.py - ID: %s" % (new_torrent_id))
else:
log.warn("Torrent URL was not added. Maybe it already existed?")
if (torrent_label):
log.info("Torrent label was passed to this script.")
try:
log.info("Trying get_enabled_plugins()")
client.core.get_enabled_plugins().addCallback(on_get_enabled_plugins).addErrback(on_get_plugins_fail)
except Exception as ex:
log.warn('(%s) failed.' % ex)
if ( is_label_plugin_active ):
add_label(torrent_label, new_torrent_id)
else:
log.error("Label plugin not installed.")
else:
log.error("No label passed.")
cleanup_on_done()
# Called when we tried to add a new torrent
# but it failed.
def on_add_torrent_fail(torrent_url):
log.error("Torrent Failed: %s" % (torrent_url))
cleanup_on_done()
def on_add_label_fail(ex):
log.error('Unable to set label: %s', ex)
# Try to add a new torrent based off of either
# an HTTP URL or a Magnet URL.
def add_torrent(torrent_url):
options = {}
if is_url(torrent_url):
d = client.core.add_torrent_url(torrent_url)
elif is_magnet(torrent_url):
d = client.core.add_torrent_magnet(torrent_url)
else:
log.error("I don't know what this is: %s" % (torrent_url))
d.addCallback(on_torrent_added)
d.addErrback(on_add_torrent_fail)
return d
# Add a label to a torrent
def add_label(torrent_label, torrent_id):
log.info("I'm in the add label function.")
try:
log.info("Adding label (%s) to torrent (%s)" % (torrent_label, torrent_id))
client.label.set_torrent(torrent_id, torrent_label)
log.info("Label (%s) added." % torrent_label)
except Exception as ex:
log.warn('Adding label (%s) failed.' % torrent_label)
on_add_label_fail(ex)
# Single function to handle closing our Deluge
# connection and wrapping up twisted session.
def cleanup_on_done():
client.disconnect()
reactor.stop()
log.info('Exiting script.')
setup_logger('none')
# We add the callback to the Deferred
# object we got from connect()
d.addCallback(on_connect_success)
# We add the callback (in this case it's an errback, for error)
d.addErrback(on_connect_fail)
# Run the twisted main loop to make everything go
reactor.run()
#!/usr/bin/env python
# Import the client module
from deluge.ui.client import client
# Import the reactor module from Twisted - this is for our mainloop
from twisted.internet import reactor, defer
# Set up the logger to print out errors
from deluge.log import setupLogger
setupLogger('debug')
# Connect to a daemon running on the localhost
# We get a Deferred object from this method and we use this to know if and when
# the connection succeeded or failed.
d = client.connect()
# We create a callback function to be called upon a successful connection
def on_connect_success(result):
print "Connection was successful!"
print "result:", result
# Disconnect from the daemon once we successfully connect
client.disconnect()
# Stop the twisted main loop and exit
reactor.stop()
# We add the callback to the Deferred object we got from connect()
d.addCallback(on_connect_success)
# We create another callback function to be called when an error is encountered
def on_connect_fail(result):
print "Connection failed!"
print "result:", result
def on_get_labels(d_labels):
"""Gets available labels from deluge, and adds any new labels we need."""
for label in d_labels:
print label
client.label.get_labels().addCallback(on_get_labels)
# We add the callback (in this case it's an errback, for error)
d.addErrback(on_connect_fail)
# Run the twisted main loop to make everything go
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment