mirror of
https://github.com/clinton-hall/nzbToMedia.git
synced 2025-08-21 13:53:15 -07:00
Merge branch 'nightly' into dev
This commit is contained in:
commit
f467213284
11 changed files with 535 additions and 71 deletions
|
@ -3,6 +3,7 @@
|
|||
import os
|
||||
import time
|
||||
import requests
|
||||
import json
|
||||
import core
|
||||
|
||||
from core.nzbToMediaSceneExceptions import process_all_exceptions
|
||||
|
@ -20,13 +21,13 @@ class autoProcessMovie(object):
|
|||
|
||||
# determine cmd and params to send to CouchPotato to get our results
|
||||
section = 'movies'
|
||||
cmd = "/media.list"
|
||||
cmd = "media.list"
|
||||
if release_id or imdbid:
|
||||
section = 'media'
|
||||
cmd = "/media.get"
|
||||
cmd = "media.get"
|
||||
params['id'] = release_id or imdbid
|
||||
|
||||
url = baseURL + cmd
|
||||
url = "{0}{1}".format(baseURL, cmd)
|
||||
logger.debug("Opening URL: {0} with PARAMS: {1}".format(url, params))
|
||||
|
||||
try:
|
||||
|
@ -103,6 +104,39 @@ class autoProcessMovie(object):
|
|||
|
||||
return results
|
||||
|
||||
def command_complete(self, url, params, headers, section):
|
||||
try:
|
||||
r = requests.get(url, params=params, headers=headers, stream=True, verify=False, timeout=(30, 60))
|
||||
except requests.ConnectionError:
|
||||
logger.error("Unable to open URL: {0}".format(url), section)
|
||||
return None
|
||||
if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]:
|
||||
logger.error("Server returned status {0}".format(r.status_code), section)
|
||||
return None
|
||||
else:
|
||||
try:
|
||||
return r.json()['state']
|
||||
except (ValueError, KeyError):
|
||||
# ValueError catches simplejson's JSONDecodeError and json's ValueError
|
||||
logger.error("{0} did not return expected json data.".format(section), section)
|
||||
return None
|
||||
|
||||
def CDH(self, url2, headers, section="MAIN"):
|
||||
try:
|
||||
r = requests.get(url2, params={}, headers=headers, stream=True, verify=False, timeout=(30, 60))
|
||||
except requests.ConnectionError:
|
||||
logger.error("Unable to open URL: {0}".format(url2), section)
|
||||
return False
|
||||
if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]:
|
||||
logger.error("Server returned status {0}".format(r.status_code), section)
|
||||
return False
|
||||
else:
|
||||
try:
|
||||
return r.json().get("enableCompletedDownloadHandling", False)
|
||||
except ValueError:
|
||||
# ValueError catches simplejson's JSONDecodeError and json's ValueError
|
||||
return False
|
||||
|
||||
def process(self, section, dirName, inputName=None, status=0, clientAgent="manual", download_id="", inputCategory=None, failureLink=None):
|
||||
|
||||
cfg = dict(core.CFG[section][inputCategory])
|
||||
|
@ -110,7 +144,10 @@ class autoProcessMovie(object):
|
|||
host = cfg["host"]
|
||||
port = cfg["port"]
|
||||
apikey = cfg["apikey"]
|
||||
method = cfg["method"]
|
||||
if section == "CouchPotato":
|
||||
method = cfg["method"]
|
||||
else:
|
||||
method = None
|
||||
delete_failed = int(cfg["delete_failed"])
|
||||
wait_for = int(cfg["wait_for"])
|
||||
ssl = int(cfg.get("ssl", 0))
|
||||
|
@ -124,14 +161,25 @@ class autoProcessMovie(object):
|
|||
else:
|
||||
extract = int(cfg.get("extract", 0))
|
||||
|
||||
baseURL = "{0}{1}:{2}{3}/api/{4}".format(protocol, host, port, web_root, apikey)
|
||||
if not server_responding(baseURL):
|
||||
imdbid = find_imdbid(dirName, inputName)
|
||||
if section == "CouchPotato":
|
||||
baseURL = "{0}{1}:{2}{3}/api/{4}/".format(protocol, host, port, web_root, apikey)
|
||||
if section == "Radarr":
|
||||
baseURL = "{0}{1}:{2}{3}/api/command".format(protocol, host, port, web_root)
|
||||
url2 = "{0}{1}:{2}{3}/api/config/downloadClient".format(protocol, host, port, web_root)
|
||||
headers = {'X-Api-Key': apikey}
|
||||
if not apikey:
|
||||
logger.info('No CouchPotato or Radarr apikey entered. Performing transcoder functions only')
|
||||
release = None
|
||||
elif server_responding(baseURL):
|
||||
if section == "CouchPotato":
|
||||
release = self.get_release(baseURL, imdbid, download_id)
|
||||
else:
|
||||
release = None
|
||||
else:
|
||||
logger.error("Server did not respond. Exiting", section)
|
||||
return [1, "{0}: Failed to post-process - {1} did not respond.".format(section, section)]
|
||||
|
||||
imdbid = find_imdbid(dirName, inputName, omdbapikey)
|
||||
release = self.get_release(baseURL, imdbid, download_id)
|
||||
|
||||
# pull info from release found if available
|
||||
release_id = None
|
||||
media_id = None
|
||||
|
@ -216,6 +264,10 @@ class autoProcessMovie(object):
|
|||
logger.debug('Renaming: {0} to: {1}'.format(video, video2))
|
||||
os.rename(video, video2)
|
||||
|
||||
if not apikey: #If only using Transcoder functions, exit here.
|
||||
logger.info('No CouchPotato or Radarr apikey entered. Processing completed.')
|
||||
return [0, "{0}: Successfully post-processed {1}".format(section, inputName)]
|
||||
|
||||
params = {}
|
||||
if download_id:
|
||||
params['downloader'] = downloader or clientAgent
|
||||
|
@ -223,20 +275,29 @@ class autoProcessMovie(object):
|
|||
|
||||
params['media_folder'] = remoteDir(dirName) if remote_path else dirName
|
||||
|
||||
if method == "manage":
|
||||
command = "/manage.update"
|
||||
params = {}
|
||||
else:
|
||||
command = "/renamer.scan"
|
||||
if section == "CouchPotato":
|
||||
if method == "manage":
|
||||
command = "manage.update"
|
||||
params = {}
|
||||
else:
|
||||
command = "renamer.scan"
|
||||
|
||||
url = "{0}{1}".format(baseURL, command)
|
||||
url = "{0}{1}".format(baseURL, command)
|
||||
logger.debug("Opening URL: {0} with PARAMS: {1}".format(url, params), section)
|
||||
logger.postprocess("Starting {0} scan for {1}".format(method, inputName), section)
|
||||
|
||||
logger.debug("Opening URL: {0} with PARAMS: {1}".format(url, params), section)
|
||||
|
||||
logger.postprocess("Starting {0} scan for {1}".format(method, inputName), section)
|
||||
if section == "Radarr":
|
||||
payload = {'name': 'DownloadedMoviesScan', 'path': params['media_folder'], 'downloadClientId': download_id}
|
||||
if not download_id:
|
||||
payload.pop("downloadClientId")
|
||||
logger.debug("Opening URL: {0} with PARAMS: {1}".format(baseURL, payload), section)
|
||||
logger.postprocess("Starting DownloadedMoviesScan scan for {0}".format(inputName), section)
|
||||
|
||||
try:
|
||||
r = requests.get(url, params=params, verify=False, timeout=(30, 1800))
|
||||
if section == "CouchPotato":
|
||||
r = requests.get(url, params=params, verify=False, timeout=(30, 1800))
|
||||
else:
|
||||
r = requests.post(baseURL, data=json.dumps(payload), headers=headers, stream=True, verify=False, timeout=(30, 1800))
|
||||
except requests.ConnectionError:
|
||||
logger.error("Unable to open URL", section)
|
||||
return [1, "{0}: Failed to post-process - Unable to connect to {1}".format(section, section)]
|
||||
|
@ -245,10 +306,20 @@ class autoProcessMovie(object):
|
|||
if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]:
|
||||
logger.error("Server returned status {0}".format(r.status_code), section)
|
||||
return [1, "{0}: Failed to post-process - Server returned status {1}".format(section, r.status_code)]
|
||||
elif result['success']:
|
||||
elif section == "CouchPotato" and result['success']:
|
||||
logger.postprocess("SUCCESS: Finished {0} scan for folder {1}".format(method, dirName), section)
|
||||
if method == "manage":
|
||||
return [0, "{0}: Successfully post-processed {1}".format(section, inputName)]
|
||||
elif section == "Radarr":
|
||||
logger.postprocess("Radarr response: {0}".format(result['state']))
|
||||
try:
|
||||
res = json.loads(r.content)
|
||||
scan_id = int(res['id'])
|
||||
logger.debug("Scan started with id: {0}".format(scan_id), section)
|
||||
Started = True
|
||||
except Exception as e:
|
||||
logger.warning("No scan id was returned due to: {0}".format(e), section)
|
||||
scan_id = None
|
||||
else:
|
||||
logger.error("FAILED: {0} scan was unable to finish for folder {1}. exiting!".format(method, dirName),
|
||||
section)
|
||||
|
@ -260,6 +331,10 @@ class autoProcessMovie(object):
|
|||
if failureLink:
|
||||
reportNzb(failureLink, clientAgent)
|
||||
|
||||
if section == "Radarr":
|
||||
logger.postprocess("FAILED: The download failed. Sending failed download to {0} for CDH processing".format(section), section)
|
||||
return [1, "{0}: Download Failed. Sending back to {1}".format(section, section)] # Return as failed to flag this in the downloader.
|
||||
|
||||
if delete_failed and os.path.isdir(dirName) and not os.path.dirname(dirName) == dirName:
|
||||
logger.postprocess("Deleting failed files and folder {0}".format(dirName), section)
|
||||
rmDir(dirName)
|
||||
|
@ -272,7 +347,7 @@ class autoProcessMovie(object):
|
|||
if release_id:
|
||||
logger.postprocess("Setting failed release {0} to ignored ...".format(inputName), section)
|
||||
|
||||
url = "{url}/release.ignore".format(url=baseURL)
|
||||
url = "{url}release.ignore".format(url=baseURL)
|
||||
params = {'id': release_id}
|
||||
|
||||
logger.debug("Opening URL: {0} with PARAMS: {1}".format(url, params), section)
|
||||
|
@ -295,7 +370,7 @@ class autoProcessMovie(object):
|
|||
|
||||
logger.postprocess("Trying to snatch the next highest ranked release.", section)
|
||||
|
||||
url = "{0}/movie.searcher.try_next".format(baseURL)
|
||||
url = "{0}movie.searcher.try_next".format(baseURL)
|
||||
logger.debug("Opening URL: {0}".format(url), section)
|
||||
|
||||
try:
|
||||
|
@ -323,7 +398,11 @@ class autoProcessMovie(object):
|
|||
timeout = time.time() + 60 * wait_for
|
||||
while time.time() < timeout: # only wait 2 (default) minutes, then return.
|
||||
logger.postprocess("Checking for status change, please stand by ...", section)
|
||||
release = self.get_release(baseURL, imdbid, download_id, release_id)
|
||||
if section == "CouchPotato":
|
||||
release = self.get_release(baseURL, imdbid, download_id, release_id)
|
||||
scan_id = None
|
||||
else:
|
||||
release = None
|
||||
if release:
|
||||
try:
|
||||
if release_id is None and release_status_old is None: # we didn't have a release before, but now we do.
|
||||
|
@ -337,6 +416,18 @@ class autoProcessMovie(object):
|
|||
return [0, "{0}: Successfully post-processed {1}".format(section, inputName)]
|
||||
except:
|
||||
pass
|
||||
elif scan_id:
|
||||
url = "{0}/{1}".format(baseURL, scan_id)
|
||||
command_status = self.command_complete(url, params, headers, section)
|
||||
if command_status:
|
||||
logger.debug("The Scan command return status: {0}".format(command_status), section)
|
||||
if command_status in ['completed']:
|
||||
logger.debug("The Scan command has completed successfully. Renaming was successful.", section)
|
||||
return [0, "{0}: Successfully post-processed {1}".format(section, inputName)]
|
||||
elif command_status in ['failed']:
|
||||
logger.debug("The Scan command has failed. Renaming was not successful.", section)
|
||||
# return [1, "%s: Failed to post-process %s" % (section, inputName) ]
|
||||
|
||||
if not os.path.isdir(dirName):
|
||||
logger.postprocess("SUCCESS: Input Directory [{0}] has been processed and removed".format(
|
||||
dirName), section)
|
||||
|
@ -347,10 +438,13 @@ class autoProcessMovie(object):
|
|||
dirName), section)
|
||||
return [0, "{0}: Successfully post-processed {1}".format(section, inputName)]
|
||||
|
||||
# pause and let CouchPotatoServer catch its breath
|
||||
# pause and let CouchPotatoServer/Radarr catch its breath
|
||||
time.sleep(10 * wait_for)
|
||||
|
||||
# The status hasn't changed. we have waited 2 minutes which is more than enough. uTorrent can resume seeding now.
|
||||
# The status hasn't changed. we have waited wait_for minutes which is more than enough. uTorrent can resume seeding now.
|
||||
if section == "Radarr" and self.CDH(url2, headers, section=section):
|
||||
logger.debug("The Scan command did not return status completed, but complete Download Handling is enabled. Passing back to {0}.".format(section), section)
|
||||
return [status, "{0}: Complete DownLoad Handling is enabled. Passing back to {1}".format(section, section)]
|
||||
logger.warning(
|
||||
"{0} does not appear to have changed status after {1} minutes, Please check your logs.".format(inputName, wait_for),
|
||||
section)
|
||||
|
|
|
@ -60,17 +60,20 @@ class autoProcessTV(object):
|
|||
ssl = int(cfg.get("ssl", 0))
|
||||
web_root = cfg.get("web_root", "")
|
||||
protocol = "https://" if ssl else "http://"
|
||||
|
||||
if not server_responding("{0}{1}:{2}{3}".format(protocol, host, port, web_root)):
|
||||
logger.error("Server did not respond. Exiting", section)
|
||||
return [1, "{0}: Failed to post-process - {1} did not respond.".format(section, section)]
|
||||
|
||||
# auto-detect correct fork
|
||||
fork, fork_params = autoFork(section, inputCategory)
|
||||
|
||||
username = cfg.get("username", "")
|
||||
password = cfg.get("password", "")
|
||||
apikey = cfg.get("apikey", "")
|
||||
|
||||
if server_responding("{0}{1}:{2}{3}".format(protocol, host, port, web_root)):
|
||||
# auto-detect correct fork
|
||||
fork, fork_params = autoFork(section, inputCategory)
|
||||
elif not username and not apikey:
|
||||
logger.info('No SickBeard username or Sonarr apikey entered. Performing transcoder functions only')
|
||||
fork, fork_params = "None", {}
|
||||
else:
|
||||
logger.error("Server did not respond. Exiting", section)
|
||||
return [1, "{0}: Failed to post-process - {1} did not respond.".format(section, section)]
|
||||
|
||||
delete_failed = int(cfg.get("delete_failed", 0))
|
||||
nzbExtractionBy = cfg.get("nzbExtractionBy", "Downloader")
|
||||
process_method = cfg.get("process_method")
|
||||
|
@ -223,6 +226,9 @@ class autoProcessTV(object):
|
|||
[fork_params.pop(k) for k, v in fork_params.items() if v is None]
|
||||
|
||||
if status == 0:
|
||||
if section == "NzbDrone" and not apikey:
|
||||
logger.info('No Sonarr apikey entered. Processing completed.')
|
||||
return [0, "{0}: Successfully post-processed {1}".format(section, inputName)]
|
||||
logger.postprocess("SUCCESS: The download succeeded, sending a post-process request", section)
|
||||
else:
|
||||
core.FAILED = True
|
||||
|
|
|
@ -142,7 +142,7 @@ class ConfigObj(configobj.ConfigObj, Section):
|
|||
if CFG_OLD[section].sections:
|
||||
subsections.update({section: CFG_OLD[section].sections})
|
||||
for option, value in CFG_OLD[section].items():
|
||||
if option in ["category", "cpsCategory", "sbCategory", "hpCategory", "mlCategory", "gzCategory"]:
|
||||
if option in ["category", "cpsCategory", "sbCategory", "hpCategory", "mlCategory", "gzCategory", "raCategory", "ndCategory"]:
|
||||
if not isinstance(value, list):
|
||||
value = [value]
|
||||
|
||||
|
@ -255,10 +255,14 @@ class ConfigObj(configobj.ConfigObj, Section):
|
|||
try:
|
||||
if 'NZBPO_NDCATEGORY' in os.environ and 'NZBPO_SBCATEGORY' in os.environ:
|
||||
if os.environ['NZBPO_NDCATEGORY'] == os.environ['NZBPO_SBCATEGORY']:
|
||||
logger.warning("{x} category is set for SickBeard and NzbDrone. "
|
||||
logger.warning("{x} category is set for SickBeard and Sonarr. "
|
||||
"Please check your config in NZBGet".format
|
||||
(x=os.environ['NZBPO_NDCATEGORY']))
|
||||
|
||||
if 'NZBPO_RACATEGORY' in os.environ and 'NZBPO_CPSCATEGORY' in os.environ:
|
||||
if os.environ['NZBPO_RACATEGORY'] == os.environ['NZBPO_CPSCATEGORY']:
|
||||
logger.warning("{x} category is set for CouchPotato and Radarr. "
|
||||
"Please check your config in NZBGet".format
|
||||
(x=os.environ['NZBPO_RACATEGORY']))
|
||||
section = "Nzb"
|
||||
key = 'NZBOP_DESTDIR'
|
||||
if key in os.environ:
|
||||
|
@ -302,6 +306,8 @@ class ConfigObj(configobj.ConfigObj, Section):
|
|||
CFG_NEW[section][os.environ[envCatKey]] = {}
|
||||
CFG_NEW[section][os.environ[envCatKey]][option] = value
|
||||
CFG_NEW[section][os.environ[envCatKey]]['enabled'] = 1
|
||||
if os.environ[envCatKey] in CFG_NEW['Radarr'].sections:
|
||||
CFG_NEW['Radarr'][envCatKey]['enabled'] = 0
|
||||
|
||||
section = "SickBeard"
|
||||
envCatKey = 'NZBPO_SBCATEGORY'
|
||||
|
@ -388,6 +394,25 @@ class ConfigObj(configobj.ConfigObj, Section):
|
|||
if os.environ[envCatKey] in CFG_NEW['SickBeard'].sections:
|
||||
CFG_NEW['SickBeard'][envCatKey]['enabled'] = 0
|
||||
|
||||
section = "Radarr"
|
||||
envCatKey = 'NZBPO_RACATEGORY'
|
||||
envKeys = ['ENABLED', 'HOST', 'APIKEY', 'PORT', 'SSL', 'WEB_ROOT', 'WATCH_DIR', 'FORK', 'DELETE_FAILED',
|
||||
'TORRENT_NOLINK', 'NZBEXTRACTIONBY', 'WAIT_FOR', 'DELETE_FAILED', 'REMOTE_PATH']
|
||||
cfgKeys = ['enabled', 'host', 'apikey', 'port', 'ssl', 'web_root', 'watch_dir', 'fork', 'delete_failed',
|
||||
'Torrent_NoLink', 'nzbExtractionBy', 'wait_for', 'delete_failed', 'remote_path']
|
||||
if envCatKey in os.environ:
|
||||
for index in range(len(envKeys)):
|
||||
key = 'NZBPO_RA{index}'.format(index=envKeys[index])
|
||||
if key in os.environ:
|
||||
option = cfgKeys[index]
|
||||
value = os.environ[key]
|
||||
if os.environ[envCatKey] not in CFG_NEW[section].sections:
|
||||
CFG_NEW[section][os.environ[envCatKey]] = {}
|
||||
CFG_NEW[section][os.environ[envCatKey]][option] = value
|
||||
CFG_NEW[section][os.environ[envCatKey]]['enabled'] = 1
|
||||
if os.environ[envCatKey] in CFG_NEW['CouchPotato'].sections:
|
||||
CFG_NEW['CouchPotato'][envCatKey]['enabled'] = 0
|
||||
|
||||
section = "Extensions"
|
||||
envKeys = ['COMPRESSEDEXTENSIONS', 'MEDIAEXTENSIONS', 'METAEXTENSIONS']
|
||||
cfgKeys = ['compressedExtensions', 'mediaExtensions', 'metaExtensions']
|
||||
|
|
|
@ -61,6 +61,8 @@ def strip_groups(filename):
|
|||
|
||||
|
||||
def rename_file(filename, newfilePath):
|
||||
if os.path.isfile(newfilePath):
|
||||
newfilePath = os.path.splitext(newfilePath)[0] + ".NTM" + os.path.splitext(newfilePath)[1]
|
||||
logger.debug("Replacing file name {old} with download name {new}".format
|
||||
(old=filename, new=newfilePath), "EXCEPTION")
|
||||
try:
|
||||
|
|
|
@ -195,7 +195,7 @@ def getDirSize(inputPath):
|
|||
from functools import partial
|
||||
prepend = partial(os.path.join, inputPath)
|
||||
return sum(
|
||||
[(os.path.getsize(f) if os.path.isfile(f) else getDirSize(f)) for f in map(prepend, os.listdir(inputPath))])
|
||||
[(os.path.getsize(f) if os.path.isfile(f) else getDirSize(f)) for f in map(prepend, os.listdir(unicode(inputPath)))])
|
||||
|
||||
|
||||
def is_minSize(inputName, minSize):
|
||||
|
@ -322,7 +322,7 @@ def removeEmptyFolders(path, removeRoot=True):
|
|||
|
||||
# remove empty subfolders
|
||||
logger.debug("Checking for empty folders in:{0}".format(path))
|
||||
files = os.listdir(path)
|
||||
files = os.listdir(unicode(path))
|
||||
if len(files):
|
||||
for f in files:
|
||||
fullpath = os.path.join(path, f)
|
||||
|
@ -330,7 +330,7 @@ def removeEmptyFolders(path, removeRoot=True):
|
|||
removeEmptyFolders(fullpath)
|
||||
|
||||
# if folder empty, delete it
|
||||
files = os.listdir(path)
|
||||
files = os.listdir(unicode(path))
|
||||
if len(files) == 0 and removeRoot:
|
||||
logger.debug("Removing empty folder:{}".format(path))
|
||||
os.rmdir(path)
|
||||
|
@ -607,9 +607,9 @@ def getDirs(section, subsection, link='hard'):
|
|||
folders = []
|
||||
|
||||
logger.info("Searching {0} for mediafiles to post-process ...".format(path))
|
||||
sync = [o for o in os.listdir(path) if os.path.splitext(o)[1] in ['.!sync', '.bts']]
|
||||
sync = [o for o in os.listdir(unicode(path)) if os.path.splitext(o)[1] in ['.!sync', '.bts']]
|
||||
# search for single files and move them into their own folder for post-processing
|
||||
for mediafile in [os.path.join(path, o) for o in os.listdir(path) if
|
||||
for mediafile in [os.path.join(path, o) for o in os.listdir(unicode(path)) if
|
||||
os.path.isfile(os.path.join(path, o))]:
|
||||
if len(sync) > 0:
|
||||
break
|
||||
|
@ -673,11 +673,11 @@ def getDirs(section, subsection, link='hard'):
|
|||
|
||||
# removeEmptyFolders(path, removeRoot=False)
|
||||
|
||||
if os.listdir(path):
|
||||
for dir in [os.path.join(path, o) for o in os.listdir(path) if
|
||||
if os.listdir(unicode(path)):
|
||||
for dir in [os.path.join(path, o) for o in os.listdir(unicode(path)) if
|
||||
os.path.isdir(os.path.join(path, o))]:
|
||||
sync = [o for o in os.listdir(dir) if os.path.splitext(o)[1] in ['.!sync', '.bts']]
|
||||
if len(sync) > 0 or len(os.listdir(dir)) == 0:
|
||||
sync = [o for o in os.listdir(unicode(dir)) if os.path.splitext(o)[1] in ['.!sync', '.bts']]
|
||||
if len(sync) > 0 or len(os.listdir(unicode(dir))) == 0:
|
||||
continue
|
||||
folders.extend([dir])
|
||||
return folders
|
||||
|
@ -728,7 +728,7 @@ def onerror(func, path, exc_info):
|
|||
def rmDir(dirName):
|
||||
logger.info("Deleting {0}".format(dirName))
|
||||
try:
|
||||
shutil.rmtree(dirName, onerror=onerror)
|
||||
shutil.rmtree(unicode(dirName), onerror=onerror)
|
||||
except:
|
||||
logger.error("Unable to delete folder {0}".format(dirName))
|
||||
|
||||
|
@ -994,7 +994,7 @@ def listMediaFiles(path, minSize=0, delete_ignored=0, media=True, audio=True, me
|
|||
|
||||
return files
|
||||
|
||||
for curFile in os.listdir(path):
|
||||
for curFile in os.listdir(unicode(path)):
|
||||
fullCurFile = os.path.join(path, curFile)
|
||||
|
||||
# if it's a folder do it recursively
|
||||
|
@ -1031,7 +1031,7 @@ def find_imdbid(dirName, inputName, omdbApiKey):
|
|||
logger.info("Found imdbID [{0}]".format(imdbid))
|
||||
return imdbid
|
||||
if os.path.isdir(dirName):
|
||||
for file in os.listdir(dirName):
|
||||
for file in os.listdir(unicode(dirName)):
|
||||
m = re.search('(tt\d{7})', file)
|
||||
if m:
|
||||
imdbid = m.group(1)
|
||||
|
@ -1047,7 +1047,10 @@ def find_imdbid(dirName, inputName, omdbApiKey):
|
|||
logger.info("Found imdbID [{0}] from DNZB-MoreInfo".format(imdbid))
|
||||
return imdbid
|
||||
logger.info('Searching IMDB for imdbID ...')
|
||||
guess = guessit.guessit(inputName)
|
||||
try:
|
||||
guess = guessit.guessit(inputName)
|
||||
except:
|
||||
guess = None
|
||||
if guess:
|
||||
# Movie Title
|
||||
title = None
|
||||
|
@ -1072,12 +1075,15 @@ def find_imdbid(dirName, inputName, omdbApiKey):
|
|||
logger.error("Unable to open URL {0}".format(url))
|
||||
return
|
||||
|
||||
results = r.json()
|
||||
try:
|
||||
results = r.json()
|
||||
except:
|
||||
logger.error("No json data returned from omdbapi.com")
|
||||
|
||||
try:
|
||||
imdbid = results['imdbID']
|
||||
except:
|
||||
pass
|
||||
logger.error("No imdbID returned from omdbapi.com")
|
||||
|
||||
if imdbid:
|
||||
logger.info("Found imdbID [{0}]".format(imdbid))
|
||||
|
|
|
@ -115,9 +115,9 @@ def getVideoDetails(videofile, img=None, bitbucket=None):
|
|||
|
||||
|
||||
def buildCommands(file, newDir, movieName, bitbucket):
|
||||
if isinstance(file, str):
|
||||
if isinstance(file, basestring):
|
||||
inputFile = file
|
||||
if '"concat:' in file:
|
||||
if 'concat:' in file:
|
||||
file = file.split('|')[0].replace('concat:', '')
|
||||
video_details, result = getVideoDetails(file)
|
||||
dir, name = os.path.split(file)
|
||||
|
@ -254,7 +254,15 @@ def buildCommands(file, newDir, movieName, bitbucket):
|
|||
|
||||
used_audio = 0
|
||||
a_mapped = []
|
||||
commentary = []
|
||||
if audioStreams:
|
||||
for i, val in reversed(list(enumerate(audioStreams))):
|
||||
try:
|
||||
if "Commentary" in val.get("tags").get("title"): # Split out commentry tracks.
|
||||
commentary.append(val)
|
||||
del audioStreams[i]
|
||||
except:
|
||||
continue
|
||||
try:
|
||||
audio1 = [item for item in audioStreams if item["tags"]["language"] == core.ALANGUAGE]
|
||||
except: # no language tags. Assume only 1 language.
|
||||
|
@ -374,6 +382,7 @@ def buildCommands(file, newDir, movieName, bitbucket):
|
|||
audio_cmd.extend(audio_cmd2)
|
||||
|
||||
if core.AINCLUDE and core.ACODEC3:
|
||||
audioStreams.extend(commentary) #add commentry tracks back here.
|
||||
for audio in audioStreams:
|
||||
if audio["index"] in a_mapped:
|
||||
continue
|
||||
|
@ -463,6 +472,10 @@ def buildCommands(file, newDir, movieName, bitbucket):
|
|||
sub_details, result = getVideoDetails(subfile)
|
||||
if not sub_details or not sub_details.get("streams"):
|
||||
continue
|
||||
if core.SCODEC == "mov_text":
|
||||
subcode = [stream["codec_name"] for stream in sub_details["streams"]]
|
||||
if set(subcode).intersection(["dvd_subtitle", "VobSub"]): # We can't convert these.
|
||||
continue
|
||||
command.extend(['-i', subfile])
|
||||
lan = os.path.splitext(os.path.splitext(subfile)[0])[1][1:].split('-')[0]
|
||||
metlan = None
|
||||
|
@ -601,7 +614,7 @@ def processList(List, newDir, bitbucket):
|
|||
if combine:
|
||||
newList.extend(combineCD(combine))
|
||||
for file in newList:
|
||||
if isinstance(file, str) and 'concat:' not in file and not os.path.isfile(file):
|
||||
if isinstance(file, basestring) and 'concat:' not in file and not os.path.isfile(file):
|
||||
success = False
|
||||
break
|
||||
if success and newList:
|
||||
|
@ -736,13 +749,13 @@ def Transcode_directory(dirName):
|
|||
return 1, dirName
|
||||
|
||||
for file in List:
|
||||
if isinstance(file, str) and os.path.splitext(file)[1] in core.IGNOREEXTENSIONS:
|
||||
if isinstance(file, basestring) and os.path.splitext(file)[1] in core.IGNOREEXTENSIONS:
|
||||
continue
|
||||
command = buildCommands(file, newDir, movieName, bitbucket)
|
||||
newfilePath = command[-1]
|
||||
|
||||
# transcoding files may remove the original file, so make sure to extract subtitles first
|
||||
if core.SEXTRACT and isinstance(file, str):
|
||||
if core.SEXTRACT and isinstance(file, basestring):
|
||||
extract_subs(file, newfilePath, bitbucket)
|
||||
|
||||
try: # Try to remove the file that we're transcoding to just in case. (ffmpeg will return an error if it already exists for some reason)
|
||||
|
@ -757,7 +770,7 @@ def Transcode_directory(dirName):
|
|||
print_cmd(command)
|
||||
result = 1 # set result to failed in case call fails.
|
||||
try:
|
||||
if isinstance(file, str):
|
||||
if isinstance(file, basestring):
|
||||
proc = subprocess.Popen(command, stdout=bitbucket, stderr=bitbucket)
|
||||
else:
|
||||
img, data = iteritems(file).next()
|
||||
|
@ -772,7 +785,7 @@ def Transcode_directory(dirName):
|
|||
except:
|
||||
logger.error("Transcoding of video {0} has failed".format(newfilePath))
|
||||
|
||||
if core.SUBSDIR and result == 0 and isinstance(file, str):
|
||||
if core.SUBSDIR and result == 0 and isinstance(file, basestring):
|
||||
for sub in get_subs(file):
|
||||
name = os.path.splitext(os.path.split(file)[1])[0]
|
||||
subname = os.path.split(sub)[1]
|
||||
|
@ -802,7 +815,7 @@ def Transcode_directory(dirName):
|
|||
os.unlink(file)
|
||||
except:
|
||||
pass
|
||||
if not os.listdir(newDir): # this is an empty directory and we didn't transcode into it.
|
||||
if not os.listdir(unicode(newDir)): # this is an empty directory and we didn't transcode into it.
|
||||
os.rmdir(newDir)
|
||||
newDir = dirName
|
||||
if not core.PROCESSOUTPUT and core.DUPLICATE: # We postprocess the original files to CP/SB
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue