Author Topic: Python script to clear completed downloads  (Read 238 times)

jeremysherriff

  • Newbie
  • *
  • Posts: 3
  • Karma: +0/-0
    • View Profile
Python script to clear completed downloads
« on: June 15, 2019, 10:48:38 am »
Not strictly linux, but python is more common here I guess.

https://github.com/jeremysherriff/OpenFLIXR2.CustomScripts/blob/master/clear_qbt_complete.py
Complete script in first comment below in case repo gets moved/closed.

Code: [Select]
clear_qbt_complete.py [option]
  Clears "Completed" status torrents from qBitTorrent
  Connects to "localhost:8080" without credentials
  Logs output to /var/log/clear_qbt_complete.log
  By default logs nothing to stdout/stderr to allow use in cron

  Options:
    -v --verbose : to enable console logging in addition to logfile
    -t --test    : for test mode (no delete) - implies -v

Edit: This script trigger the "also delete files on the hard disk" option, in case that was not clear.
That's what makes this different from simply setting the action on reaching seeding limit to "remove".
« Last Edit: June 15, 2019, 11:26:10 am by jeremysherriff »

jeremysherriff

  • Newbie
  • *
  • Posts: 3
  • Karma: +0/-0
    • View Profile
Re: Python script to clear completed downloads
« Reply #1 on: June 15, 2019, 10:50:10 am »
Full code as promised:
Code: [Select]
#!/usr/bin/python
import sys
import json
import requests
import logging
import argparse

# Set up logging - kinda important when deleting stuff!
logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s")
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler("/var/log/clear_qbt_complete.log")
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.INFO)
debugmode = 0
if len(sys.argv) > 1 and ( str(sys.argv[1]) == '-v' or str(sys.argv[1]) == '--verbose' ):
    consoleHandler = logging.StreamHandler(sys.stdout)
    consoleHandler.setFormatter(logFormatter)
    rootLogger.addHandler(consoleHandler)
    rootLogger.setLevel(logging.DEBUG)
    debugmode = 1

testmode = 0
if len(sys.argv) > 1 and ( str(sys.argv[1]) == '-t' or str(sys.argv[1]) == '--test' ):
    consoleHandler = logging.StreamHandler(sys.stdout)
    consoleHandler.setFormatter(logFormatter)
    rootLogger.addHandler(consoleHandler)
    rootLogger.setLevel(logging.DEBUG)
    debugmode = 1
    testmode = 1

if len(sys.argv) > 1 and ( str(sys.argv[1]) == '-?' or str(sys.argv[1]) == '--help' ):
    print('clear_qbt_complete.py [option]')
    print('  Clears "Completed" status torrents from qBitTorrent')
    print('  Connects to "localhost:8080" without credentials')
    print('  Logs output to /var/log/clear_qbt_complete.log')
    print('  By default logs nothing to stdout/stderr to allow use in cron')
    print('')
    print('  Options:')
    print('    -v --verbose : to enable console logging in addition to logfile')
    print('    -t --test    : for test mode (no delete) - implies -v')
    print('')
    exit(0)

if len(sys.argv) > 1 and ( debugmode == 0 ):
    print('clear_qbt_complete.py: Invalid option "'+str(sys.argv[1])+'"')
    exit(1)

if len(sys.argv) > 2:
    print('clear_qbt_complete.py: Invalid option "'+str(sys.argv[2])+'"')
    exit(1)

# qBitTorrent server details, in URL format:
baseurl = 'http://localhost:8080'

# OK lets do stuff
exitcode = 0
url = '/query/torrents?filter=completed'
try:
    response = requests.get(baseurl+url)
    response.raise_for_status()
    data = response.json()
    # Observed status for torrents in 'completed' filter:
    #  uploading - seeding
    #  stalledUP - seeding but stalled
    # >pausedUP  - seeding and manually paused
    #            - seeding and ratio reached but seeding time still to go

    if len(data) == 0:
        logging.debug('No completed torrents to clear')
        if debugmode == 1:
            print('')
        exit(0)
    for tor in data:
        if tor['state'] != 'pausedUP':
            logging.debug('Skipping '+tor['state']+' torrent: '+tor['name'])
            continue
        logging.info('Clearing '+tor['state']+' torrent: '+tor['name'])
        payload = {'hashes': tor['hash']}
        url = '/command/deletePerm'
        if testmode == 0:
            try:
                response = requests.post(baseurl+url,data=payload)
                response.raise_for_status()
                logging.debug('POST data: '+str(payload))
            except requests.exceptions.RequestException as err:
                logging.error(str(err))
                exitcode = 1
    logging.debug('Exiting normally with code '+str(exitcode))
    if debugmode == 1:
        print('')
    exit(exitcode)
except requests.exceptions.RequestException as err:
    logging.error(str(err))
    if debugmode == 1:
        print('')
    exit(1)

Edit: Code clean-up for console output
« Last Edit: June 15, 2019, 11:55:53 am by jeremysherriff »