Example #1
0
def processEpisode(dirName, nzbName=None, failed=False):

    status = int(failed)
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
    Logger.info("Loading config from %s", configFilename)

    if not os.path.isfile(configFilename):
        Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
        return 1 # failure

    config.read(configFilename)

    watch_dir = ""
    host = config.get("SickBeard", "host")
    port = config.get("SickBeard", "port")
    username = config.get("SickBeard", "username")
    password = config.get("SickBeard", "password")
    try:
        ssl = int(config.get("SickBeard", "ssl"))
    except (ConfigParser.NoOptionError, ValueError):
        ssl = 0

    try:
        web_root = config.get("SickBeard", "web_root")
    except ConfigParser.NoOptionError:
        web_root = ""

    try:
        watch_dir = config.get("SickBeard", "watch_dir")
    except ConfigParser.NoOptionError:
        watch_dir = ""

    try:
        failed_fork = int(config.get("SickBeard", "failed_fork"))
    except (ConfigParser.NoOptionError, ValueError):
        failed_fork = 0

    try:    
        transcode = int(config.get("Transcoder", "transcode"))
    except (ConfigParser.NoOptionError, ValueError):
        transcode = 0

    try:
        delete_failed = int(config.get("SickBeard", "delete_failed"))
    except (ConfigParser.NoOptionError, ValueError):
        delete_failed = 0
    try:
        delay = float(config.get("SickBeard", "delay"))
    except (ConfigParser.NoOptionError, ValueError):
        delay = 0


    mediaContainer = (config.get("Extensions", "mediaExtensions")).split(',')
    minSampleSize = int(config.get("Extensions", "minSampleSize"))

    process_all_exceptions(nzbName.lower(), dirName)

    # Now check if movie files exist in destination:
    video = int(0)
    for dirpath, dirnames, filenames in os.walk(dirName):
        for file in filenames:
            filePath = os.path.join(dirpath, file)
            fileExtension = os.path.splitext(file)[1]
            if fileExtension in mediaContainer:  # If the file is a video file
                if is_sample(filePath, nzbName, minSampleSize):
                    Logger.debug("Removing sample file: %s", filePath)
                    os.unlink(filePath)  # remove samples
                else:
                    video = video + 1
    if video > 0:  # Check that a video exists. if not, assume failed.
        flatten(dirName) # to make sure SickBeard can find the video (not in sub-folder)
    else:
        Logger.warning("No media files found in directory %s. Processing this as a failed download", dirName)
        status = int(1)
        failed = True

    #allows manual call of postprocess script if we have specified a watch_dir. Check that here.
    if nzbName == "Manual Run" and watch_dir == "":
        Logger.error("In order to run this script manually you must specify a watch_dir in autoProcessTV.cfg")
        return 1 # failure
    #allows us to specify the default watch directory and call the postproecssing on another PC with different directory structure.
    if watch_dir != "":
        dirName = watch_dir

    params = {}

    params['quiet'] = 1

    # if you have specified you are using development branch from fork https://github.com/Tolstyak/Sick-Beard.git
    if failed_fork:
        params['dirName'] = dirName
        if nzbName != None:
            params['nzbName'] = nzbName
        params['failed'] = failed
        if status == 0:
            Logger.info("The download succeeded. Sending process request to SickBeard's failed branch")
        else:
            Logger.info("The download failed. Sending 'failed' process request to SickBeard's failed branch")
            

    # this is our default behaviour to work with the standard Master branch of SickBeard
    else:
        params['dir'] = dirName
        if nzbName != None:
            params['nzbName'] = nzbName
        # the standard Master bamch of SickBeard cannot process failed downloads. So Exit here.
        if status == 0:
            Logger.info("The download succeeded. Sending process request to SickBeard")
        else:
            Logger.info("The download failed. Nothing to process")
            if delete_failed and os.path.isdir(dirName) and not dirName in ['sys.argv[0]','/','']:
                delete(dirName)
            return 0 # Success (as far as this script is concerned)
    
    if status == 0 and transcode == 1: # only transcode successful downlaods
        result = Transcoder.Transcode_directory(dirName)
        if result == 0:
            Logger.debug("Transcoding succeeded for files in %s", dirName)
        else:
            Logger.warning("Transcoding failed for files in %s", dirName)

    myOpener = AuthURLOpener(username, password)

    if ssl:
        protocol = "https://"
    else:
        protocol = "http://"

    url = protocol + host + ":" + port + web_root + "/home/postprocess/processEpisode?" + urllib.urlencode(params)

    Logger.info("Waiting for %s seconds to allow CPS to process newly extracted files", str(delay))

    time.sleep(delay)

    Logger.debug("Opening URL: %s", url)

    try:
        urlObj = myOpener.openit(url)
    except:
        Logger.exception("Unable to open URL")
        return 1 # failure

    result = urlObj.readlines()
    for line in result:
        Logger.info("%s", line.rstrip())
    if status != 0 and delete_failed and not dirName in ['sys.argv[0]','/','']:
        delete(dirName)
    return 0 # Success
Example #2
0
def process(dirName,
            nzbName=None,
            status=0,
            clientAgent="manual",
            download_id=""):

    status = int(status)
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]),
                                  "autoProcessMedia.cfg")
    Logger.info("Loading config from %s", configFilename)

    if not os.path.isfile(configFilename):
        Logger.error(
            "You need an autoProcessMedia.cfg file - did you rename and edit the .sample?"
        )
        return 1  # failure

    config.read(configFilename)

    host = config.get("CouchPotato", "host")
    port = config.get("CouchPotato", "port")
    apikey = config.get("CouchPotato", "apikey")
    delay = float(config.get("CouchPotato", "delay"))
    method = config.get("CouchPotato", "method")
    delete_failed = int(config.get("CouchPotato", "delete_failed"))
    wait_for = int(config.get("CouchPotato", "wait_for"))

    try:
        ssl = int(config.get("CouchPotato", "ssl"))
    except (ConfigParser.NoOptionError, ValueError):
        ssl = 0

    try:
        web_root = config.get("CouchPotato", "web_root")
    except ConfigParser.NoOptionError:
        web_root = ""

    try:
        transcode = int(config.get("Transcoder", "transcode"))
    except (ConfigParser.NoOptionError, ValueError):
        transcode = 0

    try:
        remoteCPS = int(config.get("CouchPotato", "remoteCPS"))
    except (ConfigParser.NoOptionError, ValueError):
        remoteCPS = 0

    nzbName = str(nzbName)  # make sure it is a string

    imdbid = get_imdb(nzbName, dirName)

    if ssl:
        protocol = "https://"
    else:
        protocol = "http://"
    # don't delay when we are calling this script manually.
    if nzbName == "Manual Run":
        delay = 0

    baseURL = protocol + host + ":" + port + web_root + "/api/" + apikey + "/"

    movie_id = get_movie_info(
        baseURL, imdbid,
        download_id)  # get the CPS database movie id this movie.

    initial_status, clientAgent, download_id, initial_release_status = get_status(
        baseURL, movie_id, clientAgent, download_id)

    process_all_exceptions(nzbName.lower(), dirName)

    if status == 0:
        if transcode == 1:
            result = Transcoder.Transcode_directory(dirName)
            if result == 0:
                Logger.debug("Transcoding succeeded for files in %s", dirName)
            else:
                Logger.warning("Transcoding failed for files in %s", dirName)

        if method == "manage":
            command = "manage.update"
        else:
            command = "renamer.scan"
            if clientAgent != "manual" and download_id != "none":
                if remoteCPS == 1:
                    command = command + "/?downloader=" + clientAgent + "&download_id=" + download_id
                else:
                    command = command + "/?movie_folder=" + dirName + "&downloader=" + clientAgent + "&download_id=" + download_id

        url = baseURL + command

        Logger.info(
            "Waiting for %s seconds to allow CPS to process newly extracted files",
            str(delay))

        time.sleep(delay)

        Logger.debug("Opening URL: %s", url)

        try:
            urlObj = urllib.urlopen(url)
        except:
            Logger.exception("Unable to open URL")
            return 1  # failure

        result = json.load(urlObj)
        Logger.info("CouchPotatoServer returned %s", result)
        if result['success']:
            Logger.info("%s scan started on CouchPotatoServer for %s", method,
                        nzbName)
        else:
            Logger.error(
                "%s scan has NOT started on CouchPotatoServer for %s. Exiting",
                method, nzbName)
            return 1  # failure

    else:
        Logger.info("Download of %s has failed.", nzbName)
        Logger.info("Trying to re-cue the next highest ranked release")

        if not movie_id:
            Logger.warning(
                "Cound not find a movie in the database for release %s",
                nzbName)
            Logger.warning(
                "Please manually ignore this release and refresh the wanted movie"
            )
            Logger.error("Exiting autoProcessMovie script")
            return 1  # failure

        url = baseURL + "movie.searcher.try_next/?id=" + movie_id

        Logger.debug("Opening URL: %s", url)

        try:
            urlObj = urllib.urlopen(url)
        except:
            Logger.exception("Unable to open URL")
            return 1  # failure

        result = urlObj.readlines()
        for line in result:
            Logger.info("%s", line)

        Logger.info(
            "Movie %s set to try the next best release on CouchPotatoServer",
            movie_id)
        if delete_failed and not dirName in ['sys.argv[0]', '/', '']:
            Logger.info("Deleting failed files and folder %s", dirName)
            try:
                shutil.rmtree(dirName)
            except:
                Logger.exception("Unable to delete folder %s", dirName)
        return 0  # success

    if nzbName == "Manual Run":
        return 0  # success

    # we will now check to see if CPS has finished renaming before returning to TorrentToMedia and unpausing.
    start = datetime.datetime.now()  # set time for timeout
    pause_for = wait_for * 10  # keep this so we only ever have 6 complete loops.
    while (datetime.datetime.now() - start) < datetime.timedelta(
            minutes=wait_for):  # only wait 2 (default) minutes, then return.
        movie_status, clientAgent, download_id, release_status = get_status(
            baseURL, movie_id, clientAgent,
            download_id)  # get the current status fo this movie.
        if movie_status != initial_status:  # Something has changed. CPS must have processed this movie.
            Logger.info(
                "SUCCESS: This movie is now marked as status %s in CouchPotatoServer",
                movie_status)
            return 0  # success
        time.sleep(
            pause_for
        )  # Just stop this looping infinitely and hogging resources for 2 minutes ;)
    else:
        if release_status != initial_release_status and release_status != "none":  # Something has changed. CPS must have processed this movie.
            Logger.info(
                "SUCCESS: This release is now marked as status %s in CouchPotatoServer",
                release_status)
            return 0  # success
        else:  # The status hasn't changed. we have waited 2 minutes which is more than enough. uTorrent can resule seeding now.
            Logger.warning(
                "The movie does not appear to have changed status after %s minutes. Please check CouchPotato Logs",
                wait_for)
            return 1  # failure
