ceap80
6/17/2012 - 9:54 AM

Transmission episode bump

Transmission episode bump

#!/usr/bin/env python
'''
Scans all seeding and idling torrents. If all enabled files in the torrent
is done, enables first disabled file in name's alphabethical order.
Optional argument is a maximum number of torrents bumped (default: 1).
'''
import re
import sys
from subprocess import Popen, PIPE
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()

try:
    max_bump = int(sys.argv[1])
except StandardError:
    max_bump = 1

output = Popen(['transmission-remote',
               '--list',
               ], stdout=PIPE).communicate()[0]

eol_re = re.compile(r'\r?\n')

torrent_lines = eol_re.split(output)

torrent_re = re.compile(r'^\s*(?P<ID>\d+)\*?' +
    '\s+(?P<Done>\d+%|n/a)' +
    '\s+(?P<Have>\d+\.\d+ \w+|None)' +
    '\s+(?P<ETA>\d+ \w+|\w+)' +
    '\s+(?P<Up>\d+\.\d+)' +
    '\s+(?P<Down>\d+\.\d+)' +
    '\s+(?P<Ratio>\d+\.\d+|None)' +
    '\s+(?P<Status>\w+)' +
    '\s+(?P<Name>.*)$')

torrents = []
for line in torrent_lines:
    mo = torrent_re.match(line)
    if not mo:
        logger.debug('Ignored torrent line %s' % line)
        continue
    torrent_dict = mo.groupdict()
    torrents.append(torrent_dict)

latent_bumps = [x for x in torrents if x['Status'] in ('Idle', 'Seeding')]
logger.debug(latent_bumps)

file_re = re.compile(r'^\s*(?P<ID>\d+):' +
        '\s+(?P<Done>\d+%|-nan%)' +
        '\s+(?P<Priority>\w+)' +
        '\s+(?P<Get>\w+)' +
        '\s+(?P<Size>[0-9.]+ \w+|None)' +
        '\s+(?P<Name>.*)$')

for torrent in latent_bumps:
    torrent_id = torrent['ID']

    output = Popen(['transmission-remote',
                   '--torrent',
                   torrent_id,
                   '--files'], stdout=PIPE).communicate()[0]

    file_lines = eol_re.split(output)
    files = []
    for line in file_lines:
        mo = file_re.match(line)
        if not mo:
            logger.debug('Ignored file line %s' % line)
            continue
        filedict = mo.groupdict()
        files.append(filedict)

    in_download = [x for x in files if x['Get'] == 'Yes']
    logger.debug(in_download)
    all_downloaded = all([x['Done'] == '100%' for x in in_download])
    logger.debug(all_downloaded)
    if all_downloaded:
        not_active = [x for x in files if x['Get'] == 'No']
        not_active.sort(cmp=lambda x, y: cmp(x['Name'], y['Name']))
        logger.debug(not_active)
        new_get = not_active[0]
        logger.debug(new_get)
        logger.info(new_get['Name'])
        Popen(['transmission-remote',
                '--torrent',
                torrent_id,
                '--get',
                new_get['ID'],
                ], stdout=PIPE).communicate()[0]
        max_bump -= 1
        if max_bump == 0:
            sys.exit()