Python API help

General support for problems installing or using Deluge
Post Reply
slvrdragn
Member
Member
Posts: 36
Joined: Tue Dec 12, 2017 4:50 pm

Python API help

Post by slvrdragn »

Hey There,
I'm a recent convert over from uTorrent where I had some pretty extensive automation using APIs. Looking for anything with experience using python with deluge, as my googleFu is failing me and I'm not finding any good examples of how to accomplish what I need.

Some of the things:
1. remove torrents when label + size exceeds a limit
2. remove torrents when label + blacklist regex matches
3. reassign torrent to label based on regex match
4. set priority of torrent based on label "comics to the bottom, tv to the top"
5. if torrent has no label, set to paused.

I have dynamic text files that are used as source for keywords, one phrase per line, one file per label that are converted in python to regex :)

Any guidance or example code of how to fetch the list of torrents, check the above conditions and then send back an action (pause, relabel, remove w/ data) would be very appreciated.

Thanks.
slvrdragn
Member
Member
Posts: 36
Joined: Tue Dec 12, 2017 4:50 pm

Re: Python API help

Post by slvrdragn »

I should probably mention.
Python 2.7
OpenSuse 42.3
Deluge 2.0b2
slvrdragn
Member
Member
Posts: 36
Joined: Tue Dec 12, 2017 4:50 pm

Re: Python API help

Post by slvrdragn »

If i do the below code, when it passes " printSuccess(None, False, "--Torrent: %s" % (status)) " it then gives me "Unhandled error in Deferred:
" and I'm not sure why. If i comment out all the IF after that, it dumps the list as expected.

Code: Select all

#!/usr/bin/python

from deluge.log import LOG as log
from deluge.ui.client import client
import deluge.component as component
from twisted.internet import reactor, defer
import time
import sys
import requests
import json
from pprint import pprint
import humanfriendly
import re
import os

reload(sys)
sys.setdefaultencoding('utf8')

print "Loading Blacklist..."
# Open the file for reading.
with open('/opt/blacklist.names', 'r') as blackfile:
    blackwords = blackfile.read()  # Read the contents of the file into memory.
# Return a list of the lines, breaking at line boundaries.
blacklist = blackwords.splitlines()

print "Loading STUFF..."
# Open the file for reading.
with open('/opt/list.stuff', 'r') as stufffile:
    stuffwords = stufffile.read()  # Read the contents of the file into memory.
# Return a list of the lines, breaking at line boundaries.
stufflist = stuffwords.splitlines()


year, month, day, hour, minute = time.strftime("%Y,%m,%d,%H,%M").split(',')

cliconnect = client.connect()
is_interactive = True # Set this to True to allow direct output or set to False for cron

cats = ['anime','tv','books','comics','pron','stuff','apps','movies','music']
pcats = ['stuff','pron']

regex = r"([Ss][0-9].*[Ee][0-9]([Ee])?([0-9])?(\-([Ee])?[0-9][0-9])?)"
regex2 = r"([0-9])?[0-9]x[0-9]([0-9])?([0-9])?"
regex3 = r"([0-9]-([Ee])?[0-9]([0-9])?)"


status_keys = [#"state",
        #"save_path",
        #"tracker",
        #"tracker_status",
        #"next_announce",
        'name',
        "total_size",
        #"progress",
        #"num_seeds",
        #"total_seeds",
        #"num_peers",
        #"total_peers",
        #"eta",
        #"download_payload_rate",
        #upload_payload_rate",
        #"ratio",
        #"distributed_copies",
        #"num_pieces",
        #"piece_length",
        #"total_done",
        #"files",
        #"file_priorities",
        #file_progress",
        #"peers",
        #"is_seed",
        "is_finished",
        #"active_time",
        #seeding_time",
        "label_id",
        "label",
        "labels"
        ]

count = 0
torrent_ids = []

def printSuccess(dresult, is_success, smsg):
    global is_interactive
    if is_interactive:
        if is_success:
            print "[+]", smsg
        else:
            print "[i]", smsg

def printError(emsg):
    global is_interactive
    if is_interactive:
        print "[e]", emsg

