Skip to content

Instantly share code, notes, and snippets.

@keizie keizie/autounrar.py
Created Aug 10, 2013

Embed
What would you like to do?
#!/usr/bin/python
import os, re, logging
from glob import glob
from pipes import quote
SOURCES = ('/path/to/rars',)
LOGFILE = '/path/to/autounrar.log'
EXECUTE = 'unrar'
def get_basename(filename):
basename = os.path.splitext(filename)[0]
if basename.find('.part')>-1:
return os.path.splitext(basename)[0]
return basename
def is_multi(filename):
if filename.find('.part1.')>-1 or filename.find('.part01.')>-1 or filename.find('.part001.')>-1:
return 1 # True
elif os.path.exists(filename.replace('.rar','.r00')):
return 2 # True
return 0 # False
def is_complete(filename):
# TODO: check .sfv
basename = get_basename(filename)
if filename.find('.part1.')>-1:
pattern = re.compile(re.escape(basename)+'\.part[1-9]\.rar$')
elif filename.find('.part01.')>-1:
#pattern = re.compile(re.escape(basename)+'\.part(?!01)\d{2}\.rar$')
pattern = re.compile(re.escape(basename)+'\.part\d{2}\.rar$')
elif filename.find('.part001.')>-1:
#pattern = re.compile(re.escape(basename)+'\.part(?!001)\d{3}\.rar$')
pattern = re.compile(re.escape(basename)+'\.part\d{3}\.rar$')
else:
pattern = re.compile(re.escape(basename)+'.*\.[rs][0-9][0-9]$') # s00 comes next to r99.
multis = [f for f in os.listdir('.') if pattern.match(f)]
if len(multis) == 0:
return False
multis.sort()
lastfile = multis[-1] # largest number
if lastfile.find('.part')>-1:
numpos = os.path.splitext(lastfile)[0].rfind('.part')+5
length = int(lastfile[numpos:-4])
if filename.find('.exe')>-1:
length = length -1 # first file not in count
else:
length = int(lastfile[-2:])+1 # .rar file not in count but begins with 00
if lastfile[-3]=='s':
length = length + 100
is_full = (len(multis) == length)
is_diffsize = (os.path.getsize(filename) != os.path.getsize(lastfile))
logging.info('file: %s' % filename)
logging.info('full: %s' % is_full)
logging.info('diff: %s' % is_diffsize)
return (is_full & is_diffsize)
def do_postproc(basename, dest):
logging.info('postprocessing...')
pattern = re.compile(re.escape(basename)+'(.*\.r.+|.*\.exe)')
multis = [f for f in os.listdir('.') if pattern.match(f)]
for f in multis:
os.remove(f)
def do_unrar(filename):
basename = get_basename(filename)
dest = basename + os.sep
command = '%s x %s %s' % (EXECUTE, quote(filename), quote(dest))
logging.debug(command)
ret = os.system(command)
if ret == 0:
logging.info('succeed')
do_postproc(basename, dest)
else:
logging.warning('error: %s' % ret)
if __name__ == '__main__':
from tendo import singleton
me = singleton.SingleInstance()
logging.basicConfig(filename=LOGFILE, level=logging.DEBUG)
for src in SOURCES:
os.chdir(src)
first_archives = [f for f in glob('*.[re][ax][re]') if is_multi(f)]
for f in first_archives:
if is_complete(f):
do_unrar(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.