Ejemplo n.º 1
0
src = os.path.normcase(os.path.normpath(sys.argv[1]))
utDownloadDir = os.path.normcase(os.path.normpath(config.get('uTorrent', 'download_dir')))
processDir = None
if os.path.isfile(src):
    parent = os.path.dirname(src)
    if parent == utDownloadDir:
        # We need to move a file to a tmp dir then let SB process that dir
        # Why? If SB is set to _not_ keep originals after a rename then it will
        # attempt to nuke the dir the file was processed from, which can cause
        # all sorts of headaches with uTorrent
        tdir = tempfile.mkdtemp('', 'tmp_', parent)
        shutil.move(src, tdir)
        processDir = tdir
    else:
        # A subdir was created for the single file torrent; just process that dir then
        processDir = parent
elif os.path.isdir(src) and src != utDownloadDir:
    # A multi file torrent in its own dir
    processDir = sys.argv[1]
elif src == utDownloadDir:
    # We CANNOT process the defined uTorrent download dir or else we may nuke it!
    print 'ERROR: Cannot process defined uTorrent download dir; check your settings! [%s]' % src
else:
    print 'ERROR: Unknown argument type! [%s]' % src

if processDir != None:
    processDir = os.path.abspath(processDir)
    print 'Processing: %s' % processDir
    autoProcessTV.processEpisode(processDir)

Ejemplo n.º 2
0
    download_final_dir = sys.argv[1]

# 2  The original name of the NZB file
org_NZB_name = sys.argv[2] if len(sys.argv) > 3 else None

# 3  Clean version of the job name (no path info and ".nzb" removed)
clean_NZB_file = sys.argv[3] if len(sys.argv) > 4 else None

# 4  Indexer's report number (if supported)
indexer_report = sys.argv[4] if len(sys.argv) > 5 else None

# 5  User-defined category
sab_user_category = sys.argv[5] if len(sys.argv) > 6 else None

# 6  Group that the NZB was posted in e.g. alt.binaries.x
group_NZB = sys.argv[6] if len(sys.argv) > 7 else None

# 7  Status of post processing. 0 = OK, 1=failed verification, 2=failed unpack, 3=1+2
sab_post_processing_status = sys.argv[7] if len(sys.argv) > 8 else None

filepath = "C:/Program Files (x86)/SABnzbd/custom scripts/rename.bat"
print download_final_dir
p = subprocess.Popen([filepath, download_final_dir], shell=True, stdout = subprocess.PIPE)
while True:
  line = p.stdout.readline()
  if not line: break
  print (line.strip())

# Only final_dir and org_NZB_name are being used to process episodes
autoProcessTV.processEpisode(download_final_dir, org_NZB_name)
Ejemplo n.º 3
0
#!/usr/bin/env python2

# Author: Nic Wolfe <*****@*****.**>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Sick Beard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Sick Beard.  If not, see <http://www.gnu.org/licenses/>.


import sys

import autoProcessTV

if len(sys.argv) < 4:
    print "No folder supplied - is this being called from HellaVCR?"
    sys.exit()
else:
    autoProcessTV.processEpisode(sys.argv[3], sys.argv[2])
Ejemplo n.º 4
0
    password = config.get("Transmission", "password")
    output = os.path.join(config.get("Transmission", "output"), type)
    

    tc = trpc.Client(host, port, user, password)
    torrent = tc.get_torrents(hash)[0]
    for each in torrent.files().values():
        if each['completed'] == each['size']:
            if each['name'].endswith(('.rar','.avi','.mkv','.mp4')) and 'sample' not in each['name'].lower() and '/subs' not in each['name'].lower():
                rarfile = os.path.join(dir, each['name'])
                if each['name'].endswith('.rar'):
                    file = os.path.basename(each['name'])
                    if 'part' not in each['name'] or 'part01' in each['name']:
                        logger.info('Extracting {}...'.format(rarfile))
                        retcode = subprocess.call(['7z', 'x', rarfile, '-aos', '-o' + output])
                        if retcode == 0:
                            logger.info('Successfully extracted {}'.format(rarfile))
                            if 'tv_shows' in type:
                                autoProcessTV.processEpisode(output)
                        else:
                            logger.error('Cannot extract {}'.format(rarfile))
                else:
                    file = os.path.basename(each['name'])
                    os.link(rarfile, os.path.join(output, file))
                    logger.info('Successfully created symlink to {}'.format(rarfile))
                    if 'tv_shows' in type:
                        autoProcessTV.processEpisode(output, file)

except KeyError, e:
    logger.error("Environment Variables not supplied - is this being called from Transmission?")
    sys.exit(1)
#!/usr/bin/python
import sys
import urllib
import autoProcessTV

if len(sys.argv) != 4:
    print "Wrong number of arguments - is this being called from rtorrent?"
    sys.exit()

filePath = "".join(sys.argv[1].replace("/download/",
                                       "/complete/").rpartition("/")[:2])
fileName = sys.argv[2]
fileLabel = urllib.unquote_plus(sys.argv[3])

if fileLabel == "tv/sickbeard":
    autoProcessTV.processEpisode(filePath, fileName)