def endSession(esresult):
    if esresult:
        print esresult
        reactor.stop()
    else:
        client.disconnect()
        printSuccess(None, False, "Client disconnected.")
        reactor.stop()

def printReport(rresult):
    printSuccess(None, True, "TOTAL TORRENTS: %i" % (count))
    endSession(None)

def on_torrents_status(torrents):
    global filtertime
    tlist=[]
    for torrent_id, status in torrents.items():
        printSuccess(None, False, "Current torrent id is: %s" % (torrent_id))
        printSuccess(None, False, "--Torrent: %s" % (status)) 
        if status['label'] == 'tv' :
            if status["total_size"] > 654288000  and re.search(regex,  status['name']) is not None or re.search(regex2,  status['name']) is not None and re.search(r"gilmore.*girls",  status['name']) is None and re.search(regex3,  status['name']) is  None:
                tlist.append(client.core.remove_torrent(torrent_id, True).addCallbacks(printSuccess))
                continue
                #print 'TV'
            if '1080p' in  status['name'] or '2160p' in  status['name'] or '4320p' in  status['name'] :
                #print "TOO HIGH"
                tlist.append(client.core.remove_torrent(torrent_id, True).addCallbacks(printSuccess))
                continue
                
        elif status['label'] == 'movies' :
            if  status['total_size'] > 2100000000:
                #print "MOVIES"
                tlist.append(client.core.remove_torrent(torrent_id, True).addCallbacks(printSuccess))
                continue
        elif status['label'] in pcats:
            for eachline3 in stufflist:
                eachline3 = re.sub('[^0-9a-zA-Z]+', ' ', eachline3)
                eachline3 = re.sub('\s+', ' ', eachline3)
                eachlineb = re.compile(eachline3.replace(' ','.*').lower())
                if re.search(eachlineb, status['name']) is not None:
                    #print "Stuff hit" + eachline3 + " " + status['name'] 
                    #print eachline3
                    stufftrack=1
                    break

            if stufftrack == 0:
                for eachline2 in blacklist:
                  if eachline2 is not None:
                      eachline2u = unicode(eachline2, 'utf8')
                      eachline2u = re.sub('[^0-9a-zA-Z]+', ' ', eachline2u)
                      eachline2u = re.sub('\s+', ' ', eachline2u)
                      eachlinec = re.compile(eachline2u.replace(' ','.*').lower())
                      #print blacklist
                      if re.search(eachlinec,  status['name']) is not None :  #and  k['cat'] == 'pron'
                            #print "Blacklist: ","Keyword: ", eachline2, status['name']
                            tlist.append(client.core.remove_torrent(torrent_id, True).addCallbacks(printSuccess))
         
        #printSuccess(None, False, "--Torrent name is: %s" % (status['name']))
        #printSuccess(None, False, "--Torrent size is: %s" % (status["total_size"]))
        #printSuccess(None, False, "--Torrent size is: %s" % (status["total_size"]))
        #printSuccess(None, False, "--Torrent state is: %s" % (status["state"]))
        #printSuccess(None, False, "--Torrent ratio is: %s" % (status["ratio"]))
        #printSuccess(None, False, "--Torrent DL rate is: %s" % (status["download_payload_rate"]))
        #rintSuccess(None, False, "--Torrent UL rate is: %s" % (status["upload_payload_rate"]))
        #rintSuccess(None, False, "--Torrent tracker is: %s" % (status["tracker_status"]))
#        break
        global count
        count += 1
    defer.DeferredList(tlist).addCallback(printReport)

def on_session_state(result):
    client.core.get_torrents_status({"id": result}, status_keys).addCallback(on_torrents_status)

def delete_torrent(result):
    client.core.remove_torrent(result, True ).addCallback(on_torrents_status)

def on_connect_success(result):
    printSuccess(None, True, "Connection was successful!")
    curtime = time.time()
    printSuccess(None, False, "Current unix time is %i" % (curtime))
    client.core.get_session_state().addCallback(on_session_state)

cliconnect.addCallbacks(on_connect_success, endSession, errbackArgs=("Connection failed: check settings and try again."))

reactor.run()

Post Reply