Example #3
0
def process(dirName, nzbName=None, status=0):

    status = int(status)
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
    Logger.info("Loading config from %s", configFilename)

    if not os.path.isfile(configFilename):
        Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
        return 1 # failure

    config.read(configFilename)

    host = config.get("CouchPotato", "host")
    port = config.get("CouchPotato", "port")
    username = config.get("CouchPotato", "username")
    password = config.get("CouchPotato", "password")
    apikey = config.get("CouchPotato", "apikey")
    delay = float(config.get("CouchPotato", "delay"))
    method = config.get("CouchPotato", "method")
    delete_failed = int(config.get("CouchPotato", "delete_failed"))

    try:
        ssl = int(config.get("CouchPotato", "ssl"))
    except (ConfigParser.NoOptionError, ValueError):
        ssl = 0

    try:
        web_root = config.get("CouchPotato", "web_root")
    except ConfigParser.NoOptionError:
        web_root = ""
        
    try:    
        transcode = int(config.get("Transcoder", "transcode"))
    except (ConfigParser.NoOptionError, ValueError):
        transcode = 0

    myOpener = AuthURLOpener(username, password)

    nzbName = str(nzbName) # make sure it is a string
    
    imdbid = get_imdb(nzbName, dirName)

    if ssl:
        protocol = "https://"
    else:
        protocol = "http://"
    # don't delay when we are calling this script manually.
    if nzbName == "Manual Run":
        delay = 0

    baseURL = protocol + host + ":" + port + web_root + "/api/" + apikey + "/"
    
    movie_id = get_movie_info(myOpener, baseURL, imdbid) # get the CPS database movie id this movie.
    
    initial_status = get_status(myOpener, baseURL, movie_id)
    
    process_all_exceptions(nzbName.lower(), dirName)

    if status == 0:
        if transcode == 1:
            result = Transcoder.Transcode_directory(dirName)
            if result == 0:
                Logger.debug("Transcoding succeeded for files in %s", dirName)
            else:
                Logger.warning("Transcoding failed for files in %s", dirName)

        if method == "manage":
            command = "manage.update"
        else:
            command = "renamer.scan"

        url = baseURL + command

        Logger.info("Waiting for %s seconds to allow CPS to process newly extracted files", str(delay))

        time.sleep(delay)

        Logger.debug("Opening URL: %s", url)

        try:
            urlObj = myOpener.openit(url)
        except IOError, e:
            Logger.error("Unable to open URL: %s", str(e))
            return 1 # failure

        result = json.load(urlObj)
        Logger.info("CouchPotatoServer returned %s", result)
        if result['success']:
            Logger.info("%s started on CouchPotatoServer for %s", command, nzbName)
        else:
            Logger.error("%s has NOT started on CouchPotatoServer for %s. Exiting", command, nzbName)
            return 1 # failure
Example #4
0
def processEpisode(dirName, nzbName=None, failed=False):

    status = int(failed)
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]),
                                  "autoProcessMedia.cfg")
    Logger.info("Loading config from %s", configFilename)

    if not os.path.isfile(configFilename):
        Logger.error(
            "You need an autoProcessMedia.cfg file - did you rename and edit the .sample?"
        )
        return 1  # failure

    config.read(configFilename)

    watch_dir = ""
    host = config.get("SickBeard", "host")
    port = config.get("SickBeard", "port")
    username = config.get("SickBeard", "username")
    password = config.get("SickBeard", "password")
    try:
        ssl = int(config.get("SickBeard", "ssl"))
    except (ConfigParser.NoOptionError, ValueError):
        ssl = 0

    try:
        web_root = config.get("SickBeard", "web_root")
    except ConfigParser.NoOptionError:
        web_root = ""

    try:
        watch_dir = config.get("SickBeard", "watch_dir")
    except ConfigParser.NoOptionError:
        watch_dir = ""

    try:
        failed_fork = int(config.get("SickBeard", "failed_fork"))
    except (ConfigParser.NoOptionError, ValueError):
        failed_fork = 0

    try:
        transcode = int(config.get("Transcoder", "transcode"))
    except (ConfigParser.NoOptionError, ValueError):
        transcode = 0

    try:
        delete_failed = int(config.get("SickBeard", "delete_failed"))
    except (ConfigParser.NoOptionError, ValueError):
        delete_failed = 0
    try:
        delay = float(config.get("SickBeard", "delay"))
    except (ConfigParser.NoOptionError, ValueError):
        delay = 0

    mediaContainer = (config.get("Extensions", "mediaExtensions")).split(',')
    minSampleSize = int(config.get("Extensions", "minSampleSize"))

    process_all_exceptions(nzbName.lower(), dirName)

    if nzbName != "Manual Run":
        # Now check if movie files exist in destination:
        video = int(0)
        for dirpath, dirnames, filenames in os.walk(dirName):
            for file in filenames:
                filePath = os.path.join(dirpath, file)
                fileExtension = os.path.splitext(file)[1]
                if fileExtension in mediaContainer:  # If the file is a video file
                    if is_sample(filePath, nzbName, minSampleSize):
                        Logger.debug("Removing sample file: %s", filePath)
                        os.unlink(filePath)  # remove samples
                    else:
                        video = video + 1
        if video > 0:  # Check that a video exists. if not, assume failed.
            flatten(
                dirName
            )  # to make sure SickBeard can find the video (not in sub-folder)
        else:
            Logger.warning(
                "No media files found in directory %s. Processing this as a failed download",
                dirName)
            status = int(1)
            failed = True

    if watch_dir != "":
        dirName = watch_dir

    params = {}

    params['quiet'] = 1

    # if you have specified you are using development branch from fork https://github.com/Tolstyak/Sick-Beard.git
    if failed_fork:
        params['dirName'] = dirName
        if nzbName != None:
            params['nzbName'] = nzbName
        params['failed'] = failed
        if status == 0:
            Logger.info(
                "The download succeeded. Sending process request to SickBeard's failed branch"
            )
        else:
            Logger.info(
                "The download failed. Sending 'failed' process request to SickBeard's failed branch"
            )

    # this is our default behaviour to work with the standard Master branch of SickBeard
    else:
        params['dir'] = dirName
        if nzbName != None:
            params['nzbName'] = nzbName
        # the standard Master bamch of SickBeard cannot process failed downloads. So Exit here.
        if status == 0:
            Logger.info(
                "The download succeeded. Sending process request to SickBeard")
        else:
            Logger.info("The download failed. Nothing to process")
            if delete_failed and os.path.isdir(
                    dirName) and not dirName in ['sys.argv[0]', '/', '']:
                delete(dirName)
            return 0  # Success (as far as this script is concerned)

    if status == 0 and transcode == 1:  # only transcode successful downlaods
        result = Transcoder.Transcode_directory(dirName)
        if result == 0:
            Logger.debug("Transcoding succeeded for files in %s", dirName)
        else:
            Logger.warning("Transcoding failed for files in %s", dirName)

    myOpener = AuthURLOpener(username, password)

    if ssl:
        protocol = "https://"
    else:
        protocol = "http://"

    url = protocol + host + ":" + port + web_root + "/home/postprocess/processEpisode?" + urllib.urlencode(
        params)

    Logger.info(
        "Waiting for %s seconds to allow SB to process newly extracted files",
        str(delay))

    time.sleep(delay)

    Logger.debug("Opening URL: %s", url)

    try:
        urlObj = myOpener.openit(url)
    except:
        Logger.exception("Unable to open URL")
        return 1  # failure

    result = urlObj.readlines()
    for line in result:
        Logger.info("%s", line.rstrip())
    if status != 0 and delete_failed and not dirName in [
            'sys.argv[0]', '/', ''
    ]:
        delete(dirName)
    return 0  # Success
Example #5
0
    try:
        watch_dir = config.get("SickBeard", "watch_dir")
    except ConfigParser.NoOptionError:
        watch_dir = ""

    try:
        failed_fork = int(config.get("SickBeard", "failed_fork"))
    except (ConfigParser.NoOptionError, ValueError):
        failed_fork = 0
    try:
        transcode = int(config.get("Transcoder", "transcode"))
    except (ConfigParser.NoOptionError, ValueError):
        transcode = 0

    process_all_exceptions(nzbName.lower(), dirName)

    # allows manual call of postprocess script if we have specified a watch_dir. Check that here.
    if nzbName == "Manual Run" and watch_dir == "":
        Logger.error("In order to run this script manually you must specify a watch_dir in autoProcessTV.cfg")
        return 1  # failure
    # allows us to specify the default watch directory and call the postproecssing on another PC with different directory structure.
    if watch_dir != "":
        dirName = watch_dir

    params = {}

    params["quiet"] = 1

    # if you have specified you are using development branch from fork https://github.com/Tolstyak/Sick-Beard.git
    if failed_fork:
Example #6
0
def processEpisode(dirName, nzbName=None, failed=False, inputCategory=None):

    status = int(failed)
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
    Logger.info("Loading config from %s", configFilename)

    if not os.path.isfile(configFilename):
        Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
        return 1 # failure

    config.read(configFilename)

    section = "SickBeard"
    if inputCategory != None and config.has_section(inputCategory):
        section = inputCategory

    watch_dir = ""
    host = config.get(section, "host")
    port = config.get(section, "port")
    username = config.get(section, "username")
    password = config.get(section, "password")
    try:
        ssl = int(config.get(section, "ssl"))
    except (ConfigParser.NoOptionError, ValueError):
        ssl = 0

    try:
        web_root = config.get(section, "web_root")
    except ConfigParser.NoOptionError:
        web_root = ""

    try:
        watch_dir = config.get(section, "watch_dir")
    except ConfigParser.NoOptionError:
        watch_dir = ""

    try:
        fork = config.get(section, "fork")
    except ConfigParser.NoOptionError:
        fork = "default"

    try:    
        transcode = int(config.get("Transcoder", "transcode"))
    except (ConfigParser.NoOptionError, ValueError):
        transcode = 0

    try:
        delete_failed = int(config.get(section, "delete_failed"))
    except (ConfigParser.NoOptionError, ValueError):
        delete_failed = 0
    try:
        delay = float(config.get(section, "delay"))
    except (ConfigParser.NoOptionError, ValueError):
        delay = 0

    mediaContainer = (config.get("Extensions", "mediaExtensions")).split(',')
    minSampleSize = int(config.get("Extensions", "minSampleSize"))

    if not fork in SICKBEARD_TORRENT:
        process_all_exceptions(nzbName.lower(), dirName)
        nzbName, dirName = converto_to_ascii(nzbName, dirName)

    if nzbName != "Manual Run" and not fork in SICKBEARD_TORRENT:
        # Now check if movie files exist in destination:
        video = int(0)
        for dirpath, dirnames, filenames in os.walk(dirName):
            for file in filenames:
                filePath = os.path.join(dirpath, file)
                fileExtension = os.path.splitext(file)[1]
                if fileExtension in mediaContainer:  # If the file is a video file
                    if is_sample(filePath, nzbName, minSampleSize):
                        Logger.debug("Removing sample file: %s", filePath)
                        os.unlink(filePath)  # remove samples
                    else:
                        video = video + 1
        if video > 0:  # Check that a video exists. if not, assume failed.
            flatten(dirName) # to make sure SickBeard can find the video (not in sub-folder)
        else:
            Logger.warning("No media files found in directory %s. Processing this as a failed download", dirName)
            status = int(1)
            failed = True

    if watch_dir != "":
        dirName = watch_dir

    params = {}

    params['quiet'] = 1
    if fork in SICKBEARD_DIRNAME:
        params['dirName'] = dirName
    else:
        params['dir'] = dirName

    if nzbName != None:
        params['nzbName'] = nzbName

    if fork in SICKBEARD_FAILED:
        params['failed'] = failed

    if status == 0:
        Logger.info("The download succeeded. Sending process request to SickBeard's %s branch", fork)
    elif fork in SICKBEARD_FAILED:
        Logger.info("The download failed. Sending 'failed' process request to SickBeard's %s branch", fork)
    else:
        Logger.info("The download failed. SickBeard's %s branch does not handle failed downloads. Nothing to process", fork)
        if delete_failed and os.path.isdir(dirName) and not dirName in ['sys.argv[0]','/','']:
            Logger.info("Deleting directory: %s", dirName)
            delete(dirName)
        return 0 # Success (as far as this script is concerned)
    
    if status == 0 and transcode == 1: # only transcode successful downlaods
        result = Transcoder.Transcode_directory(dirName)
        if result == 0:
            Logger.debug("Transcoding succeeded for files in %s", dirName)
        else:
            Logger.warning("Transcoding failed for files in %s", dirName)

    myOpener = AuthURLOpener(username, password)

    if ssl:
        protocol = "https://"
    else:
        protocol = "http://"

    url = protocol + host + ":" + port + web_root + "/home/postprocess/processEpisode?" + urllib.urlencode(params)

    Logger.info("Waiting for %s seconds to allow SB to process newly extracted files", str(delay))

    time.sleep(delay)

    Logger.debug("Opening URL: %s", url)

    try:
        urlObj = myOpener.openit(url)
    except:
        Logger.exception("Unable to open URL")
        return 1 # failure

    result = urlObj.readlines()
    for line in result:
        Logger.info("%s", line.rstrip())
    if status != 0 and delete_failed and not dirName in ['sys.argv[0]','/','']:
        delete(dirName)
    return 0 # Success
