path = converter.output_dir
else:
    newpath = os.path.join(path, torrent_name)
    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)
# 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 Sickrage." % path)
    autoProcessTVSR.processEpisode(path, settings)
elif (category == categories[4]):
    log.info("Bypassing any further processing as per category.")

if delete_dir:
        if single_file:
            inputfile = content_path
            shutil.copy(inputfile, newpath)
            log.debug("Copying %s to %s" % (inputfile, newpath))
        else:
            for r, d, f in os.walk(root_path):
                for files in f:
                    inputfile = os.path.join(r, files)
                    shutil.copy(inputfile, newpath)
                    log.debug("Copying %s to %s" % (inputfile, newpath))
        path = newpath
        delete_dir = newpath

    if settings.qBittorrent['sb'].startswith(label):
        log.info("Passing %s directory to Sickbeard." % path)
        autoProcessTV.processEpisode(path, settings, pathMapping=path_mapping)
    elif settings.qBittorrent['sonarr'].startswith(label):
        log.info("Passing %s directory to Sonarr." % path)
        sonarr.processEpisode(path, settings, pathMapping=path_mapping)
    elif settings.qBittorrent['radarr'].startswith(label):
        log.info("Passing %s directory to Radarr." % path)
        radarr.processMovie(path, settings, pathMapping=path_mapping)
    elif settings.qBittorrent['sr'].startswith(label):
        log.info("Passing %s directory to Sickrage." % path)
        autoProcessTVSR.processEpisode(path,
                                       settings,
                                       pathMapping=path_mapping)
    elif settings.qBittorrent['bypass'].startswith(label):
        log.info("Bypassing any further processing as per category.")

    # Run a qbittorrent action after conversion.
예제 #3
0
        log.debug("Copying %s to %s" % (inputfile, newpath))
    else:
        for r, d, f in os.walk(path):
            for files in f:
                inputfile = os.path.join(r, files)
                shutil.copy(inputfile, newpath)
                log.debug("Copying %s to %s" % (inputfile, newpath))
    path = newpath
    delete_dir = newpath

if label == categories[0]:
    log.info("Passing %s directory to Couch Potato." % path)
    autoProcessMovie.process(path, settings)
elif label == categories[1]:
    log.info("Passing %s directory to Sickbeard." % path)
    autoProcessTV.processEpisode(path, settings)
elif label == categories[2]:
    log.info("Passing %s directory to Sonarr." % path)
    sonarr.processEpisode(path, settings)
elif label == categories[3]:
    log.info("Passing %s directory to Radarr." % path)
    radarr.processMovie(path, settings)
elif label == categories[4]:
    log.info("Passing %s directory to Sickrage." % path)
    autoProcessTVSR.processEpisode(path, settings)
elif label == categories[5]:
    log.info("Bypassing any further processing as per category.")

# Run a uTorrent action after conversion.
if web_ui:
    if session and auth and settings.uTorrentActionAfter:
