예제 #1
0
    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
예제 #2
0
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 os
import sys
import json
import urllib
from readSettings import ReadSettings
from tvdb_mp4 import Tvdb_mp4
from mkvtomp4 import MkvtoMp4
from extensions import valid_output_extensions

settings = ReadSettings(os.path.dirname(sys.argv[0]), "tvdb_mp4.ini")

if len(sys.argv) > 4:
    path = str(sys.argv[1]).replace("\\","\\\\").replace("\\\\\\\\","\\\\")
    extension = os.path.splitext(path)[1][1:]
    tvdb_id = int(sys.argv[3])
    season = int(sys.argv[4])
    episode  = int(sys.argv[5])

    convert = MkvtoMp4(path, settings.ffmpeg, settings.ffprobe, settings.delete, settings.output_extension, settings.output_dir)
    if extension not in valid_output_extensions:
        path = convert.output
        try:
            refresh = json.load(urllib.urlopen(settings.getRefreshURL(tvdb_id)))
            for item in refresh:
                print refresh[item]
        except IOError:
            print "Couldn't refresh Sickbeard, check your tvdb_mp4.ini settings"
    tagmp4 = Tvdb_mp4(tvdb_id, season, episode)
    tagmp4.setHD(convert.width, convert.height)
    tagmp4.writeTags(path)
else:
예제 #4
0
log.info("SAB post processing started.")

if len(sys.argv) < 8:
    log.error("Not enough command line parameters specified. Is this being called from SAB?")
    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

settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini")
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)

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

if len(categories) != len(set(categories)):
    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)
예제 #6
0
              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(os.path.dirname(sys.argv[0]), "autoProcess.ini")
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:
    name = sys.argv[6]

log.debug("Path: %s." % path)
log.debug("Label: %s." % label)
log.info("SAB post processing started.")

if len(sys.argv) < 8:
    log.error("Not enough command line parameters specified. Is this being called from SAB?")
    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

settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini")
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)

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

if len(categories) != len(set(categories)):
예제 #8
0
        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)
예제 #9
0
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()
log = logging.getLogger("qBittorrentPostProcess")

log.info("qBittorrent post processing started.")

if len(sys.argv) != 7:
    log.error(
        "Not enough command line parameters present, are you launching this from qBittorrent?"
    )
    log.error(
        "#Args: %L %T %R %F %N %I Category, Tracker, RootPath, ContentPath , TorrentName, InfoHash"
    )
    log.error("Length was %s" % str(len(sys.argv)))
    log.error(str(sys.argv[1:]))
    sys.exit()

settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini")
label = sys.argv[1].lower()
root_path = str(sys.argv[3])
content_path = str(sys.argv[4])
name = sys.argv[5]
torrent_hash = sys.argv[6]
categories = [
    settings.qBittorrent['cp'], settings.qBittorrent['sb'],
    settings.qBittorrent['sonarr'], settings.qBittorrent['radarr'],
    settings.qBittorrent['sr'], settings.qBittorrent['bypass']
]

log.debug("Root Path: %s." % root_path)
log.debug("Content Path: %s." % content_path)
log.debug("Label: %s." % label)
log.debug("Categories: %s." % categories)
    if response.status_code == 200:
        log.debug("Request sent successfully - %s." % fnct)
        return True

    log.error(
        "Problem sending command "
        + fnct
        + ", return code = "
        + str(response.status_code)
        + "."
    )
    return False


settings = ReadSettings(os.path.dirname(__file__), "autoProcess.ini")


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])
if len(sys.argv) < 8:
    log.error(
        "Not enough command line parameters specified. Is this being called from SAB?"
    )
    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

settings = ReadSettings(os.path.dirname(__file__), "autoProcess.ini")
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)
if len(sys.argv) < 8:
    log.error(
        "Not enough command line parameters specified. Is this being called from SAB?"
    )
    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

settings = ReadSettings(os.path.dirname(__file__), "autoProcess.ini")
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)
        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, "autoProcess.ini")

    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:
                    if MkvtoMp4(settings, logger=log).validSource(inputfile):
                        try:
                            output = converter.process(inputfile)
                            log.info("Successfully processed %s." % inputfile)
예제 #15
0
import os
import sys
from log import getLogger
from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr, radarr
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
from deluge_client import DelugeRPCClient
import logging
import shutil
from logging.config import fileConfig

log = getLogger("DelugePostProcess")

log.info("Deluge post processing started.")