Ejemplo n.º 6
0
                        returnCode7z = subprocess.call(
                            ['7z', 'x', filePath, '-aos', '-o' + dir])
                    except:
                        returnCode7z = -2
                    if returnCode7z != 0:
                        try:
                            returnCodeUnrar = subprocess.call(
                                ['unrar', 'x', filePath, dir])
                        except:
                            returnCodeUnrar = -2
                    if returnCode7z == -2 and returnCodeUnrar == -2:
                        logger.error(
                            loggerHeader +
                            "Cannot find 7z or unrar on your shell path")
                        sys.exit(1)

                    if returnCode7z != 0 and returnCodeUnrar != 0:
                        logger.error(loggerHeader +
                                     "Unable to extract {}".format(file))
                    else:
                        logger.info(loggerHeader +
                                    "Successfully extracted {}".format(file))
                        autoProcessTV.processEpisode(dir)
            else:
                autoProcessTV.processEpisode(dir)
    logger.info(loggerHeader + "Processing from uTorrent finished.")
    sys.exit(0)
except Exception, e:
    logger.error(str(e))
    sys.exit(1)
Ejemplo n.º 7
0
#!/usr/bin/env python2

# Author: Nic Wolfe <*****@*****.**>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickGear.
#
# SickGear is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickGear is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with SickGear.  If not, see <http://www.gnu.org/licenses/>.


import sys

import autoProcessTV

if len(sys.argv) < 4:
    print "No folder supplied - is this being called from HellaVCR?"
    sys.exit()
else:
    autoProcessTV.processEpisode(sys.argv[3], sys.argv[2])
Ejemplo n.º 8
0
try:
    download_dir = config.get("Transmission", "download_dir")
except (ConfigParser.NoOptionError, ValueError):
    print "No download_dir supplied for Transmission autoProcessTV.cfg"
    sys.exit(-1)

try:
    tc = transmissionrpc.Client(host, port=port, user=username, password=password)
except transmissionrpc.TransmissionError, e:
    print "Unknown failure! Transmission return text is: " + str(e)
    sys.exit(-1)

try:
    trans_dir = os.getenv("TR_TORRENT_DIR")
    trans_name = os.getenv("TR_TORRENT_NAME")
    trans_hash = os.getenv("TR_TORRENT_HASH")
except Exception, e:
    print e
    sys.exit(-1)

print trans_dir
print trans_name
print trans_hash

##start processing here
if download_dir == trans_dir:
    print tc.info(trans_hash)
    tc.stop(trans_hash)
    tc.remove(trans_hash)
    autoProcessTV.processEpisode(trans_dir, trans_name)
Ejemplo n.º 9
0
# 0  sys.argv[0] is the name of this script

# 1  The final directory of the job (full path)
if len(sys.argv) < 2:
    print("No folder supplied - is this being called from SABnzbd?")
    sys.exit(1)
else:
    download_final_dir = sys.argv[1]

# 2  The original name of the NZB file
org_NZB_name = sys.argv[2] if len(sys.argv) > 3 else None

# 3  Clean version of the job name (no path info and ".nzb" removed)
clean_NZB_file = sys.argv[3] if len(sys.argv) > 4 else None

# 4  Indexer's report number (if supported)
indexer_report = sys.argv[4] if len(sys.argv) > 5 else None

# 5  User-defined category
sab_user_category = sys.argv[5] if len(sys.argv) > 6 else None

# 6  Group that the NZB was posted in e.g. alt.binaries.x
group_NZB = sys.argv[6] if len(sys.argv) > 7 else None

# 7  Status of post processing. 0 = OK, 1=failed verification, 2=failed unpack, 3=1+2
sab_post_processing_status = sys.argv[7] if len(sys.argv) > 8 else None

# Only final_dir and org_NZB_name are being used to process episodes
autoProcessTV.processEpisode(download_final_dir, org_NZB_name)
Ejemplo n.º 10
0
    os.chdir(destFolder)
    currentFolder = os.getcwd()
    print 100 * '-'
    print ""

# Add multimedia files in the Syno DLNA if the option has been enabled
if (IndexInSynoDLNA == True) & (SickBeardPostProcessing == False):
    print 100 * '-'
    addToSynoIndex(currentFolder)
    print ""
    print 100 * '-'
# Send to SickBeard for post-processing
elif (IndexInSynoDLNA == False) & (SickBeardPostProcessing == True):
    print 100 * '-'
    print "Launching SickBeard post-processing..."
    autoProcessTV.processEpisode(currentFolder)
    print "SickBeard post-processing done!"
    print ""
    print 100 * '-'
# Display error message + advise if both options are enabled
elif (IndexInSynoDLNA == True) & (SickBeardPostProcessing == True):
    print 100 * '#'
    print "IndexInSynoDLNA and SickBeardPostProcessing options are exclusive"
    print "Please check your configuration"
    print ""
    print "If you want to have both options enables at the same time, please processed as follow:"
    print " 1- Enable only SickBeardPostProcessing option"
    print " 2- In SickBeard GUI -> Config -> Notifications -> Enable 'Synology Indexer'"
    print 100 * '#'
    sys.exit(1)