Example #7
0
def process(dirName, nzbName=None, status=0, clientAgent = "manual", download_id = "", inputCategory=None):

    status = int(status)
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
    Logger.info("Loading config from %s", configFilename)

    if not os.path.isfile(configFilename):
        Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
        return 1 # failure

    config.read(configFilename)

    section = "CouchPotato"
    if inputCategory != None and config.has_section(inputCategory):
        section = inputCategory

    host = config.get(section, "host")
    port = config.get(section, "port")
    apikey = config.get(section, "apikey")
    delay = float(config.get(section, "delay"))
    method = config.get(section, "method")
    delete_failed = int(config.get(section, "delete_failed"))
    wait_for = int(config.get(section, "wait_for"))

    try:
        ssl = int(config.get(section, "ssl"))
    except (ConfigParser.NoOptionError, ValueError):
        ssl = 0

    try:
        web_root = config.get(section, "web_root")
    except ConfigParser.NoOptionError:
        web_root = ""
        
    try:    
        transcode = int(config.get("Transcoder", "transcode"))
    except (ConfigParser.NoOptionError, ValueError):
        transcode = 0

    try:
        remoteCPS = int(config.get(section, "remoteCPS"))
    except (ConfigParser.NoOptionError, ValueError):
        remoteCPS = 0

    nzbName = str(nzbName) # make sure it is a string
    
    imdbid = get_imdb(nzbName, dirName)

    if ssl:
        protocol = "https://"
    else:
        protocol = "http://"
    # don't delay when we are calling this script manually.
    if nzbName == "Manual Run":
        delay = 0

    baseURL = protocol + host + ":" + port + web_root + "/api/" + apikey + "/"
    
    movie_id = get_movie_info(baseURL, imdbid, download_id) # get the CPS database movie id this movie.
   
    initial_status, clientAgent, download_id, initial_release_status = get_status(baseURL, movie_id, clientAgent, download_id)
    
    process_all_exceptions(nzbName.lower(), dirName)
    nzbName, dirName = converto_to_ascii(nzbName, dirName)

    TimeOut2 = int(wait_for) * 60 # If transfering files across directories, it now appears CouchPotato can take a while to confirm this url request... Try using wait_for timing.
    socket.setdefaulttimeout(int(TimeOut2)) #initialize socket timeout. We may now be able to remove the delays from the wait_for section below?

    if status == 0:
        if transcode == 1:
            result = Transcoder.Transcode_directory(dirName)
            if result == 0:
                Logger.debug("Transcoding succeeded for files in %s", dirName)
            else:
                Logger.warning("Transcoding failed for files in %s", dirName)

        if method == "manage":
            command = "manage.update"
        else:
            command = "renamer.scan"
            if clientAgent != "manual" and download_id != "none":
                if remoteCPS == 1:
                    command = command + "/?downloader=" + clientAgent + "&download_id=" + download_id
                else:
                    command = command + "/?media_folder=" + dirName + "&downloader=" + clientAgent + "&download_id=" + download_id

        url = baseURL + command

        Logger.info("Waiting for %s seconds to allow CPS to process newly extracted files", str(delay))

        time.sleep(delay)

        Logger.debug("Opening URL: %s", url)

        try:
            urlObj = urllib.urlopen(url)
        except:
            Logger.exception("Unable to open URL")
            return 1 # failure

        result = json.load(urlObj)
        Logger.info("CouchPotatoServer returned %s", result)
        if result['success']:
            Logger.info("%s scan started on CouchPotatoServer for %s", method, nzbName)
        else:
            Logger.error("%s scan has NOT started on CouchPotatoServer for %s. Exiting", method, nzbName)
            return 1 # failure

    else:
        Logger.info("Download of %s has failed.", nzbName)
        Logger.info("Trying to re-cue the next highest ranked release")
        
        if not movie_id:
            Logger.warning("Cound not find a movie in the database for release %s", nzbName)
            Logger.warning("Please manually ignore this release and refresh the wanted movie")
            Logger.error("Exiting autoProcessMovie script")
            return 1 # failure

        url = baseURL + "movie.searcher.try_next/?id=" + movie_id

        Logger.debug("Opening URL: %s", url)

        try:
            urlObj = urllib.urlopen(url)
        except:
            Logger.exception("Unable to open URL")
            return 1 # failure

        result = urlObj.readlines()
        for line in result:
            Logger.info("%s", line)

        Logger.info("Movie %s set to try the next best release on CouchPotatoServer", movie_id)
        if delete_failed and not dirName in ['sys.argv[0]','/','']:
            Logger.info("Deleting failed files and folder %s", dirName)
            try:
                shutil.rmtree(dirName)
            except:
                Logger.exception("Unable to delete folder %s", dirName)
        return 0 # success
    
    if nzbName == "Manual Run" or download_id == "none":
        return 0 # success

    # we will now check to see if CPS has finished renaming before returning to TorrentToMedia and unpausing.
    socket.setdefaulttimeout(int(TimeOut)) #initialize socket timeout.

    start = datetime.datetime.now()  # set time for timeout
    pause_for = int(wait_for) * 10 # keep this so we only ever have 6 complete loops. This may not be necessary now?
    while (datetime.datetime.now() - start) < datetime.timedelta(minutes=wait_for):  # only wait 2 (default) minutes, then return.
        movie_status, clientAgent, download_id, release_status = get_status(baseURL, movie_id, clientAgent, download_id) # get the current status fo this movie.
        if movie_status != initial_status:  # Something has changed. CPS must have processed this movie.
            Logger.info("SUCCESS: This movie is now marked as status %s in CouchPotatoServer", movie_status)
            return 0 # success
        time.sleep(pause_for) # Just stop this looping infinitely and hogging resources for 2 minutes ;)
    else:
        if release_status != initial_release_status and release_status != "none":  # Something has changed. CPS must have processed this movie.
            Logger.info("SUCCESS: This release is now marked as status %s in CouchPotatoServer", release_status)
            return 0 # success
        else: # The status hasn't changed. we have waited 2 minutes which is more than enough. uTorrent can resule seeding now. 
            Logger.warning("The movie does not appear to have changed status after %s minutes. Please check CouchPotato Logs", wait_for)
            return 1 # failure
