cleanup variables

fixed flatten.
added test for failure conditions. failed postprocessing allowed only on extract fail.

Fully tested on Win7.
This commit is contained in:
Clinton Hall 2013-02-19 17:39:39 -08:00
commit 982ea2bcec

View file

@ -16,98 +16,79 @@ import autoProcessTV
from nzbToMediaEnv import * from nzbToMediaEnv import *
Logger = logging.getLogger() Logger = logging.getLogger()
logFile = os.path.join(os.path.dirname(sys.argv[0]), "postprocess.log") logFile = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]), "postprocess.log"))
logging.config.fileConfig(os.path.join(os.path.dirname(sys.argv[0]), "logger.conf")) logging.config.fileConfig(os.path.join(os.path.dirname(sys.argv[0]), "logger.conf"))
fileHandler = logging.FileHandler(logFile, encoding='utf-8', delay=True) fileHandler = logging.FileHandler(logFile, encoding='utf-8', delay=True)
fileHandler.formatter = logging.Formatter('%(asctime)s|%(levelname)-7.7s %(message)s', '%H:%M:%S') fileHandler.formatter = logging.Formatter('%(asctime)s|%(levelname)-7.7s %(message)s', '%H:%M:%S')
fileHandler.level = logging.DEBUG fileHandler.level = logging.DEBUG
Logger.addHandler(fileHandler) Logger.addHandler(fileHandler)
Logger.info("TorrentToMedia %s", VERSION) def category_search(inputDirectory, inputCategory, root):
categorySearch = os.path.split(os.path.normpath(inputDirectory)) # Test for blackhole sub-directory
config = ConfigParser.ConfigParser() if categorySearch[1] == inputName:
configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg") Logger.info("SEARCH: Files appear to be in their own directory")
categorySearch2 = os.path.split(os.path.normpath(categorySearch[0]))
Logger.info("Loading config from %s", configFilename) if categorySearch2[1] == movieCategory or categorySearch2[1] == tvCategory:
if not inputCategory:
if not os.path.isfile(configFilename): Logger.info("SEARCH: Determined Category to be: %s", categorySearch2[1])
Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?") inputCategory = categorySearch2[1]
sys.exit(-1) elif not inputCategory:
Logger.error("SEARCH: Could not identify category from the directory structure. please check downlaoder settings")
config.read(configFilename)
TV_Cat = config.get("SickBeard", "category")
TV_dest = os.path.normpath(config.get("SickBeard", "destination"))
Movie_dest = os.path.normpath(config.get("CouchPotato", "destination"))
Movie_Cat = config.get("CouchPotato", "category")
useLink = int(config.get("Torrent", "uselink"))
extractionTool = config.get("Torrent", "extractiontool")
def category_search(Directory, Category, root):
DirBase = os.path.split(os.path.normpath(Directory)) #Test for blackhole sub-directory.
if DirBase[1] == Name:
Logger.info("Files appear to be in their own directory")
DirBase2 = os.path.split(os.path.normpath(DirBase[0]))
if DirBase2[1] == Movie_Cat or DirBase2[1] == TV_Cat:
if not Category:
Logger.info("Determined Category to be: %s", DirBase2[1])
Category = DirBase2[1]
elif not Category:
Logger.error("Could not identify category from the directory structure. please check downlaoder settings.")
sys.exit(-1) sys.exit(-1)
else: else:
pass pass
elif DirBase[1] == Movie_Cat or DirBase[1] == TV_Cat: elif categorySearch[1] == movieCategory or categorySearch[1] == tvCategory:
if os.path.isdir(os.path.join(Directory, Name)): if os.path.isdir(os.path.join(inputDirectory, inputName)):
Logger.info("Found torrent directory %s in category directory %s", os.path.join(Directory, Name), Directory) Logger.info("SEARCH: Found torrent directory %s in category directory %s", os.path.join(inputDirectory, inputName), inputDirectory)
Directory = os.path.join(Directory, Name) inputDirectory = os.path.join(inputDirectory, inputName)
else: else:
Logger.info("The directory passed is the root directory for category %s", DirBase[1]) Logger.info("SEARCH: The directory passed is the root directory for category %s", categorySearch[1])
Logger.warn("You should change settings to download torrents to their own directory if possible") Logger.warn("SEARCH: You should change settings to download torrents to their own directory if possible")
Logger.info("We will try and determine which files to process, individually") Logger.info("SEARCH: We will try and determine which files to process, individually")
root = 1 root = 1
if not Category: if not inputCategory:
Logger.info("Determined Category to be: %s", DirBase[1]) Logger.info("SEARCH: Determined Category to be: %s", categorySearch[1])
Category = DirBase[1] inputCategory = categorySearch[1]
elif not Category: elif not inputCategory:
Logger.error("Could not identify category from the directory structure. please check downlaoder settings.") Logger.error("SEARCH: Could not identify category from the directory structure. please check downlaoder settings")
sys.exit(-1) sys.exit(-1)
else: else:
Logger.info("The directory passed does not appear to include a category or the torrent name") Logger.info("SEARCH: The directory passed does not appear to include a category or the torrent name")
Logger.warn("You should change settings to download torrents to their own directory if possible and include Label/Category directories.") Logger.warn("SEARCH: You should change settings to download torrents to their own directory if possible and include Label/Category directories")
Logger.info("We will try and determine which files to process, individually") Logger.info("SEARCH: We will try and determine which files to process, individually")
root = 1 root = 1
return Directory, Category, root return inputDirectory, inputCategory, root
def is_sample(file_path, Name): def is_sample(filePath, inputName):
# 200 MB in bytes # 200 MB in bytes
SIZE_CUTOFF = 200 * 1024 * 1024 SIZE_CUTOFF = 200 * 1024 * 1024
# ignore 'sample' in files unless 'sample' in Torrent Name # Ignore 'sample' in files unless 'sample' in Torrent Name
if ('sample' in file_path.lower()) and (not 'sample' in Name) and (os.path.getsize(file_path) < SIZE_CUTOFF): if ('sample' in filePath.lower()) and (not 'sample' in inputName) and (os.path.getsize(filePath) < SIZE_CUTOFF):
return True return True
else: else:
return False return False
def copy_link(source, target, useLink, destination): def copy_link(source, target, useLink, outputDestination):
## Create destination folder # Create destination folder
if not os.path.exists(destination): if not os.path.exists(outputDestination):
try: try:
Logger.debug("Creating destination folder: %s", destination) Logger.info("COPYLINK: Creating destination folder: %s", outputDestination)
os.makedirs(destination) os.makedirs(outputDestination)
except Exception, e: except Exception, e:
Logger.error("Not possible to create destination folder: %s", e) Logger.error("COPYLINK: Not possible to create destination folder: %s", e)
return False return False
if useLink: if useLink:
try: try:
Logger.debug("Linking %s to %s", source, target) Logger.info("COPYLINK: Linking %s to %s", source, target)
linktastic.link(source, target) linktastic.link(source, target)
except: except:
if os.path.isfile(target): if os.path.isfile(target):
Logger.info("something went wrong in linktastic.link, but the destination file was created") Logger.info("COPYLINK: Something went wrong in linktastic.link, but the destination file was created")
else: else:
Logger.info("something went wrong in linktastic.link. trying to create a copy") Logger.info("COPYLINK: Something went wrong in linktastic.link, copying instead")
Logger.debug("Copying %s to %s", source, target) Logger.debug("COPYLINK: Copying %s to %s", source, target)
shutil.copy(source, target) shutil.copy(source, target)
else: else:
Logger.debug("Copying %s to %s", source, target) Logger.debug("Copying %s to %s", source, target)
@ -115,105 +96,96 @@ def copy_link(source, target, useLink, destination):
return True return True
def unpack(dirpath, file, destination): def unpack(dirpath, file, destination):
## Using Windows? # Using Windows
if os.name == 'nt': if os.name == 'nt':
Logger.info("EXTRACTOR: We are using Windows")
cmd_7zip = [extractionTool, 'x -y'] cmd_7zip = [extractionTool, 'x -y']
ext_7zip = [".rar",".zip",".tar.gz","tgz",".tar.bz2",".tbz",".tar.lzma",".tlz",".7z",".xz"] ext_7zip = [".rar",".zip",".tar.gz","tgz",".tar.bz2",".tbz",".tar.lzma",".tlz",".7z",".xz"]
EXTRACT_COMMANDS = dict.fromkeys(ext_7zip, cmd_7zip) EXTRACT_COMMANDS = dict.fromkeys(ext_7zip, cmd_7zip)
Logger.info("We are using Windows")
## Using linux? # Using linux
elif os.name == 'posix': elif os.name == 'posix':
Logger.info("EXTRACTOR: We are using *nix")
required_cmds=["unrar", "unzip", "tar", "unxz", "unlzma", "7zr"] required_cmds=["unrar", "unzip", "tar", "unxz", "unlzma", "7zr"]
EXTRACT_COMMANDS = { EXTRACT_COMMANDS = {".rar": ["unrar", "x -o+ -y"], ".zip": ["unzip", ""], ".tar.gz": ["tar", "xzf"], ".tgz": ["tar", "xzf"], ".tar.bz2": ["tar", "xjf"], ".tbz": ["tar", "xjf"], ".tar.lzma": ["tar", "--lzma xf"], ".tlz": ["tar", "--lzma xf"], ".txz": ["tar", "--xz xf"], ".7z": ["7zr", "x"],}
".rar": ["unrar", "x -o+ -y"],
".zip": ["unzip", ""],
".tar.gz": ["tar", "xzf"],
".tgz": ["tar", "xzf"],
".tar.bz2": ["tar", "xjf"],
".tbz": ["tar", "xjf"],
".tar.lzma": ["tar", "--lzma xf"],
".tlz": ["tar", "--lzma xf"],
".txz": ["tar", "--xz xf"],
".7z": ["7zr", "x"],
}
Logger.info("We are using *nix")
## Need to add a check for which commands that can be utilized in *nix systems.. # Need to add a check for which commands that can be utilized in *nix systems..
else: else:
Logger.error("Unknown OS, exiting") Logger.error("EXTRACTOR: Unknown OS, exiting")
ext = os.path.splitext(file) ext = os.path.splitext(file)
fp = os.path.join(dirpath, file) fp = os.path.join(dirpath, file)
if ext[1] in (".gz", ".bz2", ".lzma"): if ext[1] in (".gz", ".bz2", ".lzma"):
## Check if this is a tar # Check if this is a tar
if os.path.splitext(ext[0])[1] == ".tar": if os.path.splitext(ext[0])[1] == ".tar":
cmd = EXTRACT_COMMANDS[".tar" + ext[1]] cmd = EXTRACT_COMMANDS[".tar" + ext[1]]
else: else:
if ext[1] in EXTRACT_COMMANDS: if ext[1] in EXTRACT_COMMANDS:
cmd = EXTRACT_COMMANDS[ext[1]] cmd = EXTRACT_COMMANDS[ext[1]]
else: else:
Logger.debug("Unknown file type: %s", ext[1]) Logger.debug("EXTRACTOR: Unknown file type: %s", ext[1])
return False return False
## Create destination folder # Create destination folder
if not os.path.exists(destination): if not os.path.exists(destination):
try: try:
Logger.debug("Creating destination folder: %s", destination) Logger.debug("EXTRACTOR: Creating destination folder: %s", destination)
os.makedirs(destination) os.makedirs(destination)
except Exception, e: except Exception, e:
Logger.error("Not possible to create destination folder: %s", e) Logger.error("EXTRACTOR: Not possible to create destination folder: %s", e)
return False return False
Logger.info("Extracting %s to %s", fp, destination) Logger.info("Extracting %s to %s", fp, destination)
## Running.. # Running
Logger.debug("Extracting %s %s %s %s", cmd[0], cmd[1], fp, destination) Logger.debug("Extracting %s %s %s %s", cmd[0], cmd[1], fp, destination)
pwd = os.getcwd() # Get our Present Working Directory pwd = os.getcwd() # Get our Present Working Directory
os.chdir(destination) #not all unpack commands accept full paths, so just extract into this directory. os.chdir(destination) # Not all unpack commands accept full paths, so just extract into this directory
if os.name == 'nt': #Windows needs quotes around directory structure if os.name == 'nt': # Windows needs quotes around directory structure
try: try:
run = "\"" + cmd[0] + "\" " + cmd[1] + " \"" + fp + "\"" #windows needs quotes around directories. run = "\"" + cmd[0] + "\" " + cmd[1] + " \"" + fp + "\"" # Windows needs quotes around directories
res = call(run) res = call(run)
if res == 0: if res == 0:
Logger.info("Extraction was successful for %s to %s", fp, destination) Logger.info("EXTRACTOR: Extraction was successful for %s to %s", fp, destination)
else: else:
Logger.info("Extraction failed for %s. 7zip result was %s", fp, res) Logger.info("EXTRACTOR: Extraction failed for %s. 7zip result was %s", fp, res)
except: except:
Logger.error("Extraction failed for %s. Could not call command %s %s", fp, run) Logger.error("EXTRACTOR: Extraction failed for %s. Could not call command %s %s", fp, run)
else: else:
try: try:
if cmd[1] == "": #if calling unzip, we dont want to pass the "" if cmd[1] == "": # If calling unzip, we dont want to pass the ""
res = call([cmd[0], fp]) res = call([cmd[0], fp])
else: else:
res = call([cmd[0], cmd[1], fp]) res = call([cmd[0], cmd[1], fp])
if res == 0: if res == 0:
Logger.info("Extraction was successful for %s to %s", fp, destination) Logger.info("EXTRACTOR: Extraction was successful for %s to %s", fp, destination)
else: else:
Logger.error("Extraction failed for %s. 7zip result was %s", fp, res) Logger.error("EXTRACTOR: Extraction failed for %s. 7zip result was %s", fp, res)
except: except:
Logger.error("Extraction failed for %s. Could not call command %s %s %s %s", fp, cmd[0], cmd[1], fp) Logger.error("EXTRACTOR: Extraction failed for %s. Could not call command %s %s %s %s", fp, cmd[0], cmd[1], fp)
os.chdir(pwd) # Go back to our Original Working Directory os.chdir(pwd) # Go back to our Original Working Directory
return True return True
def flatten(destination): def flatten(outputDestination):
Logger.info("Flattening directory: %s", destination) Logger.info("FLATTEN: Flattening directory: %s", outputDestination)
for dirpath, dirnames, filenames in os.walk(destination): #flatten out the directory to make postprocessing easier. for dirpath, dirnames, filenames in os.walk(outputDestination): # Flatten out the directory to make postprocessing easier
if dirpath == destination: if dirpath == outputDestination:
continue #no need to try and move files in the root destination directory. continue # No need to try and move files in the root destination directory
for filename in filenames: for filename in filenames:
source = os.path.join(dirpath, filename)
target = os.path.join(outputDestination, filename)
try: try:
shutil.move(os.path.join(dirpath, filename), destination) shutil.move(source, target)
except OSError: except OSError:
Logger.info("Could not flatten %s", os.path.join(dirpath, filename)) Logger.info("FLATTEN: Could not flatten %s", source)
removeEmptyFolders(destination) #cleanup empty directories. removeEmptyFolders(outputDestination) # Cleanup empty directories
def removeEmptyFolders(path): def removeEmptyFolders(path):
Logger.info("Removing empty folders in: %s", path) Logger.info("REMOVER: Removing empty folders in: %s", path)
if not os.path.isdir(path): if not os.path.isdir(path):
return return
# remove empty subfolders # Remove empty subfolders
files = os.listdir(path) files = os.listdir(path)
if len(files): if len(files):
for f in files: for f in files:
@ -221,167 +193,158 @@ def removeEmptyFolders(path):
if os.path.isdir(fullpath): if os.path.isdir(fullpath):
removeEmptyFolders(fullpath) removeEmptyFolders(fullpath)
# if folder empty, delete it # If folder empty, delete it
files = os.listdir(path) files = os.listdir(path)
if len(files) == 0: if len(files) == 0:
Logger.debug("Removing empty folder: %s", path) Logger.debug("REMOVER: Removing empty folder: %s", path)
os.rmdir(path) os.rmdir(path)
if len(sys.argv) == 4: Logger.info("TorrentToMedia %s", VERSION)
##You can use the following parameters (UTORRENT): config = ConfigParser.ConfigParser()
## configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
##%F - Name of downloaded file (for single file torrents)
##%D - Directory where files are saved
##%N - Title of torrent
##%P - Previous state of torrent
##%L - Label
##%T - Tracker
##%M - Status message string (same as status column)
##%I - hex encoded info-hash
##%S - State of torrent
##%K - kind of torrent (single|multi)
##
##Where State is one of:
##
##Error - 1
##Checked - 2
##Paused - 3
##Super seeding - 4
##Seeding - 5
##Downloading - 6
##Super seed [F] - 7
##Seeding [F] - 8
##Downloading [F] - 9
##Queued seed - 10
##Finished - 11
##Queued - 12
##Stopped - 13
## We will pass in %D, %N, %L from uTorrent
Logger.info("Script called from utorrent")
Directory = os.path.normpath(sys.argv[1]) ## %D -- Example output: F:\path\to\dir\My.Series.S01E01.720p.HDTV.x264-2HD
Name = sys.argv[2] ## %N -- Example output: My.Series.S01E01.720p.HDTV.x264-2HD
Category = sys.argv[3] ## %L -- Example output: tvseries ## This is the label in uTorrent
elif len(sys.argv) == 3: # assume uTorrent but no label exists. ### TORRENT TO MEDIA ###
Logger.info("Script called from utorrent, without a Label.") if not os.path.isfile(configFilename):
Directory = os.path.normpath(sys.argv[1]) ## %D -- Example output: F:\path\to\dir\My.Series.S01E01.720p.HDTV.x264-2HD Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
Name = sys.argv[2] ## %N -- Example output: My.Series.S01E01.720p.HDTV.x264-2HD
Category = '' #We dont have a category, so assume the last directory is the category for now.
elif len(sys.argv) > 1: #Doesn't match Transmission (1) or uTorrent (4).
Logger.error("The number of arguments passed is %s. Unable to determin the arguments to use; Exiting", len(sys.argv))
sys.exit(-1) sys.exit(-1)
Logger.info("MAIN: Loading config from %s", configFilename)
config.read(configFilename)
if len(sys.argv) > 2:
# We will pass in %D, %N, and %L (if it exists), from uTorrent
# In short pass "/path/to/downloaded/torrent/ name" to TorrentToMedia.py, eg >>>> TorrentToMedia.py /Downloaded/MovieName.2013.BluRay.1080p.x264-10bit.DTS MovieName.2013.BluRay.1080p.x264-10bit.DTS <<<<
inputDirectory = os.path.normpath(sys.argv[1])
inputName = sys.argv[2]
inputCategory = '' # We dont have a category yet
if len (sys.argv) > 3: #assume we have a label.
inputCategory = sys.argv[3] # We dont have a category yet
elif os.getenv('TR_TORRENT_DIR'):
# We will pass in %TR_TORRENT_DIR% %TR_TORRENT_NAME% from Transmission
# In short pass "/path/to/downloaded/torrent/ name" to TorrentToMedia.py, eg >>>> TorrentToMedia.py /Downloaded/MovieName.2013.BluRay.1080p.x264-10bit.DTS MovieName.2013.BluRay.1080p.x264-10bit.DTS <<<<
inputDirectory = os.path.normpath(os.getenv('TR_TORRENT_DIR'))
inputName = os.getenv('TR_TORRENT_NAME')
inputCategory = '' # We dont have a category yet
else: else:
##test for Transmission here. Logger.error("MAIN: There was a problem loading variables: Exiting")
#TR_APP_VERSION
#TR_TIME_LOCALTIME
#TR_TORRENT_DIR
#TR_TORRENT_HASH
#TR_TORRENT_ID
#TR_TORRENT_NAME
try:
Directory = os.path.normpath(os.getenv('TR_TORRENT_DIR'))
Name = os.getenv('TR_TORRENT_NAME')
Logger.info("Script called from Transmission")
except:
Logger.error("There was a problem loading variables from Transmission: Exiting")
sys.exit(-1) sys.exit(-1)
Category = '' #We dont have a category, so assume the last directory is the category for now.
Logger.debug("Received Directory: %s", Directory) #### Main routine starts here.
Logger.debug("Received Torrent Name: %s", Name)
Logger.debug("Received Category: %s", Category)
status = 1 # we start as "failed" until we verify movie file in destination Logger.debug("MAIN: Received Directory: %s | Name: %s | Category: %s", inputDirectory, inputName, inputCategory)
root = 0
video = 0
video2 = 0
Directory, Category, root = category_search(Directory, Category, root) # confirm the catgeogy by parsing directory structure. # Sick-Beard
tvCategory = config.get("SickBeard", "category")
tvDestination = os.path.normpath(config.get("SickBeard", "outputDirectory"))
# CouchPotatoServer
movieCategory = config.get("CouchPotato", "category")
movieDestination = os.path.normpath(config.get("CouchPotato", "outputDirectory"))
# Torrent specific
useLink = int(config.get("Torrent", "useLink"))
extractionTool = os.path.normpath(config.get("Torrent", "extractionTool"))
compressedContainer = config.get("Torrent", "compressedExtentions")
mediaContainer = config.get("Torrent", "mediaExtentions")
metaContainer = config.get("Torrent", "metaExtentions")
if Category == Movie_Cat: status = int(1) # We start as "failed" until we verify movie file in destination
destination = os.path.join(Movie_dest, Name) root = int(0)
elif Category == TV_Cat: video = int(0)
destination = os.path.join(TV_dest, Name) video2 = int(0)
failed_link = int(0)
failed_extract = int(0)
inputDirectory, inputCategory, root = category_search(inputDirectory, inputCategory, root) # Confirm the catgeogy by parsing directory structure
if inputCategory == movieCategory:
outputDestination = os.path.normpath(os.path.join(movieDestination, inputName))
elif inputCategory == tvCategory:
outputDestination = os.path.normpath(os.path.join(tvDestination, inputName))
else: else:
Logger.info("Category of %s does not match either %s or %s: Exiting", Category, Movie_Cat, TV_Cat) Logger.error("MAIN: Category of %s does not match either %s or %s: Exiting", inputCategory, movieCategory, tvCategory)
sys.exit(-1) sys.exit(-1)
packed_files = ['.zip', '.rar', '.7z', '.gz', '.bz', '.tar', '.arj'] Logger.debug("MAIN: Scanning files in directory: %s", inputDirectory)
video_files = ['.mkv', '.avi', '.divx', '.xvid', '.mov', '.wmv', '.mp4', '.mpg', '.mpeg', '.vob', '.iso'] for dirpath, dirnames, filenames in os.walk(inputDirectory):
meta_files = ['.nfo', '.sub', '.srt', '.jpg', '.gif']
Logger.debug("scanning files in directory: %s", Directory)
for dirpath, dirnames, filenames in os.walk(Directory):
for file in filenames: for file in filenames:
if root == 1: if root == 1:
Logger.debug("Looking for %s in filename", Name) Logger.debug("MAIN: Looking for %s in filename", inputName)
if (Name in file) or (os.path.splitext(file)[0] in Name): if (inputName in file) or (os.path.splitext(file)[0] in inputName):
pass #This file does match the Torrent name pass # This file does match the Torrent name
logger.debug("Found file %s that matches Torrent Name %s", file, Name) Logger.debug("Found file %s that matches Torrent Name %s", file, inputName)
else: else:
continue #This file does not match the Torrent name. Skip it continue # This file does not match the Torrent name, skip it
file_path = os.path.join(dirpath, file) filePath = os.path.join(dirpath, file)
file_ext = os.path.splitext(file)[1] fileExtention = os.path.splitext(file)[1]
if file_ext in video_files: #if the file is a video file. if fileExtention in mediaContainer: # If the file is a video file
if is_sample(file_path, Name): if is_sample(filePath, inputName): # Ignore samples
Logger.info("file %s is a sample file. Ignoring", file_path) Logger.info("MAIN: Ignoring %s sample file. Ignoring", filePath)
continue #ignore samples
video = video + 1
source = file_path
target = os.path.join(destination, file)
Logger.info("Found video file %s.", file)
state = copy_link(source, target, useLink, destination)
if state == False:
Logger.info("Failed to link file %s.", file)
elif file_ext in meta_files:
source = file_path
target = os.path.join(destination, file)
Logger.info("Found metadata file %s.", file)
state = copy_link(source, target, useLink, destination)
if state == False:
Logger.info("Failed to link file %s.", file)
elif file_ext in packed_files:
Logger.info("Found packed file %s.", file)
source = file_path
target = os.path.join(destination, file)
state = unpack(dirpath, file, destination)
if state == False:
Logger.info("Failed to unpack file %s.", file)
else:
Logger.info("Unknown file type %s for file %s. Ignoring", file_ext, file_path)
continue continue
flatten(destination) else:
video = video + 1
source = filePath
target = os.path.join(outputDestination, file)
Logger.info("MAIN: Found video file %s in %s", fileExtention, filePath)
state = copy_link(source, target, useLink, outputDestination)
if state == False:
Logger.info("MAIN: Failed to link file %s", file)
failed_link = 1
elif fileExtention in metaContainer:
source = filePath
target = os.path.join(outputDestination, file)
Logger.info("MAIN: Found metadata file %s for file %s", fileExtention, filePath)
state = copy_link(source, target, useLink, outputDestination)
if state == False:
Logger.info("MAIN: Failed to link file %s", file)
failed_link = 1
elif fileExtention in compressedContainer:
Logger.info("MAIN: Found compressed archive %s for file %s", fileExtention, filePath)
source = filePath
target = os.path.join(outputDestination, file)
state = unpack(dirpath, file, outputDestination)
if state == False:
Logger.info("MAIN: Failed to unpack file %s", file)
failed_extract = 1
else:
Logger.info("MAIN: Ignoring unknown filetype %s for file %s", fileExtention, filePath)
continue
flatten(outputDestination)
#now check if movie files exist in destination: # Now check if movie files exist in destination:
for dirpath, dirnames, filenames in os.walk(destination): for dirpath, dirnames, filenames in os.walk(outputDestination):
for file in filenames: for file in filenames:
file_path = os.path.join(dirpath, file) filePath = os.path.join(dirpath, file)
file_ext = os.path.splitext(file)[1] fileExtention = os.path.splitext(file)[1]
if file_ext in video_files: #if the file is a video file. if fileExtention in mediaContainer: # If the file is a video file
if is_sample(file_path, Name): if is_sample(filePath, inputName):
Logger.info("file %s is a sample file. Removing", file_path) Logger.info("file %s is a sample file. Removing", filePath)
os.unlink(file_path) #remove samples os.unlink(filePath) #remove samples
else: else:
video2 = video2 + 1 video2 = video2 + 1
if video2 >= video and video2 > 0: #check that all video files were moved. if video2 >= video and video2 > 0: # Check that all video files were moved
status = 0 status = 0
status = int(status) status = int(status) #just to be safe.
if status == 0: if status == 0:
Logger.info("calling autoProcess script for successful download") 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: else:
Logger.info("calling autoProcess script for failed download") Logger.info("MAIN: Something failed! Please check logs. Exiting")
## Now we pass off to CouchPotato or SickBeard. sys.exit(-1)
## log this output.
old_stdout = sys.stdout ## Still crude, but we wat to capture this for now. # 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
log_file = open(logFile,"a+") log_file = open(logFile,"a+")
sys.stdout = log_file sys.stdout = log_file
if Category == Movie_Cat: if inputCategory == movieCategory:
autoProcessMovie.process(destination, Name, status) Logger.info("MAIN: Calling postprocessing script for CouchPotatoServer")
elif Category == TV_Cat: autoProcessMovie.process(outputDestination, inputName, status)
autoProcessTV.processEpisode(destination, Name, status) elif inputCategory == tvCategory:
Logger.info("MAIN: Calling postprocessing script for Sick-Beard")
autoProcessTV.processEpisode(outputDestination, inputName, status)
sys.stdout = old_stdout sys.stdout = old_stdout
log_file.close() log_file.close()