Ejemplo n.º 11
0
#!/usr/bin/env python2.7

# Created these simple scripts to import into SickRage
# only using the API key
#
# Based on the work of Nic Wolfe <*****@*****.**>
# URL: http://code.google.com/p/SickRage/


import sys
import autoProcessTV

if len(sys.argv) < 2:
    print 'No folder to process supplied!'
    sys.exit()
elif len(sys.argv) > 2:
    print 'Only 1 argument allowed!'
    sys.exit()
else:
    autoProcessTV.processEpisode(sys.argv[1])
Ejemplo n.º 12
0
                filePath = os.path.join(dir, file)
                if 'part' not in file.lower() or 'part01' in file.lower():
                    returnCode7z = -1
                    returnCodeUnrar = -1
                    try:
                        returnCode7z = subprocess.call(['7z', 'x', filePath, '-aos', '-o' + dir])
                    except:
                        returnCode7z = -2
                    if returnCode7z != 0 :
                        try: 
                            returnCodeUnrar = subprocess.call(['unrar', 'x', filePath, dir])
                        except:
                            returnCodeUnrar = -2
                    if returnCode7z == -2 and returnCodeUnrar == -2:
                        logger.error(loggerHeader + "Cannot find 7z or unrar on your shell path")
                        sys.exit(1)
                        
                    if returnCode7z != 0 and returnCodeUnrar != 0:
                        logger.error(loggerHeader + "Unable to extract {}".format(file))
                    else:
                        logger.info(loggerHeader + "Successfully extracted {}".format(file))
                        autoProcessTV.processEpisode(dir)            
            else:
                autoProcessTV.processEpisode(dir)  
    logger.info(loggerHeader + "Processing from uTorrent finished.")
    sys.exit(0)
except Exception, e:
    logger.error(str(e))
    sys.exit(1)

Ejemplo n.º 13
0
from nzbToMediaEnv import *

print "nzbToSickBeard %s" % VERSION

# SABnzbd
if len(sys.argv) == 8:
# 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
        print "Script triggered from SABnzbd, starting autoProcessTV..."
        autoProcessTV.processEpisode(sys.argv[1], sys.argv[2], sys.argv[7])

# NZBGet
elif len(sys.argv) == 4:
# NZBGet argv:
# 1  The final directory of the job (full path)
# 2  The original name of the NZB file
# 3  The status of the download: 0 == successful
	print "Script triggered from NZBGet, starting autoProcessTV..."

	autoProcessTV.processEpisode(sys.argv[1], sys.argv[2], sys.argv[3])

else:
	print "Invalid number of arguments received from client."
	print "Running autoProcessTV as a manual run..."
	autoProcessTV.processEpisode('Manual Run', 'Manual Run', 0)
Ejemplo n.º 14
0
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Sick Beard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Sick Beard.  If not, see <http://www.gnu.org/licenses/>.

import sys
import autoProcessTV

if len(sys.argv) < 8:
    print "Not enough arguments received from SABnzbd."
    sys.exit()
else:
    status = int(sys.argv[7])
    autoProcessTV.processEpisode(sys.argv[1], sys.argv[2], status)

# 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
Ejemplo n.º 15
0
    # 2  The original name of the NZB file
    # 3  The status of the download: 0 == successful
    # 4  User-defined category
    Logger.info("MAIN: Script triggered from NZBGet")
    nzbDir, inputName, status, inputCategory = (sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
else: # only CPS supports this manual run for now.
    Logger.warn("MAIN: Invalid number of arguments received from client.")
    Logger.info("MAIN: Running autoProcessMovie as a manual run...")
    nzbDir, inputName, status, inputCategory = ('Manual Run', 'Manual Run', 0, cpsCategory)

if inputCategory == cpsCategory:
    Logger.info("MAIN: Calling CouchPotatoServer to post-process: %s", inputName)
    result = autoProcessMovie.process(nzbDir, inputName, status)
elif inputCategory == sbCategory:
    Logger.info("MAIN: Calling Sick-Beard to post-process: %s", inputName)
    result = autoProcessTV.processEpisode(nzbDir, inputName, status)
elif inputCategory == hpCategory:
    Logger.info("MAIN: Calling HeadPhones to post-process: %s", inputName)
    result = autoProcessMusic.process(nzbDir, inputName, status)
elif inputCategory == mlCategory:
    Logger.info("MAIN: Calling Mylar to post-process: %s", inputName)
    result = autoProcessComics.processEpisode(nzbDir, inputName, status)
elif inputCategory == gzCategory:
    Logger.info("MAIN: Calling Gamez to post-process: %s", inputName)
    result = autoProcessGames.process(nzbDir, inputName, status)

if result == 0:
    Logger.info("MAIN: The autoProcess* script completed successfully.")
else:
    Logger.info("MAIN: A problem was reported in the autoProcess* script.")
    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)
                if MkvtoMp4(settings).validSource(inputfile):
                    converter.process(inputfile)

    autoProcessTV.processEpisode(converter.output_dir)
    if os.path.exists(settings.output_dir) and delete_dir:
        try:
            os.rmdir(converter.output_dir)
        except:
            print "Unable to delete temporary conversion directory"