Example #8
0
def processEpisode(dirName, nzbName=None, failed=False):

    status = int(failed)
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
    Logger.info("Loading config from %s", configFilename)

    if not os.path.isfile(configFilename):
        Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
        return 1 # failure

    config.read(configFilename)

    watch_dir = ""
    host = config.get("SickBeard", "host")
    port = config.get("SickBeard", "port")
    username = config.get("SickBeard", "username")
    password = config.get("SickBeard", "password")
    try:
        ssl = int(config.get("SickBeard", "ssl"))
    except (ConfigParser.NoOptionError, ValueError):
        ssl = 0

    try:
        web_root = config.get("SickBeard", "web_root")
    except ConfigParser.NoOptionError:
        web_root = ""

    try:
        watch_dir = config.get("SickBeard", "watch_dir")
    except ConfigParser.NoOptionError:
        watch_dir = ""

    try:
        failed_fork = int(config.get("SickBeard", "failed_fork"))
    except (ConfigParser.NoOptionError, ValueError):
        failed_fork = 0

    try:    
        transcode = int(config.get("Transcoder", "transcode"))
    except (ConfigParser.NoOptionError, ValueError):
        transcode = 0

    try:
        delete_failed = int(config.get("CouchPotato", "delete_failed"))
    except (ConfigParser.NoOptionError, ValueError):
        delete_failed = 0


    process_all_exceptions(nzbName.lower(), dirName)


    #allows manual call of postprocess script if we have specified a watch_dir. Check that here.
    if nzbName == "Manual Run" and watch_dir == "":
        Logger.error("In order to run this script manually you must specify a watch_dir in autoProcessTV.cfg")
        return 1 # failure
    #allows us to specify the default watch directory and call the postproecssing on another PC with different directory structure.
    if watch_dir != "":
        dirName = watch_dir

    params = {}

    params['quiet'] = 1

    # if you have specified you are using development branch from fork https://github.com/Tolstyak/Sick-Beard.git
    if failed_fork:
        params['dirName'] = dirName
        if nzbName != None:
            params['nzbName'] = nzbName
        params['failed'] = failed
        if status == 0:
            Logger.info("The download succeeded. Sending process request to SickBeard's failed branch")
        else:
            Logger.info("The download failed. Sending 'failed' process request to SickBeard's failed branch")
            

    # this is our default behaviour to work with the standard Master branch of SickBeard
    else:
        params['dir'] = dirName
        if nzbName != None:
            params['nzbName'] = nzbName
        # the standard Master bamch of SickBeard cannot process failed downloads. So Exit here.
        if status == 0:
            Logger.info("The download succeeded. Sending process request to SickBeard")
        else:
            Logger.info("The download failed. Nothing to process")
            if delete_failed and not dirName in ['sys.argv[0]','/','']:
                delete(dirName)
            return 0 # Success (as far as this script is concerned)
    
    if status == 0 and transcode == 1: # only transcode successful downlaods
        result = Transcoder.Transcode_directory(dirName)
        if result == 0:
            Logger.debug("Transcoding succeeded for files in %s", dirName)
        else:
            Logger.warning("Transcoding failed for files in %s", dirName)

    myOpener = AuthURLOpener(username, password)

    if ssl:
        protocol = "https://"
    else:
        protocol = "http://"

    url = protocol + host + ":" + port + web_root + "/home/postprocess/processEpisode?" + urllib.urlencode(params)

    Logger.debug("Opening URL: %s", url)

    try:
        urlObj = myOpener.openit(url)
    except:
        Logger.exception("Unable to open URL")
        return 1 # failure

    result = urlObj.readlines()
    for line in result:
        Logger.info("%s", line.rstrip())
    if status != 0 and delete_failed and not dirName in ['sys.argv[0]','/','']:
        delete(dirName)
    return 0 # Success