def callscript(self, message=None, group=None): log.info('MP4 Automator Post Processing script initialized version 2') sys.path.append(path) try: from readSettings import ReadSettings from mkvtomp4 import MkvtoMp4 from tmdb_mp4 import tmdb_mp4 from autoprocess import plex except ImportError: log.error('Path to script folder appears to be invalid.') return False settings = ReadSettings(path, "autoProcess.ini") converter = MkvtoMp4(settings) try: imdbid = group['library']['identifier'] except: imdbid = group['identifier'] moviefile = group['renamed_files'] original = group['files']['movie'][0] success = False for inputfile in moviefile: try: log.info('Processing file: %s', inputfile) if MkvtoMp4(settings).validSource(inputfile): log.info('File is valid') output = converter.process(inputfile, original=original) # Tag with metadata if settings.tagfile: log.info('Tagging file with IMDB ID %s', imdbid) tagmp4 = tmdb_mp4(imdbid, original=original, language=settings.taglanguage) tagmp4.setHD(output['x'], output['y']) tagmp4.writeTags(output['output'], settings.artwork) #QTFS if settings.relocate_moov: converter.QTFS(output['output']) # Copy to additional locations converter.replicate(output['output']) success = True else: log.info('File is invalid') except: log.error('File processing failed: %s', (traceback.format_exc())) plex.refreshPlex(settings, 'movie') return success
def process(dirName, nzbName=None, status=0): status = int(status) settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini") host = settings.CP['host'] port = settings.CP['port'] username = settings.CP['username'] password = settings.CP['password'] apikey = settings.CP['apikey'] delay = settings.CP['delay'] method = settings.CP['method'] delete_failed = settings.CP['delete_failed'] protocol = settings.CP['protocol'] web_root = settings.CP['web_root'] myOpener = AuthURLOpener(username, password) nzbName1 = str(nzbName) # Don't delay when we are calling this script manually. if nzbName == "Manual Run": delay = 0 if status == 0: if method == "manage": command = "manage.update" else: command = "renamer.scan" url = protocol + host + ":" + port + web_root + "/api/" + apikey + "/" + command print "waiting for", str( delay), "seconds to allow CPS to process newly extracted files" time.sleep(delay) print "Opening URL:", url try: urlObj = myOpener.openit(url) except IOError, e: print "Unable to open URL: ", str(e) sys.exit(1) result = json.load(urlObj) print "CouchPotatoServer returned", result if result['success']: print command, "started on CouchPotatoServer for", nzbName1 else: print "Error", command, "has NOT started on CouchPotatoServer for", nzbName1
import sys import os import guessit import locale import glob import argparse from readSettings import ReadSettings from tvdb_mp4 import Tvdb_mp4 from tmdb_mp4 import tmdb_mp4 from mkvtomp4 import MkvtoMp4 from tvdb_api import tvdb_api from tmdb_api import tmdb from extensions import tmdb_api_key settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini") def mediatype(): print "Select media type:" print "1. Movie (via IMDB ID)" print "2. Movie (via TMDB ID)" print "3. TV" print "4. Convert without tagging" print "5. Skip file" result = raw_input("#: ") if 0 < int(result) < 6: return int(result) else: print "Invalid selection" return mediatype()
def main(): global settings parser = argparse.ArgumentParser( description= "Manual conversion and tagging script for sickbeard_mp4_automator") parser.add_argument( '-i', '--input', help='The source that will be converted. May be a file or a directory') parser.add_argument( '-c', '--config', help='Specify an alternate configuration file location') parser.add_argument( '-a', '--auto', action="store_true", help= "Enable auto mode, the script will not prompt you for any further input, good for batch files. It will guess the metadata using guessit" ) parser.add_argument('-tv', '--tvdbid', help="Set the TVDB ID for a tv show") parser.add_argument('-s', '--season', help="Specifiy the season number") parser.add_argument('-e', '--episode', help="Specify the episode number") parser.add_argument('-imdb', '--imdbid', help="Specify the IMDB ID for a movie") parser.add_argument('-tmdb', '--tmdbid', help="Specify theMovieDB ID for a movie") parser.add_argument( '-nm', '--nomove', action='store_true', help= "Overrides and disables the custom moving of file options that come from output_dir and move-to" ) parser.add_argument( '-nc', '--nocopy', action='store_true', help= "Overrides and disables the custom copying of file options that come from output_dir and move-to" ) parser.add_argument( '-nd', '--nodelete', action='store_true', help="Overrides and disables deleting of original files") parser.add_argument( '-nt', '--notag', action="store_true", help="Overrides and disables tagging when using the automated option") parser.add_argument( '-np', '--nopost', action="store_true", help= "Overrides and disables the execution of additional post processing scripts" ) parser.add_argument( '-pr', '--preserveRelative', action='store_true', help= "Preserves relative directories when processing multiple files using the copy-to or move-to functionality" ) parser.add_argument( '-cmp4', '--convertmp4', action='store_true', help= "Overrides convert-mp4 setting in autoProcess.ini enabling the reprocessing of mp4 files" ) parser.add_argument( '-m', '--moveto', help= "Override move-to value setting in autoProcess.ini changing the final destination of the file" ) args = vars(parser.parse_args()) # Setup the silent mode silent = args['auto'] tag = True print("%sbit Python." % (struct.calcsize("P") * 8)) # Settings overrides if (args['config']): if os.path.exists(args['config']): print('Using configuration file "%s"' % (args['config'])) settings = ReadSettings(os.path.split(args['config'])[0], os.path.split(args['config'])[1], logger=log) elif os.path.exists( os.path.join(os.path.dirname(sys.argv[0]), args['config'])): print('Using configuration file "%s"' % (args['config'])) settings = ReadSettings(os.path.dirname(sys.argv[0]), args['config'], logger=log) else: print( 'Configuration file "%s" not present, using default autoProcess.ini' % (args['config'])) if (args['nomove']): settings.output_dir = None settings.moveto = None print("No-move enabled") elif (args['moveto']): settings.moveto = args['moveto'] print("Overriden move-to to " + args['moveto']) if (args['nocopy']): settings.copyto = None print("No-copy enabled") if (args['nodelete']): settings.delete = False print("No-delete enabled") if (args['convertmp4']): settings.processMP4 = True print("Reprocessing of MP4 files enabled") if (args['notag']): settings.tagfile = False print("No-tagging enabled") if (args['nopost']): settings.postprocess = False print("No post processing enabled") # Establish the path we will be working with if (args['input']): path = (str(args['input'])) try: path = glob.glob(path)[0] except: pass else: path = getValue("Enter path to file") tvdbid = int(args['tvdbid']) if args['tvdbid'] else None if os.path.isdir(path): walkDir(path, silent, tvdbid=tvdbid, preserveRelative=args['preserveRelative'], tag=settings.tagfile) elif (os.path.isfile(path) and MkvtoMp4(settings, logger=log).validSource(path)): if (not settings.tagfile): tagdata = None elif (args['tvdbid'] and not (args['imdbid'] or args['tmdbid'])): season = int(args['season']) if args['season'] else None episode = int(args['episode']) if args['episode'] else None if (tvdbid and season and episode): tagdata = [3, tvdbid, season, episode] else: tagdata = getinfo(path, silent=silent, tvdbid=tvdbid) elif ((args['imdbid'] or args['tmdbid']) and not args['tvdbid']): if (args['imdbid']): imdbid = args['imdbid'] tagdata = [1, imdbid] elif (args['tmdbid']): tmdbid = int(args['tmdbid']) tagdata = [2, tmdbid] else: tagdata = getinfo(path, silent=silent, tvdbid=tvdbid) processFile(path, tagdata) else: try: print("File %s is not in the correct format" % (path)) except: print("File is not in the correct format")
if category.lower() not in categories: log.error( "Post-Process: No valid category detected. Category was %s." % (category)) status = 1 sys.exit(POSTPROCESS_NONE) # Make sure there are no duplicate categories if len(categories) != len(set(categories)): log.error( "Duplicate category detected. Category names must be unique.") status = 1 sys.exit(POSTPROCESS_NONE) # All checks done, now launching the script. settings = ReadSettings(MP4folder, "autoProcess.ini") successful_process = False if shouldConvert: if output_dir: settings.output_dir = output_dir converter = MkvtoMp4(settings, logger=log) biggest_file_size = 0 biggest_file_name = "" m2ts_file = False for r, d, f in os.walk(path): for file in f: filepath = os.path.join(r, file) if filepath.endswith( '.m2ts' ): #m2ts files just screw up everything, but typically the largest file is the file that we want to convert.
sys.exit() # SABnzbd argv: # 1 The final directory of the job (full path) # 2 The original name of the NZB file # 3 Clean version of the job name (no path info and ".nzb" removed) # 4 Indexer's report number (if supported) # 5 User-defined category # 6 Group that the NZB was posted in e.g. alt.binaries.x # 7 Status of post processing. 0 = OK, 1=failed verification, 2=failed unpack, 3=1+2 # Chcanged by me, use custom ini based on category ini_file = "autoProcess-{}.ini".format(str(sys.argv[5]).lower()) log.info(ini_file) settings = ReadSettings( os.path.dirname(sys.argv[0]), ini_file, ) categories = [ settings.SAB['sb'], settings.SAB['cp'], settings.SAB['sonarr'], settings.SAB['radarr'], settings.SAB['sr'], settings.SAB['bypass'] ] category = str(sys.argv[5]).lower() path = str(sys.argv[1]) nzb = str(sys.argv[2]) log.debug("Path: %s." % path) log.debug("Category: %s." % category) log.debug("Categories: %s." % categories) log.debug("NZB: %s." % nzb)
str(response.status_code) + ".") return False if len(sys.argv) < 6: log.error( "Not enough command line parameters present, are you launching this from uTorrent?" ) log.error( "#Args: %L %T %D %K %F %I %N Label, Tracker, Directory, single|multi, NameofFile(if single), InfoHash, Name" ) log.error("Length was %s" % str(len(sys.argv))) log.error(str(sys.argv[1:])) sys.exit() settings = ReadSettings() path = str(sys.argv[3]) label = sys.argv[1].lower().strip() kind = sys.argv[4].lower().strip() filename = sys.argv[5].strip() categories = [ settings.uTorrent['cp'], settings.uTorrent['sb'], settings.uTorrent['sonarr'], settings.uTorrent['radarr'], settings.uTorrent['sr'], settings.uTorrent['bypass'] ] torrent_hash = sys.argv[6] try: name = sys.argv[7] except: name = sys.argv[6]
def main(): global settings parser = argparse.ArgumentParser( description= "Manual conversion and tagging script for sickbeard_mp4_automator") parser.add_argument( '-i', '--input', help='The source that will be converted. May be a file or a directory') parser.add_argument( '-c', '--config', help='Specify an alternate configuration file location') parser.add_argument( '-a', '--auto', action="store_true", help= "Enable auto mode, the script will not prompt you for any further input, good for batch files. It will guess the metadata using guessit" ) parser.add_argument('-s', '--season', help="Specifiy the season number") parser.add_argument('-e', '--episode', help="Specify the episode number") parser.add_argument('-tvdb', '--tvdbid', help="Specify the TVDB ID for media") parser.add_argument('-imdb', '--imdbid', help="Specify the IMDB ID for media") parser.add_argument('-tmdb', '--tmdbid', help="Specify the TMDB ID for media") parser.add_argument( '-nm', '--nomove', action='store_true', help= "Overrides and disables the custom moving of file options that come from output_dir and move-to" ) parser.add_argument( '-nc', '--nocopy', action='store_true', help= "Overrides and disables the custom copying of file options that come from output_dir and move-to" ) parser.add_argument( '-nd', '--nodelete', action='store_true', help="Overrides and disables deleting of original files") parser.add_argument( '-nt', '--notag', action="store_true", help="Overrides and disables tagging when using the automated option") parser.add_argument( '-np', '--nopost', action="store_true", help= "Overrides and disables the execution of additional post processing scripts" ) parser.add_argument( '-pr', '--preserveRelative', action='store_true', help= "Preserves relative directories when processing multiple files using the copy-to or move-to functionality" ) parser.add_argument( '-cmp4', '--convertmp4', action='store_true', help= "Overrides convert-mp4 setting in autoProcess.ini enabling the reprocessing of mp4 files" ) parser.add_argument( '-fc', '--forceconvert', action='store_true', help= "Overrides force-convert setting in autoProcess.ini and also enables convert-mp4 if true forcing the conversion of mp4 files" ) parser.add_argument( '-m', '--moveto', help= "Override move-to value setting in autoProcess.ini changing the final destination of the file" ) parser.add_argument( '-oo', '--optionsonly', action="store_true", help= "Display generated conversion options only, do not perform conversion") args = vars(parser.parse_args()) # Setup the silent mode silent = args['auto'] print("Python %s-bit %s." % (struct.calcsize("P") * 8, sys.version)) print("Guessit version: %s." % guessit.__version__) # Settings overrides if (args['config']): if os.path.exists(args['config']): settings = ReadSettings(args['config'], logger=log) elif os.path.exists( os.path.join(os.path.dirname(sys.argv[0]), args['config'])): settings = ReadSettings(os.path.join(os.path.dirname(sys.argv[0]), args['config']), logger=log) else: settings = ReadSettings(logger=log) if (args['nomove']): settings.output_dir = None settings.moveto = None print("No-move enabled") elif (args['moveto']): settings.moveto = args['moveto'] print("Overriden move-to to " + args['moveto']) if (args['nocopy']): settings.copyto = None print("No-copy enabled") if (args['nodelete']): settings.delete = False print("No-delete enabled") if (args['convertmp4']): settings.processMP4 = True print("Reprocessing of MP4 files enabled") if (args['forceconvert']): settings.forceConvert = True settings.processMP4 = True print( "Force conversion of mp4 files enabled. As a result conversion of mp4 files is also enabled" ) if (args['notag']): settings.tagfile = False print("No-tagging enabled") if (args['nopost']): settings.postprocess = False print("No post processing enabled") if (args['optionsonly']): logging.getLogger("mkvtomp4").setLevel(logging.CRITICAL) print("Options only mode enabled") # Establish the path we will be working with if (args['input']): path = (str(args['input'])) try: path = glob.glob(path)[0] except: pass else: path = getValue("Enter path to file") if os.path.isdir(path): walkDir(path, silent=silent, tmdbid=args.get('tmdbid'), tvdbid=args.get('tvdbid'), imdbid=args.get('imdbid'), preserveRelative=args['preserveRelative'], tag=settings.tagfile, optionsOnly=args['optionsonly']) elif (os.path.isfile(path)): converter = MkvtoMp4(settings, logger=log) info = converter.isValidSource(path) if info: if (args['optionsonly']): displayOptions(path) return if not settings.tagfile: processFile(path, None, converter, info=info) else: try: tagdata = getInfo(path, silent=silent, tmdbid=args.get('tmdbid'), tvdbid=args.get('tvdbid'), imdbid=args.get('imdbid'), season=args.get('season'), episode=args.get('episode')) processFile(path, tagdata, converter, info=info) except SkipFileException: log.debug("Skipping file %s" % path) else: print("File %s is not in a valid format" % (path)) else: print("File %s does not exist" % (path))
elif not os.path.isdir(logpath): try: os.mkdir(logpath) except Exception: logpath = os.path.dirname(__file__) configPath = os.path.abspath( os.path.join(os.path.dirname(__file__), "logging.ini")).replace("\\", "\\\\") logPath = os.path.abspath(os.path.join(logpath, "index.log")).replace("\\", "\\\\") fileConfig(configPath, defaults={"logfilename": logPath}) log = logging.getLogger("delugePostProcess") log.info("Deluge post processing started.") settings = ReadSettings(os.path.dirname(__file__), "autoProcess.ini") categories = [ settings.deluge["sb"], settings.deluge["cp"], settings.deluge["sonarr"], settings.deluge["radarr"], settings.deluge["sr"], settings.deluge["bypass"], ] remove = settings.deluge["remove"] if len(sys.argv) < 4: log.error( "Not enough command line parameters present, are you launching this from deluge?" ) sys.exit()
def main_functions(stop_event): try: global settings settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini", logger=log) signal.signal(signal.SIGINT, signal.SIG_IGN) parser = argparse.ArgumentParser(description="Manual conversion and tagging script for sickbeard_mp4_automator") parser.add_argument('-i', '--input', help='The source that will be converted. May be a file or a directory') parser.add_argument('-r', '--readonly', action="store_true", help='Read all data from files in the directory provided, and list them in a file') parser.add_argument('-c', '--config', help='Specify an alternate configuration file location') parser.add_argument('-a', '--auto', action="store_true", help="Enable auto mode, the script will not prompt you for any further input, good for batch files. It will guess the metadata using guessit") parser.add_argument('-tv', '--tvdbid', help="Set the TVDB ID for a tv show") parser.add_argument('-s', '--season', help="Specifiy the season number") parser.add_argument('-o', '--outdir', help="Specifiy the output directory") parser.add_argument('-e', '--episode', help="Specify the episode number") parser.add_argument('-imdb', '--imdbid', help="Specify the IMDB ID for a movie") parser.add_argument('-tmdb', '--tmdbid', help="Specify theMovieDB ID for a movie") parser.add_argument('-nm', '--nomove', action='store_true', help="Overrides and disables the custom moving of file options that come from output_dir and move-to") parser.add_argument('-nc', '--nocopy', action='store_true', help="Overrides and disables the custom copying of file options that come from output_dir and move-to") parser.add_argument('-nd', '--nodelete', action='store_true', help="Overrides and disables deleting of original files") parser.add_argument('-nt', '--notag', action="store_true", help="Overrides and disables tagging when using the automated option") parser.add_argument('-np', '--nopost', action="store_true", help="Overrides and disables the execution of additional post processing scripts") parser.add_argument('-pr', '--preserveRelative', action='store_true', help="Preserves relative directories when processing multiple files using the copy-to or move-to functionality") parser.add_argument('-cmp4', '--convertmp4', action='store_true', help="Overrides convert-mp4 setting in autoProcess.ini enabling the reprocessing of mp4 files") parser.add_argument('-mp', '--maxproc', help="Specify the max amount of concurrent scripts can happen. Passmark score of your CPU / 2000 is a good baseline.") parser.add_argument('-m', '--moveto', help="Override move-to value setting in autoProcess.ini changing the final destination of the file") parser.add_argument('-fc', '--forceConvert', action='store_true', help="Override video copying and force encoding, useful for files that have timescale issues.") args = vars(parser.parse_args()) # Setup the silent mode silent = args['auto'] tag = True #Concurrent if not args['maxproc'] == None: checkForSpot(args['maxproc']) # Settings overrides if(args['config']): if os.path.exists(args['config']): print('Using configuration file "%s"' % (args['config'])) settings = ReadSettings(os.path.split(args['config'])[0], os.path.split(args['config'])[1], logger=log) elif os.path.exists(os.path.join(os.path.dirname(sys.argv[0]), args['config'])): print('Using configuration file "%s"' % (args['config'])) settings = ReadSettings(os.path.dirname(sys.argv[0]), args['config'], logger=log) else: print('Configuration file "%s" not present, using default autoProcess.ini' % (args['config'])) # IF READONLY IS SET, WE WILL ONLY DO THAT. WE WILL NOT USE ANY OTHER CMD ARGUMENT GIVEN (EXCEPT CONFIG) if (args['readonly']): log.debug("Reading info about files only..Ignoring all other command arguments..") readonly = True else: readonly = False if (args['outdir']): settings.output_dir = os.path.normpath(args['outdir']) settings.create_subdirectories = False print("new output directory: %s. Setting create_subdirectories False" % (settings.output_dir)) if (args['nomove']): settings.output_dir = None settings.moveto = None print("No-move enabled") elif (args['moveto']): settings.moveto = args['moveto'] print("Overriden move-to to " + args['moveto']) if (args['nocopy']): settings.copyto = None print("No-copy enabled") if (args['nodelete']): settings.delete = False print("No-delete enabled") if (args['convertmp4']): settings.processMP4 = True print("Reprocessing of MP4 files enabled") if (args['notag']): settings.tagfile = False print("No-tagging enabled") if (args['nopost']): settings.postprocess = False print("No post processing enabled") if (args['forceConvert']): settings.forceConvert = True # Establish the path we will be working with if (args['input']): path = (str(args['input'])) try: path = glob.glob(path)[0] except: pass else: path = getValue("Enter path to file") if readonly: getFileInfo(path, stop_event) else: tvdbid = int(args['tvdbid']) if args['tvdbid'] else None if os.path.isdir(path): walkDir(path, stop_event, silent, tvdbid=tvdbid, preserveRelative=args['preserveRelative'], tag=settings.tagfile) elif (os.path.isfile(path) and MkvtoMp4(settings, logger=log).validSource(path)): if (not settings.tagfile): tagdata = None elif (args['tvdbid'] and not (args['imdbid'] or args['tmdbid'])): season = int(args['season']) if args['season'] else None episode = int(args['episode']) if args['episode'] else None if (tvdbid and season and episode): tagdata = [3, tvdbid, season, episode] else: tagdata = getinfo(path, silent=silent, tvdbid=tvdbid) elif ((args['imdbid'] or args['tmdbid']) and not args['tvdbid']): if (args['imdbid']): imdbid = args['imdbid'] tagdata = [1, imdbid] elif (args['tmdbid']): tmdbid = int(args['tmdbid']) tagdata = [2, tmdbid] else: tagdata = getinfo(path, silent=silent, tvdbid=tvdbid) processFile(path, tagdata, stop_event, None) elif (os.path.isfile(path)): try: with open(path) as f: content = f.readlines() content = [x.strip() for x in content] contentCopy = list(content) contentLen = len(content) print("TOTAL FILES TO CONVERT: %s" % contentLen) count = 0 try: for x in content: currFile = x; updatedCount = percentage(count, contentLen) print("Completion: %%%s" % round(updatedCount, 2), end='\r') if MkvtoMp4(settings, logger=log).validSource(currFile): if (not settings.tagfile): tagdata = None elif (args['tvdbid'] and not (args['imdbid'] or args['tmdbid'])): tvdbid = int(args['tvdbid']) if args['tvdbid'] else None season = int(args['season']) if args['season'] else None episode = int(args['episode']) if args['episode'] else None if (tvdbid and season and episode): tagdata = [3, tvdbid, season, episode] else: tagdata = getinfo(currFile, silent=silent, tvdbid=tvdbid) elif ((args['imdbid'] or args['tmdbid']) and not args['tvdbid']): if (args['imdbid']): imdbid = args['imdbid'] tagdata = [1, imdbid] elif (args['tmdbid']): tmdbid = int(args['tmdbid']) tagdata = [2, tmdbid] else: tagdata = getinfo(currFile, silent=silent) print("PROCCESSING: %s" % (currFile)) processFile(currFile, tagdata, stop_event) count += 1 print("removing %s from file..list length before: %s" % (currFile, len(contentCopy))) contentCopy.remove(currFile) print("list length after: %s" % (len(contentCopy))) data = open(path, "w") for c in contentCopy: data.write("%s\n" % (c)) data.close() except Exception as e: print(e) except: print("File %s is not in the correct format" % (path)) else: try: print("File %s is not in the correct format" % (path)) except: print("File is not in the correct format") except: if stop_event.is_set(): print("Manually stopping conversion...") else: raise Exception("".join(traceback.format_exception(*sys.exc_info()))) #print("done with conversions.") stop_event.set()
sys.exit(POSTPROCESS_NONE) # Make sure one of the appropriate categories is set if category.lower() not in categories: log.error("Post-Process: No valid category detected. Category was %s." % (category)) status = 1 sys.exit(POSTPROCESS_NONE) # Make sure there are no duplicate categories if len(categories) != len(set(categories)): log.error("Duplicate category detected. Category names must be unique.") status = 1 sys.exit(POSTPROCESS_NONE) # All checks done, now launching the script. settings = ReadSettings(MP4folder) if shouldConvert: if output_dir: settings.output_dir = output_dir converter = MkvtoMp4(settings, logger=log) for r, d, f in os.walk(path): for files in f: inputfile = os.path.join(r, files) #DEBUG#print inputfile #Ignores files under 50MB if os.path.getsize(inputfile) > 50000000: info = converter.isValidSource(inputfile) if info: try: output = converter.process(inputfile, info=info)
def main(argv): logpath = './logs/deluge_convert' if os.name == 'nt': logpath = os.path.dirname(sys.argv[0]) elif not os.path.isdir(logpath): try: os.mkdir(logpath) except: logpath = os.path.dirname(sys.argv[0]) configPath = os.path.abspath( os.path.join(os.path.dirname(sys.argv[0]), 'logging.ini')).replace("\\", "\\\\") logPath = os.path.abspath(os.path.join(logpath, 'index.log')).replace("\\", "\\\\") fileConfig(configPath, defaults={'logfilename': logPath}) log = logging.getLogger("delugePostProcess") log.info("Deluge post processing started.") settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini") categories = [ settings.deluge['sb'], settings.deluge['cp'], settings.deluge['sonarr'], settings.deluge['radarr'], settings.deluge['sr'], settings.deluge['bypass'] ] remove = settings.deluge['remove'] if len(argv) < 4: log.error( "Not enough command line parameters present, are you launching this from deluge?" ) return else: path = str(argv[3]) torrent_name = str(argv[2]) torrent_id = str(argv[1]) log.info("Path: %s." % path) log.info("Torrent: %s." % torrent_name) log.info("Hash: %s." % torrent_id) client = DelugeRPCClient(host=settings.deluge['host'], port=int(settings.deluge['port']), username=settings.deluge['user'], password=settings.deluge['pass']) client.connect() if client.connected: log.info("Successfully connected to Deluge") else: log.error("Failed to connect to Deluge") sys.exit() torrent_data = client.call('core.get_torrent_status', torrent_id, ['files', 'label']) torrent_files = torrent_data[b'files'] category = torrent_data[b'label'].lower().decode() files = [] log.debug("List of files in torrent:") for contents in torrent_files: files.append(contents[b'path'].decode()) log.debug(contents[b'path'].decode()) if category.lower() not in categories: log.error("No valid category detected.") sys.exit() if len(categories) != len(set(categories)): log.error( "Duplicate category detected. Category names must be unique.") sys.exit() if settings.deluge['convert']: # Check for custom Deluge output_dir if settings.deluge['output_dir']: settings.output_dir = os.path.join(settings.deluge['output_dir'], "%s" % torrent_name) log.debug("Overriding output_dir to %s.", settings.deluge['output_dir']) # Perform conversion. settings.delete = False if not settings.output_dir: suffix = "convert" settings.output_dir = os.path.join(path, ("%s-%s" % (torrent_name, suffix))) if not os.path.exists(settings.output_dir): os.mkdir(settings.output_dir) delete_dir = settings.output_dir converter = MkvtoMp4(settings) archive = [] movies = [] for filename in files: inputfile = os.path.join(path, filename) pfiles = PF(inputfile) if pfiles.is_movie() == True: log.info('Is our file a video %s', pfiles.is_movie()) log.info("Converting file %s at location %s." % (inputfile, settings.output_dir)) movies.append(inputfile) elif pfiles.is_archive() == True: log.info('Is our file an archive %s', pfiles.is_archive()) if pfiles.test_archive() == True: log.info('Our intput file is a valid archive') archive.append(inputfile) else: log.debug('%s - is not a valid file to process.', filename) if len(archive) == 1: log.info('We have 1 file in our archive list, extracting it') if pfiles.extract_archive(archive[0], settings.output_dir) == True: log.info('Our archive was successful!') pmov = PF(settings.output_dir) movies = pmov.find_movie() converter.delete = True log.info('Our movies list is %s', movies) else: log.error('Our extraction failed') return elif len(archive) >= 1: log.inf0('We have lots of files in our archive list') log.info( 'Choosing the first file to avoid decompressing same file multiple times.' ) if pfiles.extract_archive(archive[0], settings.output_dir) == True: log.info('Our archive was successful!') pmov = PF(settings.output_dir) movies = pmov.find_movie() converter.delete = True log.info('Our movies list is %s', movies) else: log.error('Our extraction failed') return log.info('our movie length is %s', len(movies)) if len(movies) >= 1: log.info('We have %s files in our movie list', len(movies)) for f in movies: try: log.info("Converting file %s at location %s.", f, settings.output_dir) output = converter.process(f) except: log.exception("Error converting file %s.", f) path = converter.output_dir else: suffix = "copy" newpath = os.path.join(path, ("%s-%s" % (torrent_name, suffix))) if not os.path.exists(newpath): os.mkdir(newpath) for filename in files: inputfile = os.path.join(path, filename) log.info("Copying file %s to %s." % (inputfile, newpath)) shutil.copy(inputfile, newpath) path = newpath delete_dir = newpath # Send to Sickbeard if (category == categories[0]): log.info("Passing %s directory to Sickbeard." % path) autoProcessTV.processEpisode(path, settings) # Send to CouchPotato elif (category == categories[1]): log.info("Passing %s directory to Couch Potato." % path) autoProcessMovie.process(path, settings, torrent_name) # Send to Sonarr elif (category == categories[2]): log.info("Passing %s directory to Sonarr." % path) sonarr.processEpisode(path, settings) elif (category == categories[3]): log.info("Passing %s directory to Radarr." % path) radarr.processMovie(path, settings) elif (category == categories[4]): log.info("Passing %s directory to Sickrage." % path) autoProcessTVSR.processEpisode(path, settings) elif (category == categories[5]): log.info("Bypassing any further processing as per category.") if delete_dir: if os.path.exists(delete_dir): try: os.rmdir(delete_dir) log.debug("Successfully removed tempoary directory %s." % delete_dir) return except: log.exception("Unable to delete temporary directory.") return if remove: try: client.call('core.remove_torrent', torrent_id, True) return except: log.exception("Unable to remove torrent from deluge.") return