else:
    print "Incorrect label, ignoring"
Ejemplo n.º 17
0
                                video2 = video2 + 1
if video2 >= video and video2 > 0: # Check that all video files were moved
        status = 0

status = int(status) #just to be safe.        
if status == 0:
        Logger.info("MAIN: Successful run")
        Logger.debug("MAIN: Calling autoProcess script for successful download.")
elif failed_extract == 1 and failed_link == 0: #failed to extract files only.
        Logger.info("MAIN: Failed to extract a packed file.")
        Logger.debug("MAIN: Assume this to be password protected file.")
        Logger.debug("MAIN: Calling autoProcess script for failed download.")
else:
        Logger.info("MAIN: Something failed! Please check logs. Exiting")
        sys.exit(-1)
       
# Now we pass off to CouchPotato or Sick-Beard
# Log this output
old_stdout = sys.stdout  # Still crude, but we wat to capture this for now
logFile = os.path.join(os.path.dirname(sys.argv[0]), "postprocess.log")
log_file = open(logFile,"a+")
sys.stdout = log_file
if inputCategory == movieCategory:  
        Logger.info("MAIN: Calling postprocessing script for CouchPotatoServer")
        autoProcessMovie.process(outputDestination, inputName, status)
elif inputCategory == tvCategory:
        Logger.info("MAIN: Calling postprocessing script for Sick-Beard")
        autoProcessTV.processEpisode(outputDestination, inputName, status)
sys.stdout = old_stdout
log_file.close()
Ejemplo n.º 18
0
            output_file = '{}_encoded.m4v'.format(file_root)
        else:
            output_file = '{}.m4v'.format(file_root)

        cmd = ' '.join([self.executable,
                        '--input="{}"'.format(self.media_file),
                        '--output="{}"'.format(output_file),
                        '--preset="{}"'.format(preset),
                        '-v'])

        logger.info('Starting encode of %s', self.media_file)
        subprocess.call(cmd, shell=True)
        logger.info('Completed encode of %s', self.media_file)

        return output_file


if __name__ == '__main__':
    download_path = sys.argv[1]
    nzb_name = sys.argv[3]
    category = sys.argv[5]

    logger.info('Encoding %s at %s from category %s',
                nzb_name, download_path, category)

    encoder = Encoder(download_path)
    encoder.encode_media_files()

    if category == 'sickbeard':
        autoProcessTV.processEpisode(download_path, nzb_name)