settings = ReadSettings()
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()

path = str(sys.argv[3])
torrent_name = str(sys.argv[2])
torrent_id = str(sys.argv[1])
delete_dir = None

log.debug("Path: %s." % path)
log.debug("Torrent: %s." % torrent_name)
log.debug("Hash: %s." % torrent_id)
    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.
예제 #17
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")
예제 #18
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()
    if response.status_code == 200:
        log.debug("Request sent successfully - %s." % fnct)
        return True

    log.error("Problem sending command " + fnct + ", return code = " + 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(os.path.dirname(sys.argv[0]), "autoProcess.ini")
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:
    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)
import os
import sys
from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
from deluge import DelugeClient
import logging
from logging.config import fileConfig

fileConfig(os.path.join(os.path.dirname(sys.argv[0]), 'logging.ini'), defaults={'logfilename': os.path.join(os.path.dirname(sys.argv[0]), 'info.log').replace("\\", "/")})
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['sr'], settings.deluge['bypass']]

if len(sys.argv) < 4:
    log.error("Not enough command line parameters present, are you launching this from deluge?")
    sys.exit()

path = str(sys.argv[3])
torrent_name = str(sys.argv[2])
torrent_id = str(sys.argv[1])

log.debug("Path: %s." % path)
log.debug("Torrent: %s." % torrent_name)
log.debug("Hash: %s." % torrent_id)

client = DelugeClient()
예제 #21
0
    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")

    if shouldConvert:
        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:
                    if MkvtoMp4(settings, logger=log).validSource(inputfile):
                        try:
                            output = converter.process(inputfile)
                            log.info("Successfully processed %s." % inputfile)
                            if (category == categories[2]
                                    and settings.relocate_moov):
import os
import sys
import autoProcessTV
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4

#Args: %L %T %D %K %F   Label, Tracker, Directory, single|multi, NameofFile(if single)

path = str(sys.argv[3])
settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini")

if settings.uTorrentLabel.lower() == sys.argv[1].lower() or not settings.uTorrentLabel:

    delete_dir = False
    settings.delete = False
    if not settings.output_dir:
        settings.output_dir = os.path.join(path, 'converted')
        if not os.path.exists(settings.output_dir):
            os.mkdir(settings.output_dir)
        delete_dir = True

    converter = MkvtoMp4(settings)
        
    if str(sys.argv[4]) == 'single':
        inputfile = os.path.join(path,str(sys.argv[5]))
        if MkvtoMp4(settings).validSource(inputfile):
            converter.process(inputfile)
    else:
        for r, d, f in os.walk(path):
            for files in f:
                inputfile = os.path.join(r, files)
              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]
예제 #24
0
from autoprocess import plex
from tvdb_mp4 import Tvdb_mp4
from mkvtomp4 import MkvtoMp4
from post_processor import PostProcessor
from logging.config import fileConfig

fileConfig(os.path.join(os.path.dirname(sys.argv[0]), 'logging.ini'),
           defaults={
               'logfilename':
               os.path.join(os.path.dirname(sys.argv[0]), 'info.log')
           })
log = logging.getLogger("SickbeardPostConversion")

log.info("Sickbeard extra script post processing started.")

settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini")

if len(sys.argv) > 4:
    inputfile = sys.argv[1]
    original = sys.argv[2]
    tvdb_id = int(sys.argv[3])
    season = int(sys.argv[4])
    episode = int(sys.argv[5])

    converter = MkvtoMp4(settings)

    log.debug("Input file: %s." % inputfile)
    log.debug("Original name: %s." % original)
    log.debug("TVDB ID: %s." % tvdb_id)
    log.debug("Season: %s episode: %s." % (season, episode))
예제 #25
0
import urllib
import struct
import logging
from readSettings import ReadSettings
from autoprocess import plex
from tvdb_mp4 import Tvdb_mp4
from mkvtomp4 import MkvtoMp4
from post_processor import PostProcessor
from logging.config import fileConfig

fileConfig(os.path.join(os.path.dirname(sys.argv[0]), 'logging.ini'), defaults={'logfilename': os.path.join(os.path.dirname(sys.argv[0]), 'info.log')})
log = logging.getLogger("SickbeardPostConversion")

log.info("Sickbeard extra script post processing started.")

settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini")

