Ejemplo n.º 1
0
            _sendRequest(session, settings.uTorrentHost,
                         settings.uTorrentUsername, settings.uTorrentPassword,
                         params, None, "Before Function")
            log.debug("Sending action %s to uTorrent" %
                      settings.uTorrentActionBefore)

if settings.uTorrent['convert']:
    # Check for custom uTorrent output_dir
    if settings.uTorrent['output_dir']:
        settings.output_dir = settings.uTorrent['output_dir']
        log.debug("Overriding output_dir to %s." %
                  settings.uTorrent['output_dir'])

    # Perform conversion.
    log.info("Performing conversion")
    settings.delete = False
    if not settings.output_dir:
        suffix = "convert"
        if str(sys.argv[4]) == 'single':
            log.info("Single File Torrent")
            settings.output_dir = os.path.join(path,
                                               ("%s-%s" % (name, suffix)))
        else:
            log.info("Multi File Torrent")
            settings.output_dir = os.path.abspath(
                os.path.join(path, '..', ("%s-%s" % (name, suffix))))
        if not os.path.exists(settings.output_dir):
            os.mkdir(settings.output_dir)
        delete_dir = settings.output_dir

    converter = MkvtoMp4(settings)
    log.debug("Category: %s" % category)
except Exception as e:
    log.exeption("Unable to connect to deluge to retrieve category.")
    sys.exit()

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']:
    # Perform conversion.
    settings.delete = False
    if not settings.output_dir:
        settings.output_dir = os.path.join(path, torrent_name)
        if not os.path.exists(settings.output_dir):
            os.mkdir(settings.output_dir)
        delete_dir = settings.output_dir

    converter = MkvtoMp4(settings)

    for filename in files:
        inputfile = os.path.join(path, filename)
        if MkvtoMp4(settings).validSource(inputfile):
            log.info("Converting file %s at location %s." % (inputfile, settings.output_dir))
            try:
                converter.process(inputfile, reportProgress=True)
            except:
Ejemplo n.º 3
0
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")
Ejemplo n.º 4
0
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")

    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")
    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']).decode(locale.getpreferredencoding())
        try:
            path = glob.glob(path)[0]
        except:
            pass
    else:
        path = getValue("Enter path to file")

    if os.path.isdir(path):
        tvdbid = int(args['tvdbid']) if args['tvdbid'] else None
        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'])):
            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(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)
        processFile(path, tagdata)
    else:
        try:
            print("File %s is not in the correct format" % (path))
        except:
            print("File is not in the correct format")
Ejemplo n.º 5
0
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))
Ejemplo n.º 6
0
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()
Ejemplo n.º 7
0
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