Ejemplo n.º 19
0
def nzbToMedia(nzbStatus):
    script = ""
    result = ""
    if Debug == "yes":
        Logger.debug("Post-Process: Executing external postprocessing with argument %s", nzbStatus) 
    PostProcessStatus = nzbStatus
    # 200 MB in bytes
    SIZE_CUTOFF = 200 * 1024 * 1024
    # Ignore 'sample' in files unless 'sample' in Torrent Name
    for dirpath, dirnames, filenames in os.walk(NZBPP_DIRECTORY):
                for file in filenames:
                    filePath = os.path.join(dirpath, file)
                    if ('sample' in filePath.lower()) and (not 'sample' in NZBPP_NZBNAME) and (os.path.getsize(filePath) < SIZE_CUTOFF):
                        Logger.info("Post-Process: Deleting sample file %s", filePath)
                        os.unlink(filePath)

    if NZBPP_CATEGORY == CouchPotatoCategory:
        if CouchPotato == "yes":
            script = "autoProcessMovie"
            # Call Couchpotato's postprocessing script
            Logger.info("Post-Process: Running CouchPotato's postprocessing script")

            if Debug == "yes":
                Logger.debug("Post-Process: CouchPotato-Script-ARGV1= %s", NZBPP_DIRECTORY)
                Logger.debug("Post-Process: CouchPotato-Script-ARGV2= %s", NZBPP_NZBFILENAME)
                Logger.debug("Post-Process: CouchPotato-Script-ARGV3= %s", PostProcessStatus)
            result = autoProcessMovie.process(NZBPP_DIRECTORY, NZBPP_NZBFILENAME, PostProcessStatus)
        else:
            Logger.debug("Post-Process: Ignored to run CouchPotato's postprocessing script as it is disabled by user")

    if NZBPP_CATEGORY == SickBeardCategory:
        if SickBeard == "yes":
            script = "autoProcessTv"
            # Call SickBeard's postprocessing script
            Logger.info("Post-Process: Running SickBeard's postprocessing script")

            if Debug == "yes":
                Logger.debug("Post-Process: SickBeard-Script-ARGV1= %s", NZBPP_DIRECTORY)
                Logger.debug("Post-Process: SickBeard-Script-ARGV2= %s", NZBPP_NZBFILENAME)
                Logger.debug("Post-Process: SickBeard-Script-ARGV3= %s", PostProcessStatus)
            result = autoProcessTV.processEpisode(NZBPP_DIRECTORY, NZBPP_NZBFILENAME, PostProcessStatus)
        else:
            Logger.debug("Post-Process: Ignored to run SickBeard's postprocessing script as it is disabled by user")

    if NZBPP_CATEGORY == HeadPhonesCategory:
        if HeadPhones == "yes":
            script = "autoProcessMusic"
            # Call HeadPhones' postprocessing script
            Logger.info("Post-Process: Running HeadPhones' postprocessing script")

            if Debug == "yes":
                Logger.debug("Post-Process: HeadPhones-Script-ARGV1= %s", NZBPP_DIRECTORY)
                Logger.debug("Post-Process: HeadPhones-Script-ARGV2= %s", NZBPP_NZBFILENAME)
                Logger.debug("Post-Process: HeadPhones-Script-ARGV3= %s", PostProcessStatus)
            result = autoProcessMusic.process(NZBPP_DIRECTORY, NZBPP_NZBFILENAME, PostProcessStatus)
        else:
            Logger.debug("Post-Process: Ignored to run HeadPhones' postprocessing script as it is disabled by user")

    if NZBPP_CATEGORY == MylarCategory:
        if Mylar == "yes":
            script = "autoProcessComics"
            # Call Mylar's postprocessing script
            Logger.info("Post-Process: Running Mylar's postprocessing script")

            if Debug == "yes":
                Logger.debug("Post-Process: Mylar-Script-ARGV1= %s", NZBPP_DIRECTORY)
                Logger.debug("Post-Process: Mylar-Script-ARGV2= %s", NZBPP_NZBFILENAME)
                Logger.debug("Post-Process: Mylar-Script-ARGV3= %s", PostProcessStatus)
            result = autoProcessComics.processEpisode(NZBPP_DIRECTORY, NZBPP_NZBFILENAME, PostProcessStatus)
        else:
            Logger.debug("Post-Process: Ignored to run Mylar's postprocessing script as it is disabled by user")

    if NZBPP_CATEGORY == GamezCategory:
        if Gamez == "yes":
            script = "autoProcessGames"
            # Call Gamez's postprocessing script
            Logger.info("Post-Process: Running Gamez's postprocessing script")

            if Debug == "yes":
                Logger.debug("Post-Process: Gamez-Script-ARGV1= %s", NZBPP_DIRECTORY)
                Logger.debug("Post-Process: Gamez-Script-ARGV2= %s", NZBPP_NZBFILENAME)
                Logger.debug("Post-Process: Gamez-Script-ARGV3= %s", PostProcessStatus)
            result = autoProcessGames.process(NZBPP_DIRECTORY, NZBPP_NZBFILENAME, PostProcessStatus)
        else:
            Logger.debug("Post-Process: Ignored to run Gamez's postprocessing script as it is disabled by user")

    return script, result
#!/usr/bin/python
import sys
import urllib
import autoProcessTV

if len(sys.argv) != 4:
    print "Wrong number of arguments - is this being called from rtorrent?"
    sys.exit()

filePath = "".join(sys.argv[1].replace("/download/", "/complete/").rpartition("/")[:2])
fileName = sys.argv[2]
fileLabel = urllib.unquote_plus(sys.argv[3])

if fileLabel == "tv/sickbeard":
	autoProcessTV.processEpisode(filePath, fileName)
Ejemplo n.º 21
0
#
# Sick Beard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Sick Beard.  If not, see <http://www.gnu.org/licenses/>.


import sys
import autoProcessTV

if len(sys.argv) < 8:
    print "Not enough arguments received from SABnzbd." 
    sys.exit()
else:
    status = int(sys.argv[7])
    autoProcessTV.processEpisode(sys.argv[1], sys.argv[2], status)


# 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

Ejemplo n.º 22
0
    if os.environ['NZBPP_UNPACKSTATUS'] == '1':
        Logger.warning("MAIN: Unpack failed, setting status \"failed\"")
        status = 1

    if os.environ['NZBPP_UNPACKSTATUS'] == '0' and os.environ['NZBPP_PARSTATUS'] == '0':
        # Unpack was skipped due to nzb-file properties or due to errors during par-check

        if os.environ['NZBPP_HEALTH'] < 1000:
            Logger.warning("MAIN: Download health is compromised and Par-check/repair disabled or no .par2 files found. Setting status \"failed\"")
            Logger.info("MAIN: Please check your Par-check/repair settings for future downloads.")
            status = 1

        else:
            Logger.info("MAIN: Par-check/repair disabled or no .par2 files found, and Unpack not required. Health is ok so handle as though download successful")
            Logger.info("MAIN: Please check your Par-check/repair settings for future downloads.")

    # Check if destination directory exists (important for reprocessing of history items)
    if not os.path.isdir(os.environ['NZBPP_DIRECTORY']):
        Logger.error("MAIN: Nothing to post-process: destination directory %s doesn't exist. Setting status \"failed\"", os.environ['NZBPP_DIRECTORY'])
        status = 1

    # All checks done, now launching the script.
    Logger.info("MAIN: Script triggered from NZBGet, starting autoProcessTV...")
    clientAgent = "nzbget"
    result = autoProcessTV.processEpisode(os.environ['NZBPP_DIRECTORY'], os.environ['NZBPP_NZBFILENAME'])
    sys.exit(POSTPROCESS_SUCCESS)

else:
    print "This script can only be called from NZBGet (11.0 or later)."
    sys.exit(POSTPROCESS_ERROR)
Ejemplo n.º 23
0
					print 'Removed dir:', os.path.join(root, name)
				except:
					print 'Unable to delete dir:', os.path.join(root, name)
					sys.exit(94)

if config.get('sabnzbd', 'moviecat')==job_cat:
	if config.getboolean('movies', 'cleanup'):
		cleanup(final_dir)

if config.get('sabnzbd', 'tvcat')==job_cat:
	if config.getboolean('tv', 'cleanup'):
		cleanup(final_dir)

	if config.getboolean('tv', 'sickbeard'):
		print '\n+Calling Sickbeard+'
		
		nzbname = os.getenv('NZBPP_NZBFILENAME')
		
		try:
			import autoProcessTV
			
			if autoProcessTV.processEpisode.func_code.co_argcount == 2:
				autoProcessTV.processEpisode(final_dir, nzbname)
			elif autoProcessTV.processEpisode.func_code.co_argcount == 3:
				autoProcessTV.processEpisode(final_dir, nzbname, job_res)
		except:
			print 'Could not run sickbeard, is autoProcessTV in the same folder as this script?'
			sys.exit(94)

sys.exit(93)
Ejemplo n.º 24
0
print "to: " + new_folder
print

if not test_mode:
    shutil.move(sys.argv[1], new_folder)

if not test_mode:
    files = os.listdir(new_folder)
else:
    files = os.listdir(sys.argv[1])

parser = NameParser(file_name=True)
for f in files:
    if not test_mode:
        full_path = os.path.join(root, new_folder, f)
    else:
        full_path = os.path.join(root, orig_folder, f)
    if os.path.isfile(full_path):
        file_info = parser.parse(string_replace(f, replace_words))
        file_info.adjust_numbering(episode_delta, season_delta)
        new_f = file_info.__str__()
        if not test_mode:
            shutil.move(full_path, os.path.join(root, new_folder, new_f))
        print f + " renamed to: " + new_f

# pass fixed file/folder to sickbeard
if not test_mode:
    if pass_to_sickbeard:
        import autoProcessTV
        autoProcessTV.processEpisode(new_folder)
Ejemplo n.º 25
0
    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)
                if MkvtoMp4(settings).validSource(inputfile):
                    converter.process(inputfile)

    autoProcessTV.processEpisode(converter.output_dir)
    if os.path.exists(settings.output_dir) and delete_dir:
        try:
            os.rmdir(converter.output_dir)
        except:
            print "Unable to delete temporary conversion directory"

else:
    print "Incorrect label, ignoring"
Ejemplo n.º 26
0
					os.remove(os.path.join(root, name))
					print 'Removed:', os.path.join(root, name)
			for name in dirs:
				try:
					os.rmdir(os.path.join(root, name))
					print 'Removed dir:', os.path.join(root, name)
				except:
					print 'Unable to delete dir:', os.path.join(root, name)

if config.get('sabnzbd', 'moviecat')==job_cat:
	if config.getboolean('movies', 'cleanup'):
		cleanup(final_dir)

if config.get('sabnzbd', 'tvcat')==job_cat:
	if config.getboolean('tv', 'cleanup'):
		cleanup(final_dir)

	if config.getboolean('tv', 'sickbeard'):
		print '\n+Calling Sickbeard+'
		try:
			import autoProcessTV
			
			if autoProcessTV.processEpisode.func_code.co_argcount == 2:
				autoProcessTV.processEpisode(final_dir, sys.argv[2])
			elif autoProcessTV.processEpisode.func_code.co_argcount == 3:
				autoProcessTV.processEpisode(final_dir, sys.argv[2], job_res)
		except:
			print 'Could not run sickbeard, is autoProcessTV in the same folder as this script?'