if len(sys.argv) > 4:
    inputfile = sys.argv[1]
    original = sys.argv[2]
    tvdb_id = int(sys.argv[3])
    season = int(sys.argv[4])
    episode = int(sys.argv[5])

    converter = MkvtoMp4(settings)

    log.debug("Input file: %s." % inputfile)
    log.debug("Original name: %s." % original)
    log.debug("TVDB ID: %s." % tvdb_id)
    log.debug("Season: %s episode: %s." % (season, episode))
예제 #26
0
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()
예제 #27
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))
import urllib
import struct
import logging
from log import getLogger
from readSettings import ReadSettings
from autoprocess import plex
from metadata import Metadata, MediaType
from mkvtomp4 import MkvtoMp4
from post_processor import PostProcessor
from logging.config import fileConfig

log = getLogger("SickbeardPostProcess")

log.info("Sickbeard extra script post processing started.")

settings = ReadSettings()

if len(sys.argv) > 4:
    inputfile = sys.argv[1]
    original = sys.argv[2]
    tvdb_id = int(sys.argv[3])
    season = int(sys.argv[4])
    episode = int(sys.argv[5])

    converter = MkvtoMp4(settings)

    log.debug("Input file: %s." % inputfile)
    log.debug("Original name: %s." % original)
    log.debug("TVDB ID: %s." % tvdb_id)
    log.debug("Season: %s episode: %s." % (season, episode))
예제 #29
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")
예제 #30
0
import time
from log import getLogger
from readSettings import ReadSettings
from autoprocess import plex
from metadata import Metadata, MediaType
from mkvtomp4 import MkvtoMp4
from post_processor import PostProcessor

log = getLogger("SonarrPostProcess")

log.info("Sonarr extra script post processing started.")

if os.environ.get('sonarr_eventtype') == "Test":
    sys.exit(0)

settings = ReadSettings()

inputfile = os.environ.get('sonarr_episodefile_path')
original = os.environ.get('sonarr_episodefile_scenename')
tvdb_id = int(os.environ.get('sonarr_series_tvdbid'))
season = int(os.environ.get('sonarr_episodefile_seasonnumber'))

try:
    episode = int(os.environ.get('sonarr_episodefile_episodenumbers'))
except:
    episode = int(
        os.environ.get('sonarr_episodefile_episodenumbers').split(",")[0])

converter = MkvtoMp4(settings)

log.debug("Input file: %s." % inputfile)
예제 #31
0
from mkvtomp4 import MkvtoMp4
from deluge import DelugeClient
import logging
from logging.config import fileConfig

fileConfig(os.path.join(os.path.dirname(sys.argv[0]), 'logging.ini'),
           defaults={
               'logfilename':
               os.path.join(os.path.dirname(sys.argv[0]),
                            'info.log').replace("\\", "/")
           })
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['sr'], settings.deluge['bypass']
]

if len(sys.argv) < 4:
    log.error(
        "Not enough command line parameters present, are you launching this from deluge?"
    )
    sys.exit()

path = str(sys.argv[3])
torrent_name = str(sys.argv[2])
torrent_id = str(sys.argv[1])
if len(sys.argv) < 8:
    log.error(
        "Not enough command line parameters specified. Is this being called from SAB?"
    )
    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

settings = ReadSettings()
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)

if category.lower() not in categories:
    log.error("No valid category detected.")
예제 #33
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(sys.argv) < 4:
    log.error(
        "Not enough command line parameters present, are you launching this from deluge?"
    )
    sys.exit()

path = str(sys.argv[3])
torrent_name = str(sys.argv[2])
torrent_id = str(sys.argv[1])
    if response.status_code == 200:
        log.debug("Request sent successfully - %s." % fnct)
        return True

    log.error("Problem sending command " + fnct + ", return code = " + 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(os.path.dirname(sys.argv[0]), "autoProcess.ini")
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:
    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)
예제 #35
0
              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(os.path.dirname(sys.argv[0]), "autoProcess.ini")
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:
    name = sys.argv[6]

log.debug("Path: %s." % path)
log.debug("Label: %s." % label)
from logging.config import fileConfig

logpath = '/var/log/sickbeard_mp4_automator'
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])
fileConfig(os.path.join(os.path.dirname(sys.argv[0]), 'logging.ini'), defaults={'logfilename': os.path.join(logpath, 'index.log')})
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(sys.argv) < 4:
    log.error("Not enough command line parameters present, are you launching this from deluge?")
    sys.exit()

path = str(sys.argv[3])
torrent_name = str(sys.argv[2])
torrent_id = str(sys.argv[1])
delete_dir = None

