#!/usr/bin/env python3 import os import sys import re import subprocess import shutil import json video_exts = [ '.mkv', '.mp4', '.avi' ] meta_exts = [ '.nfo', '.srt', # We can get these on our own. '.jpg', '.jpeg', '.png', '.bmp' ] def filebot_rename(src, destdir, action, name=None, format=None): if not os.path.isdir(destdir): os.makedirs(destdir) args = ['filebot', '-rename', src, '-non-strict', '--output', destdir, '--action', action, '--conflict', 'index'] if name is not None: args.append('--filter') args.append('n == \"' + name + '\"') if format is not None: args.append('--format') args.append(format) subprocess.run(args) def unrar(src, dest='extract'): if not os.path.isdir(dest): os.makedirs(dest) subprocess.run(['unrar', 'x', '-y', src, dest + '/']) return dest # Load the config. cfgpath = os.path.join(os.path.expanduser('~'), '.config', 'bootybot.conf') if 'BOOTYCFG' in os.environ: cfgpath = os.path.expanduser(os.environ['BOOTYCFG']) cfg = None with open(cfgpath) as data: cfg = json.load(data) # Load custom title names for TV shows. title_overrides = [] for t in cfg['overrides']: title_overrides.append({ 'name': t['name'], 'pat': re.compile(t['pattern']) }) raw_tv_regex = re.compile('.*\\.S[0-9][0-9](E[0-9][0-9])?\\..*') def gen_title_action(fpath, action): mname = None bn = os.path.basename(fpath) # Check to see if it's a TV show and if we can provide a specific title for it. if raw_tv_regex.match(bn) is not None: for to in title_overrides: if to['pat'].match(bn) is not None: mname = to['name'] print('found title ' + to['name'] + ' for ' + fpath) return { 'src': fpath, 'action': action, 'medianame': mname } def get_simple_rename_action(): if 'BOOTY_SIMPLE_RENAME_ACTION' in os.environ: return os.environ['BOOTY_SIMPLE_RENAME_ACTION'] else: return cfg['simpleaction'] # Now go over all of the input files and figure out what to do with them. sources = [] rarregex = re.compile('\\.r[0-9][0-9]') for f in os.listdir(os.getcwd()): if os.path.isdir(f): continue name, ext = os.path.splitext(f) if ext in video_exts: sources.append(gen_title_action(f, get_simple_rename_action())) elif ext == '.rar': # RARs are a little more complicated to handle. exd = os.path.expanduser(os.path.join(cfg['extractdir'], os.path.basename(f))) contents = unrar(f, dest=exd) for ff in os.listdir(contents): _, ext2 = os.path.splitext(ff) if ext2 in video_exts: sources.append(gen_title_action(os.path.join(contents, ff), 'move')) else: pass elif ext in meta_exts or rarregex.match(ext) is not None: pass else: print('warning: ignoring file because of extension: ' + f) # Create the output directory if it doesn't exist yet. outdir = cfg['outdir'] if not os.path.isdir(outdir): os.makedirs(outdir, mode=0o755) print('created destination directory ' + outdir) for e in sources: filebot_rename(e['src'], outdir, e['action'], name=e['medianame'], format='{plex}')