sys.exit(0)
Ejemplo n.º 27
0
def main(inputDirectory, inputName, inputCategory, inputHash):

    status = int(1)  # 1 = failed | 0 = success
    root = int(0)
    video = int(0)
    video2 = int(0)
    foundFile = int(0)
    deleteOriginal = int(0)
    numCompressed = int(0)
    extractionSuccess = False

    Logger.debug("MAIN: Received Directory: %s | Name: %s | Category: %s", inputDirectory, inputName, inputCategory)

    inputDirectory, inputName, inputCategory, root = category_search(inputDirectory, inputName, inputCategory, root, categories)  # Confirm the category by parsing directory structure

    for category in categories:
        if category == inputCategory:
            outputDestination = os.path.normpath(os.path.join(outputDirectory, category, safeName(inputName)))
            Logger.info("MAIN: Output directory set to: %s", outputDestination)
            break
        else:
            continue

    Logger.debug("MAIN: Scanning files in directory: %s", inputDirectory)      

    now = datetime.datetime.now()
    for dirpath, dirnames, filenames in os.walk(inputDirectory):
        for file in filenames:

            filePath = os.path.join(dirpath, file)
            fileName, fileExtension = os.path.splitext(file)
            targetDirectory = os.path.join(outputDestination, file)

            if root == 1:
                if not foundFile: 
                    Logger.debug("MAIN: Looking for %s in: %s", inputName, file)
                if (safeName(inputName) in safeName(file)) or (safeName(os.path.splitext(file)[0]) in safeName(inputName)) and foundFile == 0:
                    pass  # This file does match the Torrent name
                    foundFile = 1
                    Logger.debug("MAIN: Found file %s that matches Torrent Name %s", file, inputName)
                else:
                    continue  # This file does not match the Torrent name, skip it

            if root == 2:
                Logger.debug("MAIN: Looking for files with modified/created dates less than 5 minutes old.")
                mtime_lapse = now - datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(dirpath, file)))
                ctime_lapse = now - datetime.datetime.fromtimestamp(os.path.getctime(os.path.join(dirpath, file)))
                if (mtime_lapse < datetime.timedelta(minutes=5)) or (ctime_lapse < datetime.timedelta(minutes=5)) and foundFile == 0:
                    pass  # This file does match the date time criteria
                    foundFile = 1
                    Logger.debug("MAIN: Found file %s with date modifed/created less than 5 minutes ago.", file)
                else:
                    continue  # This file has not been recently moved or created, skip it

            if not (inputCategory == cpsCategory or inputCategory == sbCategory): #process all for non-video categories.
                Logger.info("MAIN: Found file %s for category %s", filepath, inputCategory)
                copy_link(filePath, targetDirectory, useLink, outputDestination)
            elif fileExtension in mediaContainer:  # If the file is a video file
                if is_sample(filePath, inputName, minSampleSize):  # Ignore samples
                    Logger.info("MAIN: Ignoring sample file: %s  ", filePath)
                    continue
                else:
                    video = video + 1
                    Logger.info("MAIN: Found video file %s in %s", fileExtension, filePath)
                    try:
                        copy_link(filePath, targetDirectory, useLink, outputDestination)
                    except Exception as e:
                        Logger.error("MAIN: Failed to link file: %s", file)
                        Logger.debug(e)
            elif fileExtension in metaContainer:
                Logger.info("MAIN: Found metadata file %s for file %s", fileExtension, filePath)
                try:
                    copy_link(filePath, targetDirectory, useLink, outputDestination)
                except Exception as e:
                    Logger.error("MAIN: Failed to link file: %s", file)
                    Logger.debug(e)
            elif fileExtension in compressedContainer:
                numCompressed = numCompressed + 1
                if re.search(r'\d+', os.path.splitext(fileName)[1]) and numCompressed > 1: # find part numbers in second "extension" from right, if we have more than 1 compressed file.
                    part = int(re.search(r'\d+', os.path.splitext(fileName)[1]).group())
                    if part == 1: # we only want to extract the primary part.
                        Logger.debug("MAIN: Found primary part of a multi-part archive %s. Extracting", file)                       
                    else:
                        Logger.debug("MAIN: Found part %s of a multi-part archive %s. Ignoring", part, file)
                        continue
                Logger.info("MAIN: Found compressed archive %s for file %s", fileExtension, filePath)
                try:
                    extractor.extract(filePath, outputDestination)
                    extractionSuccess = True # we use this variable to determine if we need to pause a torrent or not in uTorrent (dont need to pause archived content)
                except Exception as e:
                    Logger.warn("MAIN: Extraction failed for: %s", file)
                    Logger.debug(e)
            else:
                Logger.debug("MAIN: Ignoring unknown filetype %s for file %s", fileExtension, filePath)
                continue
    flatten(outputDestination)

    # Now check if movie files exist in destination:
    for dirpath, dirnames, filenames in os.walk(outputDestination):
        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, inputName, minSampleSize):
                    Logger.debug("MAIN: Removing sample file: %s", filePath)
                    os.unlink(filePath)  # remove samples
                else:
                    video2 = video2 + 1
    if video2 >= video and video2 > 0:  # Check that all video files were moved
        status = 0

    # Hardlink solution for uTorrent, need to implent support for deluge, transmission
    if clientAgent == 'utorrent' and extractionSuccess == False and inputHash:
        try:
            Logger.debug("MAIN: Connecting to uTorrent: %s", uTorrentWEBui)
            utorrentClass = UTorrentClient(uTorrentWEBui, uTorrentUSR, uTorrentPWD)
        except Exception as e:
            Logger.error("MAIN: Failed to connect to uTorrent: %s", e)

        # if we are using links with uTorrent it means we need to pause it in order to access the files
        if useLink == 1:
            Logger.debug("MAIN: Stoping torrent %s in uTorrent while processing", inputName)
            utorrentClass.stop(inputHash)
            time.sleep(5)  # Give uTorrent some time to catch up with the change

        # Delete torrent and torrentdata from uTorrent
        if deleteOriginal == 1:
            Logger.debug("MAIN: Deleting torrent %s from uTorrent", inputName)
            utorrentClass.removedata(inputHash)
            utorrentClass.remove(inputHash)
            time.sleep(5)

    processCategories = {cpsCategory, sbCategory, hpCategory, mlCategory, gzCategory}

    if inputCategory and not (inputCategory in processCategories): # no extra processign to be done... yet.
        Logger.info("MAIN: No further processing to be done for category %s.", inputCategory)
        result = 1
    elif status == 0:
        Logger.debug("MAIN: Calling autoProcess script for successful download.")
    else:
        Logger.error("MAIN: Something failed! Please check logs. Exiting")
        sys.exit(-1)

    if inputCategory == cpsCategory:
        Logger.info("MAIN: Calling CouchPotatoServer to post-process: %s", inputName)
        result = autoProcessMovie.process(outputDestination, inputName, status)
    elif inputCategory == sbCategory:
        Logger.info("MAIN: Calling Sick-Beard to post-process: %s", inputName)
        result = autoProcessTV.processEpisode(outputDestination, inputName, status)
    elif inputCategory == hpCategory:
        Logger.info("MAIN: Calling HeadPhones to post-process: %s", inputName)
        result = autoProcessMusic.process(outputDestination, inputName, status)
    elif inputCategory == mlCategory:
        Logger.info("MAIN: Calling Mylar to post-process: %s", inputName)
        result = autoProcessComics.processEpisode(outputDestination, inputName, status)
    elif inputCategory == gzCategory:
        Logger.info("MAIN: Calling Gamez to post-process: %s", inputName)
        result = autoProcessGames.process(outputDestination, inputName, status)

    if result == 1:
        Logger.info("MAIN: A problem was reported in the autoProcess* script. If torrent was pasued we will resume seeding")

    # Hardlink solution for uTorrent, need to implent support for deluge, transmission
    if clientAgent == 'utorrent' and extractionSuccess == False and inputHash and useLink == 1 and deleteOriginal == 0: # we always want to resume seeding, for now manually find out what is wrong when extraction fails
        Logger.debug("MAIN: Starting torrent %s in uTorrent", inputName)
        utorrentClass.start(inputHash)

    Logger.info("MAIN: All done.")
            if each['name'].endswith(
                ('.rar', '.avi', '.mkv',
                 '.mp4')) and 'sample' not in each['name'].lower(
                 ) and '/subs' not in each['name'].lower():
                rarfile = os.path.join(dir, each['name'])
                if each['name'].endswith('.rar'):
                    file = os.path.basename(each['name'])
                    if 'part' not in each['name'] or 'part01' in each['name']:
                        logger.info('Extracting {}...'.format(rarfile))
                        retcode = subprocess.call(
                            ['7z', 'x', rarfile, '-aos', '-o' + output])
                        if retcode == 0:
                            logger.info(
                                'Successfully extracted {}'.format(rarfile))
                            if 'tv_shows' in type:
                                autoProcessTV.processEpisode(output)
                        else:
                            logger.error('Cannot extract {}'.format(rarfile))
                else:
                    file = os.path.basename(each['name'])
                    os.link(rarfile, os.path.join(output, file))
                    logger.info(
                        'Successfully created symlink to {}'.format(rarfile))
                    if 'tv_shows' in type:
                        autoProcessTV.processEpisode(output, file)

