#!/usr/bin/python # Joe Gillotti - 3/28/2014 import os import re import glob import sys import subprocess torrents = '/srv/media/torrents' rar = '/usr/bin/rar' extensions = ('mkv', 'mp4', 'mpg', 'avi', 'm4v', 'wmv') dryRun = '--dry' in sys.argv if not os.path.exists(rar): print 'Rar not found' sys.exit(1) toExtract = [] for root, dirs, files in os.walk(torrents): for fn in files: if fn.split('.')[-1] != 'rar': continue path = os.path.join(root, fn) base = fn[:-4] if not os.path.exists(os.path.join(root, base+'.r01')): continue try: proc = subprocess.Popen([rar, 'l', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out = proc.communicate() except OSError as e: print 'Failed listing rar contents for {0}: {1}'.format(fn, e) continue # Likely needlessly complex but whatever. Also don't care about files # with spaces in their names listParsing = False destFile = None for line in out[0].split('\n'): line = line.strip() if line == '-'*79: if listParsing: break listParsing = True if listParsing: name = line.split(' ')[0] if name.split('.')[-1] in extensions: destFile = name break if destFile is None: continue result = os.path.join(root, name) if not os.path.exists(result): toExtract.append(os.path.join(root, fn)) # Extracting after the fact as os.chdir'ing inside os.walk breaks things for path in toExtract: folder = os.path.dirname(path) base = os.path.basename(path) print 'Extracting {0}...'.format(base) if dryRun: continue try: os.chdir(folder) except OSError as e: print 'Failed cding into {0}: {1}'.format(folder, e) try: subprocess.Popen([rar, 'x', base]).wait() except OSError as e: print 'Failed extracting {0}: {1}'.format(base, e)