log.debug("Path: %s." % path)
log.debug("Torrent: %s." % torrent_name)
log.debug("Hash: %s." % torrent_id)
예제 #37
0
def main(argv=None):
    '''Command line options.'''

    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__

    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    program_usage = '''python postProcess.py calFreq''' # optional - will be autogenerated by optparse
    program_longdesc = '''''' # optional - give further explanation about what the program does
    program_license = "Copyright 2016 user_name (organization_name)                                            \
                Licensed under the Apache License 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0"
    
    usage = "usage: %prog [options] [arg]  \'python postProcess freFreq\' should be run first. Then \'python postProcess.py\'" 
    longdesc  = "arg = calFreq: calculate frequencies of the workd. It should be run first. No arg meanse calculate cooefficient" 
    
    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(usage=usage)
#         parser.add_option("-a", "--wordA", dest="wordA", 
#                           help="word A which need to find the autocorrelation")
#         parser.add_option("-b", "--wordB", dest="wordB",
#                           help="word A which need to find the autocorrelation")
        parser.add_option("-n", "--number",dest="maxNum", default="5", help="set the max number of words that can form a phrase")

        # process options
        (opts, args) = parser.parse_args(argv)
            
        MAXWORDS = int(opts.maxNum)
     

        # MAIN BODY #
        settings = ReadSettings();
       
        if not os.path.exists(settings.getWriteWebDir()):
            print "Cannot find original crawled web directory."
            sys.exit(0)
         
        if not os.path.exists(settings.getReadWebDir()):
            print "Cannot find the directory where the frequency files with timestamp is located." 
            sys.exit(0) 

        if not os.path.exists(settings.getWordsFilePath()):
            print "Cannot find the words file." 
            sys.exit(0)
            
        if not os.path.exists(settings.getResultsDir()):
            print "Cannot find the result directory." 
            sys.exit(0)    
        
        if len(args) == 0:
            resultsFileName = settings.getResultsDir() + '/' + str(int(time.time()))
            print "Please make sure you have run python postProcess.py calFreq."
            print "Calculating the coefficients of the word pairs in %s." % settings.getWordsFilePath()
            with open(resultsFileName, 'w+') as resultFile: 
                with open(settings.getWordsFilePath(), 'r+') as f:
                    for line in f:
                        resultFile.write(line)
                        resultFile.write('\r\n')
                        words = line.split(':')
                        wordA = words[0].strip()
                        wordB = words[0].strip()
                        autoCorr = CalAutocorrelation(settings.getWriteWebDir())
                        autoCorrelation, corrcoef, normA, normB = autoCorr.getAutocorrelation(wordA, wordA)
                        resultFile.write('Correlation coefficient is %4f.' %  corrcoef)
                        resultFile.write('\r\n')
                        resultFile.write('The norms of the two words are %4f and %4f.' % (normA, normB))
                        resultFile.write('\r\n')
                        resultFile.write('..........................................................')
                        resultFile.write('\r\n')
        elif args[0] == 'calFreq':
            print "Calulating the frequencies from the files in %s." % settings.getReadWebDir()
            print "The frequency files are in %s." % settings.getReadWebDir()
            calFreq = CalFreqFiles(settings.getReadWebDir(), settings.getWriteWebDir(), MAXWORDS) 
            calFreq.calFreq()              
    except Exception, e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2
    if response.status_code == 200:
        log.debug("Request sent successfully - %s." % fnct)
        return True

    log.error("Problem sending command " + fnct + ", return code = " + 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(os.path.dirname(sys.argv[0]), "autoProcess.ini")
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:
    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)
import os
import sys
from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
from deluge import DelugeClient
import logging
from logging.config import fileConfig

fileConfig(os.path.join(os.path.dirname(sys.argv[0]), 'logging.ini'), defaults={'logfilename': os.path.join(os.path.dirname(sys.argv[0]), 'info.log').replace("\\", "/")})
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['sr'], settings.deluge['bypass']]

if len(sys.argv) < 4:
    log.error("Not enough command line parameters present, are you launching this from deluge?")
    sys.exit()

path = str(sys.argv[3])
torrent_name = str(sys.argv[2])
torrent_id = str(sys.argv[1])

log.debug("Path: %s." % path)
log.debug("Torrent: %s." % torrent_name)
log.debug("Hash: %s." % torrent_id)

client = DelugeClient()
예제 #40
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