def main():
    # Args: %L %T %D %K %F %I Label, Tracker, Directory, single|multi, NameofFile(if single), InfoHash
    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()
    path = str(sys.argv[3])
    label = sys.argv[1].lower()
    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 Exception:
        name = sys.argv[6]

    log.debug("Path: %s." % path)
    log.debug("Label: %s." % label)
    log.debug("Categories: %s." % categories)
    log.debug("Torrent hash: %s." % torrent_hash)
    log.debug("Torrent name: %s." % name)

    if label not in categories:
        log.error("No valid label detected.")
        sys.exit()

    if len(categories) != len(set(categories)):
        log.error("Duplicate category detected. Category names must be unique.")
        sys.exit()

    # Import requests
    try:
        import requests
    except ImportError:
        log.exception(
            "Python module REQUESTS is required. Install with 'pip install requests' then try again."
        )
        sys.exit()

    try:
        web_ui = settings.uTorrentWebUI
        log.debug("WebUI is true.")
    except Exception:
        log.debug("WebUI is false.")
        web_ui = False

    delete_dir = False

    # Run a uTorrent action before conversion.
    if web_ui:
        session = requests.Session()
        if session:
            auth, session = _authToken(
                session,
                settings.uTorrentHost,
                settings.uTorrentUsername,
                settings.uTorrentPassword,
            )
            if auth and settings.uTorrentActionBefore:
                params = {
                    "token": auth,
                    "action": settings.uTorrentActionBefore,
                    "hash": torrent_hash,
                }
                _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)

        if str(sys.argv[4]) == "single":
            inputfile = os.path.join(path, str(sys.argv[5]))
            if MkvtoMp4(settings).validSource(inputfile):
                log.info("Processing file %s." % inputfile)
                try:
                    output = converter.process(inputfile, reportProgress=True)
                except Exception:
                    log.exception("Error converting file %s." % inputfile)
            else:
                log.debug("Ignoring file %s." % inputfile)
        else:
            log.debug("Processing multiple files.")
            ignore = []
            for r, d, f in os.walk(path):
                for files in f:
                    inputfile = os.path.join(r, files)
                    if (
                        MkvtoMp4(settings).validSource(inputfile)
                        and inputfile not in ignore
                    ):
                        log.info("Processing file %s." % inputfile)
                        try:
                            output = converter.process(inputfile)
                            if output is not False:
                                ignore.append(output["output"])
                            else:
                                log.error("Converting file failed %s." % inputfile)
                        except:
                            log.exception("Error converting file %s." % inputfile)
                    else:
                        log.debug("Ignoring file %s." % inputfile)

        path = converter.output_dir
    else:
        suffix = "copy"
        # name = name[:260-len(suffix)]
        if str(sys.argv[4]) == "single":
            log.info("Single File Torrent")
            newpath = os.path.join(path, ("%s-%s" % (name, suffix)))
        else:
            log.info("Multi File Torrent")
            newpath = os.path.abspath(
                os.path.join(path, "..", ("%s-%s" % (name, suffix)))
            )
        if not os.path.exists(newpath):
            os.mkdir(newpath)
            log.debug("Creating temporary directory %s" % newpath)
        if str(sys.argv[4]) == "single":
            inputfile = os.path.join(path, str(sys.argv[5]))
            shutil.copy(inputfile, newpath)
            log.debug("Copying %s to %s" % (inputfile, newpath))
        else:
            for r, d, f in os.walk(path):
                for files in f:
                    inputfile = os.path.join(r, files)
                    shutil.copy(inputfile, newpath)
                    log.debug("Copying %s to %s" % (inputfile, newpath))
        path = newpath
        delete_dir = newpath

    if label == categories[0]:
        log.info("Passing %s directory to Couch Potato." % path)
        autoProcessMovie.process(path, settings)
    elif label == categories[1]:
        log.info("Passing %s directory to Sickbeard." % path)
        autoProcessTV.processEpisode(path, settings)
    elif label == categories[2]:
        log.info("Passing %s directory to Sonarr." % path)
        sonarr.processEpisode(path, settings)
    elif label == categories[3]:
        log.info("Passing %s directory to Radarr." % path)
        radarr.processMovie(path, settings)
    elif label == categories[4]:
        log.info("Passing %s directory to Sickrage." % path)
        autoProcessTVSR.processEpisode(path, settings)
    elif label == categories[5]:
        log.info("Bypassing any further processing as per category.")

    # Run a uTorrent action after conversion.
    if web_ui:
        if session and auth and settings.uTorrentActionAfter:
            params = {
                "token": auth,
                "action": settings.uTorrentActionAfter,
                "hash": torrent_hash,
            }
            _sendRequest(
                session,
                settings.uTorrentHost,
                settings.uTorrentUsername,
                settings.uTorrentPassword,
                params,
                None,
                "After Function",
            )
            log.debug("Sending action %s to uTorrent" % settings.uTorrentActionAfter)

    if delete_dir:
        if os.path.exists(delete_dir):
            try:
                os.rmdir(delete_dir)
                log.debug("Successfully removed tempoary directory %s." % delete_dir)
            except Exception:
                log.exception("Unable to delete temporary directory")

    sys.exit()
    else:
        log.info("Doesn't already exist: {}.".format(sub_copy_path))
    copytree(copy_to,
             sub_copy_path,
             ignore=include_patterns('*.sub', '*.smi', '*.ssa', '*.ass',
                                     '*.vtt', '*.srt', '*.idx'))
    if os.path.isdir(sub_copy_path) and not os.listdir(sub_copy_path):
        # If no subs found, no point having dir
        os.rmdir(sub_copy_path)

    if label == categories[0]:
        log.info("Passing %s directory to Couch Potato." % copy_to)
        autoProcessMovie.process(copy_to, settings)
    elif label == categories[1]:
        log.info("Passing %s directory to Sickbeard." % copy_to)
        autoProcessTV.processEpisode(copy_to, settings)
    elif label == categories[2]:
        log.info("Passing %s directory to Sonarr." % copy_to)
        sonarr.processEpisode(copy_to, settings)
    elif label == categories[3]:
        log.info("Passing %s directory to Radarr." % copy_to)
        radarr.processMovie(copy_to, settings)
    elif label == categories[4]:
        log.info("Passing %s directory to Sickrage." % copy_to)
        autoProcessTVSR.processEpisode(copy_to, settings)
    elif label == categories[5]:
        log.info("Bypassing any further processing as per category.")

    log.info("Resuming all torrents")
    qb.resume_all()
예제 #6
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