except KeyError, e:
    logger.error(
        "Environment Variables not supplied - is this being called from Transmission?"
    )
    sys.exit(1)
Ejemplo n.º 29
0
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickRage.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

import sys

import autoProcessTV

if len(sys.argv) < 2:
    print "No folder supplied - is this being called from SABnzbd?"
    sys.exit()
elif len(sys.argv) >= 8:
    autoProcessTV.processEpisode(sys.argv[1], sys.argv[2], sys.argv[7])
elif len(sys.argv) >= 3:
    autoProcessTV.processEpisode(sys.argv[1], sys.argv[2])
else:
    autoProcessTV.processEpisode(sys.argv[1])
Ejemplo n.º 30
0
    os.chdir(destFolder)
    currentFolder = os.getcwd()
    print 100*'-'
    print ""

# Add multimedia files in the Syno DLNA if the option has been enabled
if (IndexInSynoDLNA == True) & (SickBeardPostProcessing == False):
    print 100*'-'
    addToSynoIndex(currentFolder)
    print ""
    print 100*'-'
# Send to SickBeard for post-processing
elif (IndexInSynoDLNA == False) & (SickBeardPostProcessing == True):
    print 100*'-'
    print "Launching SickBeard post-processing..."
    autoProcessTV.processEpisode(currentFolder)
    print "SickBeard post-processing done!"
    print ""
    print 100*'-'
# Display error message + advise if both options are enabled
elif (IndexInSynoDLNA == True) & (SickBeardPostProcessing == True):
    print 100*'#'
    print "IndexInSynoDLNA and SickBeardPostProcessing options are exclusive"
    print "Please check your configuration"
    print ""
    print "If you want to have both options enables at the same time, please processed as follow:"
    print " 1- Enable only SickBeardPostProcessing option"
    print " 2- In SickBeard GUI -> Config -> Notifications -> Enable 'Synology Indexer'"
    print 100*'#'
    sys.exit(1)