rename nzbtomedia to core. Fixes #744 #746

This commit is contained in:
clinton-hall 2015-04-26 16:41:39 +09:30
parent 617bf37878
commit c80a678ded
54 changed files with 567 additions and 567 deletions

View file

@ -4,12 +4,12 @@ import os
import time
import shutil
import sys
import nzbtomedia
import core
from subprocess import Popen
from nzbtomedia import logger, nzbToMediaDB
from nzbtomedia.nzbToMediaUtil import convert_to_ascii, CharReplace
from nzbtomedia.nzbToMediaUserScript import external_script
from core import logger, nzbToMediaDB
from core.nzbToMediaUtil import convert_to_ascii, CharReplace
from core.nzbToMediaUserScript import external_script
def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, clientAgent):
status = 1 # 1 = failed | 0 = success
@ -17,7 +17,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
foundFile = 0
uniquePath = 1
if clientAgent != 'manual' and not nzbtomedia.DOWNLOADINFO:
if clientAgent != 'manual' and not core.DOWNLOADINFO:
logger.debug('Adding TORRENT download info for directory %s to database' % (inputDirectory))
myDB = nzbToMediaDB.DBConnection()
@ -37,26 +37,26 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
logger.debug("Received Directory: %s | Name: %s | Category: %s" % (inputDirectory, inputName, inputCategory))
inputDirectory, inputName, inputCategory, root = nzbtomedia.category_search(inputDirectory, inputName,
inputDirectory, inputName, inputCategory, root = core.category_search(inputDirectory, inputName,
inputCategory, root,
nzbtomedia.CATEGORIES) # Confirm the category by parsing directory structure
core.CATEGORIES) # Confirm the category by parsing directory structure
if inputCategory == "":
inputCategory = "UNCAT"
usercat = inputCategory
try:
inputName = inputName.encode(nzbtomedia.SYS_ENCODING)
inputName = inputName.encode(core.SYS_ENCODING)
except: pass
try:
inputDirectory = inputDirectory.encode(nzbtomedia.SYS_ENCODING)
inputDirectory = inputDirectory.encode(core.SYS_ENCODING)
except: pass
logger.debug("Determined Directory: %s | Name: %s | Category: %s" % (inputDirectory, inputName, inputCategory))
# auto-detect section
section = nzbtomedia.CFG.findsection(inputCategory).isenabled()
section = core.CFG.findsection(inputCategory).isenabled()
if section is None:
section = nzbtomedia.CFG.findsection("ALL").isenabled()
section = core.CFG.findsection("ALL").isenabled()
if section is None:
logger.error(
'Category:[%s] is not defined or is not enabled. Please rename it or ensure it is enabled for the appropriate section in your autoProcessMedia.cfg and try again.' % (
@ -95,21 +95,21 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
uniquePath = 1
if clientAgent != 'manual':
nzbtomedia.pause_torrent(clientAgent, inputHash, inputID, inputName)
core.pause_torrent(clientAgent, inputHash, inputID, inputName)
if uniquePath:
outputDestination = os.path.normpath(
nzbtomedia.os.path.join(nzbtomedia.OUTPUTDIRECTORY, inputCategory, nzbtomedia.sanitizeName(inputName)))
core.os.path.join(core.OUTPUTDIRECTORY, inputCategory, core.sanitizeName(inputName)))
else:
outputDestination = os.path.normpath(
nzbtomedia.os.path.join(nzbtomedia.OUTPUTDIRECTORY, inputCategory))
core.os.path.join(core.OUTPUTDIRECTORY, inputCategory))
try:
outputDestination = outputDestination.encode(nzbtomedia.SYS_ENCODING)
outputDestination = outputDestination.encode(core.SYS_ENCODING)
except: pass
logger.info("Output directory set to: %s" % (outputDestination))
if nzbtomedia.SAFE_MODE and outputDestination == nzbtomedia.TORRENT_DEFAULTDIR:
if core.SAFE_MODE and outputDestination == core.TORRENT_DEFAULTDIR:
logger.error(
'The output directory:[%s] is the Download Directory. Edit outputDirectory in autoProcessMedia.cfg. Exiting' % (
inputDirectory))
@ -118,33 +118,33 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
logger.debug("Scanning files in directory: %s" % (inputDirectory))
if sectionName == 'HeadPhones':
nzbtomedia.NOFLATTEN.extend(
core.NOFLATTEN.extend(
inputCategory) # Make sure we preserve folder structure for HeadPhones.
now = datetime.datetime.now()
inputFiles = nzbtomedia.listMediaFiles(inputDirectory)
inputFiles = core.listMediaFiles(inputDirectory)
logger.debug("Found %s files in %s" % (str(len(inputFiles)), inputDirectory))
for inputFile in inputFiles:
filePath = os.path.dirname(inputFile)
fileName, fileExt = os.path.splitext(os.path.basename(inputFile))
fullFileName = os.path.basename(inputFile)
targetFile = nzbtomedia.os.path.join(outputDestination, fullFileName)
if inputCategory in nzbtomedia.NOFLATTEN:
targetFile = core.os.path.join(outputDestination, fullFileName)
if inputCategory in core.NOFLATTEN:
if not os.path.basename(filePath) in outputDestination:
targetFile = nzbtomedia.os.path.join(
nzbtomedia.os.path.join(outputDestination, os.path.basename(filePath)), fullFileName)
targetFile = core.os.path.join(
core.os.path.join(outputDestination, os.path.basename(filePath)), fullFileName)
logger.debug(
"Setting outputDestination to %s to preserve folder structure" % (os.path.dirname(targetFile)))
try:
targetFile = targetFile.encode(nzbtomedia.SYS_ENCODING)
targetFile = targetFile.encode(core.SYS_ENCODING)
except: pass
if root == 1:
if not foundFile:
logger.debug("Looking for %s in: %s" % (inputName, inputFile))
if (nzbtomedia.sanitizeName(inputName) in nzbtomedia.sanitizeName(inputFile)) or (
nzbtomedia.sanitizeName(fileName) in nzbtomedia.sanitizeName(inputName)):
if (core.sanitizeName(inputName) in core.sanitizeName(inputFile)) or (
core.sanitizeName(fileName) in core.sanitizeName(inputName)):
foundFile = True
logger.debug("Found file %s that matches Torrent Name %s" % (fullFileName, inputName))
else:
@ -164,8 +164,8 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
if Torrent_NoLink == 0:
try:
nzbtomedia.copy_link(inputFile, targetFile, nzbtomedia.USELINK)
nzbtomedia.rmReadOnly(targetFile)
core.copy_link(inputFile, targetFile, core.USELINK)
core.rmReadOnly(targetFile)
except:
logger.error("Failed to link: %s to %s" % (inputFile, targetFile))
@ -173,15 +173,15 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
if extract == 1:
logger.debug('Checking for archives to extract in directory: %s' % (outputDestination))
nzbtomedia.extractFiles(outputDestination)
core.extractFiles(outputDestination)
if not inputCategory in nzbtomedia.NOFLATTEN: #don't flatten hp in case multi cd albums, and we need to copy this back later.
nzbtomedia.flatten(outputDestination)
if not inputCategory in core.NOFLATTEN: #don't flatten hp in case multi cd albums, and we need to copy this back later.
core.flatten(outputDestination)
# Now check if video files exist in destination:
if sectionName in ["SickBeard", "NzbDrone", "CouchPotato"]:
numVideos = len(
nzbtomedia.listMediaFiles(outputDestination, media=True, audio=False, meta=False, archives=False))
core.listMediaFiles(outputDestination, media=True, audio=False, meta=False, archives=False))
if numVideos > 0:
logger.info("Found %s media files in %s" % (numVideos, outputDestination))
status = 0
@ -202,48 +202,48 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
result = external_script(outputDestination, inputName, inputCategory, section[usercat])
elif sectionName == 'CouchPotato':
result = nzbtomedia.autoProcessMovie().process(sectionName,outputDestination, inputName, status, clientAgent, inputHash,
result = core.autoProcessMovie().process(sectionName,outputDestination, inputName, status, clientAgent, inputHash,
inputCategory)
elif sectionName in ['SickBeard','NzbDrone']:
if inputHash:
inputHash = inputHash.upper()
result = nzbtomedia.autoProcessTV().processEpisode(sectionName,outputDestination, inputName, status, clientAgent,
result = core.autoProcessTV().processEpisode(sectionName,outputDestination, inputName, status, clientAgent,
inputHash, inputCategory)
elif sectionName == 'HeadPhones':
result = nzbtomedia.autoProcessMusic().process(sectionName,outputDestination, inputName, status, clientAgent, inputCategory)
result = core.autoProcessMusic().process(sectionName,outputDestination, inputName, status, clientAgent, inputCategory)
elif sectionName == 'Mylar':
result = nzbtomedia.autoProcessComics().processEpisode(sectionName,outputDestination, inputName, status, clientAgent,
result = core.autoProcessComics().processEpisode(sectionName,outputDestination, inputName, status, clientAgent,
inputCategory)
elif sectionName == 'Gamez':
result = nzbtomedia.autoProcessGames().process(sectionName,outputDestination, inputName, status, clientAgent, inputCategory)
result = core.autoProcessGames().process(sectionName,outputDestination, inputName, status, clientAgent, inputCategory)
if result[0] != 0:
if clientAgent != 'manual':
logger.error(
"A problem was reported in the autoProcess* script. If torrent was paused we will resume seeding")
nzbtomedia.resume_torrent(clientAgent, inputHash, inputID, inputName)
core.resume_torrent(clientAgent, inputHash, inputID, inputName)
else:
if clientAgent != 'manual':
# update download status in our DB
nzbtomedia.update_downloadInfoStatus(inputName, 1)
core.update_downloadInfoStatus(inputName, 1)
# remove torrent
nzbtomedia.remove_torrent(clientAgent, inputHash, inputID, inputName)
core.remove_torrent(clientAgent, inputHash, inputID, inputName)
if not sectionName == 'UserScript': # for user script, we assume this is cleaned by the script or option USER_SCRIPT_CLEAN
# cleanup our processing folders of any misc unwanted files and empty directories
nzbtomedia.cleanDir(outputDestination, sectionName, inputCategory)
core.cleanDir(outputDestination, sectionName, inputCategory)
return result
def main(args):
# Initialize the config
nzbtomedia.initialize()
core.initialize()
# clientAgent for Torrents
clientAgent = nzbtomedia.TORRENT_CLIENTAGENT
clientAgent = core.TORRENT_CLIENTAGENT
logger.info("#########################################################")
logger.info("## ..::[%s]::.. ##" % os.path.basename(__file__))
@ -256,7 +256,7 @@ def main(args):
result = [ 0, "" ]
try:
inputDirectory, inputName, inputCategory, inputHash, inputID = nzbtomedia.parse_args(clientAgent, args)
inputDirectory, inputName, inputCategory, inputHash, inputID = core.parse_args(clientAgent, args)
except:
logger.error("There was a problem loading variables")
return -1
@ -267,16 +267,16 @@ def main(args):
# Perform Manual Post-Processing
logger.warning("Invalid number of arguments received from client, Switching to manual run mode ...")
for section, subsections in nzbtomedia.SECTIONS.items():
for section, subsections in core.SECTIONS.items():
for subsection in subsections:
if not nzbtomedia.CFG[section][subsection].isenabled():
if not core.CFG[section][subsection].isenabled():
continue
for dirName in nzbtomedia.getDirs(section, subsection, link='hard'):
for dirName in core.getDirs(section, subsection, link='hard'):
logger.info("Starting manual run for %s:%s - Folder:%s" % (section, subsection, dirName))
logger.info("Checking database for download info for %s ..." % (os.path.basename(dirName)))
nzbtomedia.DOWNLOADINFO = nzbtomedia.get_downloadInfo(os.path.basename(dirName), 0)
if nzbtomedia.DOWNLOADINFO:
core.DOWNLOADINFO = core.get_downloadInfo(os.path.basename(dirName), 0)
if core.DOWNLOADINFO:
logger.info(
"Found download info for %s, setting variables now ..." % (os.path.basename(dirName)))
else:
@ -286,27 +286,27 @@ def main(args):
)
try:
clientAgent = str(nzbtomedia.DOWNLOADINFO[0]['client_agent'])
clientAgent = str(core.DOWNLOADINFO[0]['client_agent'])
except:
clientAgent = 'manual'
try:
inputHash = str(nzbtomedia.DOWNLOADINFO[0]['input_hash'])
inputHash = str(core.DOWNLOADINFO[0]['input_hash'])
except:
inputHash = None
try:
inputID = str(nzbtomedia.DOWNLOADINFO[0]['input_id'])
inputID = str(core.DOWNLOADINFO[0]['input_id'])
except:
inputID = None
if clientAgent.lower() not in nzbtomedia.TORRENT_CLIENTS and clientAgent != 'manual':
if clientAgent.lower() not in core.TORRENT_CLIENTS and clientAgent != 'manual':
continue
try:
dirName = dirName.encode(nzbtomedia.SYS_ENCODING)
dirName = dirName.encode(core.SYS_ENCODING)
except: pass
inputName = os.path.basename(dirName)
try:
inputName = inputName.encode(nzbtomedia.SYS_ENCODING)
inputName = inputName.encode(core.SYS_ENCODING)
except: pass
results = processTorrent(dirName, inputName, subsection, inputHash, inputID,
@ -320,7 +320,7 @@ def main(args):
logger.info("The %s script completed successfully." % (args[0]))
else:
logger.error("A problem was reported in the %s script." % (args[0]))
del nzbtomedia.MYAPP
del core.MYAPP
return result[0]

View file

@ -25,19 +25,19 @@ CONFIG_TV_FILE = os.path.join(PROGRAM_DIR, 'autoProcessTv.cfg')
TEST_FILE = os.path.join(os.path.join(PROGRAM_DIR, 'tests'), 'test.mp4')
MYAPP = None
from nzbtomedia.autoProcess.autoProcessComics import autoProcessComics
from nzbtomedia.autoProcess.autoProcessGames import autoProcessGames
from nzbtomedia.autoProcess.autoProcessMovie import autoProcessMovie
from nzbtomedia.autoProcess.autoProcessMusic import autoProcessMusic
from nzbtomedia.autoProcess.autoProcessTV import autoProcessTV
from nzbtomedia import logger, versionCheck, nzbToMediaDB
from nzbtomedia.nzbToMediaConfig import config
from nzbtomedia.nzbToMediaUtil import category_search, sanitizeName, copy_link, parse_args, flatten, getDirs, \
from core.autoProcess.autoProcessComics import autoProcessComics
from core.autoProcess.autoProcessGames import autoProcessGames
from core.autoProcess.autoProcessMovie import autoProcessMovie
from core.autoProcess.autoProcessMusic import autoProcessMusic
from core.autoProcess.autoProcessTV import autoProcessTV
from core import logger, versionCheck, nzbToMediaDB
from core.nzbToMediaConfig import config
from core.nzbToMediaUtil import category_search, sanitizeName, copy_link, parse_args, flatten, getDirs, \
rmReadOnly,rmDir, pause_torrent, resume_torrent, remove_torrent, listMediaFiles, \
extractFiles, cleanDir, update_downloadInfoStatus, get_downloadInfo, WakeUp, makeDir, cleanDir, \
create_torrent_class, listMediaFiles, RunningProcess
from nzbtomedia.transcoder import transcoder
from nzbtomedia.databases import mainDB
from core.transcoder import transcoder
from core.databases import mainDB
# Client Agents
NZB_CLIENTS = ['sabnzbd','nzbget']
@ -631,7 +631,7 @@ def initialize(section=None):
if platform.system() == 'Windows':
FFMPEG = os.path.join(FFMPEG_PATH, 'ffmpeg.exe')
FFPROBE = os.path.join(FFMPEG_PATH, 'ffprobe.exe')
SEVENZIP = os.path.join(PROGRAM_DIR, 'nzbtomedia', 'extractor', 'bin', platform.machine(), '7z.exe')
SEVENZIP = os.path.join(PROGRAM_DIR, 'core', 'extractor', 'bin', platform.machine(), '7z.exe')
if not (os.path.isfile(FFMPEG)): # problem
FFMPEG = None

View file

@ -1,11 +1,11 @@
import os
import time
import nzbtomedia
import core
import requests
import time
from nzbtomedia.nzbToMediaUtil import convert_to_ascii, remoteDir, server_responding
from nzbtomedia.nzbToMediaSceneExceptions import process_all_exceptions
from nzbtomedia import logger
from core.nzbToMediaUtil import convert_to_ascii, remoteDir, server_responding
from core.nzbToMediaSceneExceptions import process_all_exceptions
from core import logger
class autoProcessComics:
def processEpisode(self, section, dirName, inputName=None, status=0, clientAgent='manual', inputCategory=None):
@ -13,20 +13,20 @@ class autoProcessComics:
logger.warning("FAILED DOWNLOAD DETECTED, nothing to process.",section)
return [1, "%s: Failed to post-process. %s does not support failed downloads" % (section, section) ]
host = nzbtomedia.CFG[section][inputCategory]["host"]
port = nzbtomedia.CFG[section][inputCategory]["port"]
username = nzbtomedia.CFG[section][inputCategory]["username"]
password = nzbtomedia.CFG[section][inputCategory]["password"]
host = core.CFG[section][inputCategory]["host"]
port = core.CFG[section][inputCategory]["port"]
username = core.CFG[section][inputCategory]["username"]
password = core.CFG[section][inputCategory]["password"]
try:
ssl = int(nzbtomedia.CFG[section][inputCategory]["ssl"])
ssl = int(core.CFG[section][inputCategory]["ssl"])
except:
ssl = 0
try:
web_root = nzbtomedia.CFG[section][inputCategory]["web_root"]
web_root = core.CFG[section][inputCategory]["web_root"]
except:
web_root = ""
try:
remote_path = int(nzbtomedia.CFG[section][inputCategory]["remote_path"])
remote_path = int(core.CFG[section][inputCategory]["remote_path"])
except:
remote_path = 0

View file

@ -1,27 +1,27 @@
import nzbtomedia
import core
import requests
import shutil
from nzbtomedia.nzbToMediaUtil import convert_to_ascii, server_responding
from nzbtomedia.nzbToMediaSceneExceptions import process_all_exceptions
from nzbtomedia import logger
from core.nzbToMediaUtil import convert_to_ascii, server_responding
from core.nzbToMediaSceneExceptions import process_all_exceptions
from core import logger
class autoProcessGames:
def process(self, section, dirName, inputName=None, status=0, clientAgent='manual', inputCategory=None):
status = int(status)
host = nzbtomedia.CFG[section][inputCategory]["host"]
port = nzbtomedia.CFG[section][inputCategory]["port"]
apikey = nzbtomedia.CFG[section][inputCategory]["apikey"]
host = core.CFG[section][inputCategory]["host"]
port = core.CFG[section][inputCategory]["port"]
apikey = core.CFG[section][inputCategory]["apikey"]
try:
library = nzbtomedia.CFG[section][inputCategory]["library"]
library = core.CFG[section][inputCategory]["library"]
except:
library = None
try:
ssl = int(nzbtomedia.CFG[section][inputCategory]["ssl"])
ssl = int(core.CFG[section][inputCategory]["ssl"])
except:
ssl = 0
try:
web_root = nzbtomedia.CFG[section][inputCategory]["web_root"]
web_root = core.CFG[section][inputCategory]["web_root"]
except:
web_root = ""

View file

@ -1,12 +1,12 @@
import os
import time
import requests
import nzbtomedia
import core
from nzbtomedia.nzbToMediaSceneExceptions import process_all_exceptions
from nzbtomedia.nzbToMediaUtil import convert_to_ascii, rmDir, find_imdbid, find_download, listMediaFiles, remoteDir, import_subs, server_responding, reportNzb
from nzbtomedia import logger
from nzbtomedia.transcoder import transcoder
from core.nzbToMediaSceneExceptions import process_all_exceptions
from core.nzbToMediaUtil import convert_to_ascii, rmDir, find_imdbid, find_download, listMediaFiles, remoteDir, import_subs, server_responding, reportNzb
from core import logger
from core.transcoder import transcoder
class autoProcessMovie:
@ -99,23 +99,23 @@ class autoProcessMovie:
def process(self, section, dirName, inputName=None, status=0, clientAgent="manual", download_id="", inputCategory=None, failureLink=None):
host = nzbtomedia.CFG[section][inputCategory]["host"]
port = nzbtomedia.CFG[section][inputCategory]["port"]
apikey = nzbtomedia.CFG[section][inputCategory]["apikey"]
method = nzbtomedia.CFG[section][inputCategory]["method"]
delete_failed = int(nzbtomedia.CFG[section][inputCategory]["delete_failed"])
wait_for = int(nzbtomedia.CFG[section][inputCategory]["wait_for"])
host = core.CFG[section][inputCategory]["host"]
port = core.CFG[section][inputCategory]["port"]
apikey = core.CFG[section][inputCategory]["apikey"]
method = core.CFG[section][inputCategory]["method"]
delete_failed = int(core.CFG[section][inputCategory]["delete_failed"])
wait_for = int(core.CFG[section][inputCategory]["wait_for"])
try:
ssl = int(nzbtomedia.CFG[section][inputCategory]["ssl"])
ssl = int(core.CFG[section][inputCategory]["ssl"])
except:
ssl = 0
try:
web_root = nzbtomedia.CFG[section][inputCategory]["web_root"]
web_root = core.CFG[section][inputCategory]["web_root"]
except:
web_root = ""
try:
remote_path = int(nzbtomedia.CFG[section][inputCategory]["remote_path"])
remote_path = int(core.CFG[section][inputCategory]["remote_path"])
except:
remote_path = 0
try:
@ -166,7 +166,7 @@ class autoProcessMovie:
if not listMediaFiles(dirName, media=True, audio=False, meta=False, archives=False) and listMediaFiles(dirName, media=False, audio=False, meta=False, archives=True) and extract:
logger.debug('Checking for archives to extract in directory: %s' % (dirName))
nzbtomedia.extractFiles(dirName)
core.extractFiles(dirName)
inputName, dirName = convert_to_ascii(inputName, dirName)
good_files = 0
@ -197,7 +197,7 @@ class autoProcessMovie:
status = 1
if status == 0:
if nzbtomedia.TRANSCODE == 1:
if core.TRANSCODE == 1:
result, newDirName = transcoder.Transcode_directory(dirName)
if result == 0:
logger.debug("Transcoding succeeded for files in %s" % (dirName), section)

View file

@ -1,11 +1,11 @@
import os
import time
import requests
import nzbtomedia
import core
from nzbtomedia.nzbToMediaUtil import convert_to_ascii, remoteDir, listMediaFiles, server_responding
from nzbtomedia.nzbToMediaSceneExceptions import process_all_exceptions
from nzbtomedia import logger
from core.nzbToMediaUtil import convert_to_ascii, remoteDir, listMediaFiles, server_responding
from core.nzbToMediaSceneExceptions import process_all_exceptions
from core import logger
class autoProcessMusic:
def get_status(self, url, apikey, dirName):
@ -34,21 +34,21 @@ class autoProcessMusic:
def process(self, section, dirName, inputName=None, status=0, clientAgent="manual", inputCategory=None):
status = int(status)
host = nzbtomedia.CFG[section][inputCategory]["host"]
port = nzbtomedia.CFG[section][inputCategory]["port"]
apikey = nzbtomedia.CFG[section][inputCategory]["apikey"]
wait_for = int(nzbtomedia.CFG[section][inputCategory]["wait_for"])
host = core.CFG[section][inputCategory]["host"]
port = core.CFG[section][inputCategory]["port"]
apikey = core.CFG[section][inputCategory]["apikey"]
wait_for = int(core.CFG[section][inputCategory]["wait_for"])
try:
ssl = int(nzbtomedia.CFG[section][inputCategory]["ssl"])
ssl = int(core.CFG[section][inputCategory]["ssl"])
except:
ssl = 0
try:
web_root = nzbtomedia.CFG[section][inputCategory]["web_root"]
web_root = core.CFG[section][inputCategory]["web_root"]
except:
web_root = ""
try:
remote_path = int(nzbtomedia.CFG[section][inputCategory]["remote_path"])
remote_path = int(core.CFG[section][inputCategory]["remote_path"])
except:
remote_path = 0
try:
@ -82,7 +82,7 @@ class autoProcessMusic:
if not listMediaFiles(dirName, media=False, audio=True, meta=False, archives=False) and listMediaFiles(dirName, media=False, audio=False, meta=False, archives=True) and extract:
logger.debug('Checking for archives to extract in directory: %s' % (dirName))
nzbtomedia.extractFiles(dirName)
core.extractFiles(dirName)
inputName, dirName = convert_to_ascii(inputName, dirName)
if listMediaFiles(dirName, media=False, audio=True, meta=False, archives=False) and status:

View file

@ -4,13 +4,13 @@ import time
import errno
import requests
import json
import nzbtomedia
import core
from nzbtomedia.nzbToMediaAutoFork import autoFork
from nzbtomedia.nzbToMediaSceneExceptions import process_all_exceptions
from nzbtomedia.nzbToMediaUtil import convert_to_ascii, flatten, rmDir, listMediaFiles, remoteDir, import_subs, server_responding, reportNzb
from nzbtomedia import logger
from nzbtomedia.transcoder import transcoder
from core.nzbToMediaAutoFork import autoFork
from core.nzbToMediaSceneExceptions import process_all_exceptions
from core.nzbToMediaUtil import convert_to_ascii, flatten, rmDir, listMediaFiles, remoteDir, import_subs, server_responding, reportNzb
from core import logger
from core.transcoder import transcoder
class autoProcessTV:
def command_complete(self, url, params, headers, section):
@ -49,10 +49,10 @@ class autoProcessTV:
return False
def processEpisode(self, section, dirName, inputName=None, failed=False, clientAgent = "manual", download_id=None, inputCategory=None, failureLink=None):
host = nzbtomedia.CFG[section][inputCategory]["host"]
port = nzbtomedia.CFG[section][inputCategory]["port"]
host = core.CFG[section][inputCategory]["host"]
port = core.CFG[section][inputCategory]["port"]
try:
ssl = int(nzbtomedia.CFG[section][inputCategory]["ssl"])
ssl = int(core.CFG[section][inputCategory]["ssl"])
except:
ssl = 0
if ssl:
@ -60,7 +60,7 @@ class autoProcessTV:
else:
protocol = "http://"
try:
web_root = nzbtomedia.CFG[section][inputCategory]["web_root"]
web_root = core.CFG[section][inputCategory]["web_root"]
except:
web_root = ""
if not server_responding("%s%s:%s%s" % (protocol,host,port,web_root)):
@ -71,37 +71,37 @@ class autoProcessTV:
fork, fork_params = autoFork(section, inputCategory)
try:
username = nzbtomedia.CFG[section][inputCategory]["username"]
password = nzbtomedia.CFG[section][inputCategory]["password"]
username = core.CFG[section][inputCategory]["username"]
password = core.CFG[section][inputCategory]["password"]
except:
username = ""
password = ""
try:
apikey = nzbtomedia.CFG[section][inputCategory]["apikey"]
apikey = core.CFG[section][inputCategory]["apikey"]
except:
apikey = ""
try:
delete_failed = int(nzbtomedia.CFG[section][inputCategory]["delete_failed"])
delete_failed = int(core.CFG[section][inputCategory]["delete_failed"])
except:
delete_failed = 0
try:
nzbExtractionBy = nzbtomedia.CFG[section][inputCategory]["nzbExtractionBy"]
nzbExtractionBy = core.CFG[section][inputCategory]["nzbExtractionBy"]
except:
nzbExtractionBy = "Downloader"
try:
process_method = nzbtomedia.CFG[section][inputCategory]["process_method"]
process_method = core.CFG[section][inputCategory]["process_method"]
except:
process_method = None
try:
remote_path = int(nzbtomedia.CFG[section][inputCategory]["remote_path"])
remote_path = int(core.CFG[section][inputCategory]["remote_path"])
except:
remote_path = 0
try:
wait_for = int(nzbtomedia.CFG[section][inputCategory]["wait_for"])
wait_for = int(core.CFG[section][inputCategory]["wait_for"])
except:
wait_for = 2
try:
force = int(nzbtomedia.CFG[section][inputCategory]["force"])
force = int(core.CFG[section][inputCategory]["force"])
except:
force = 0
try:
@ -155,7 +155,7 @@ class autoProcessTV:
logger.warning("No media files found in directory %s to manually process." % (dirName), section)
return [0, ""] # Success (as far as this script is concerned)
if fork not in nzbtomedia.SICKBEARD_TORRENT or (clientAgent in ['nzbget','sabnzbd'] and nzbExtractionBy != "Destination"):
if fork not in core.SICKBEARD_TORRENT or (clientAgent in ['nzbget','sabnzbd'] and nzbExtractionBy != "Destination"):
if inputName:
process_all_exceptions(inputName, dirName)
inputName, dirName = convert_to_ascii(inputName, dirName)
@ -165,7 +165,7 @@ class autoProcessTV:
flatten(dirName) # to make sure SickBeard can find the video (not in sub-folder)
elif listMediaFiles(dirName, media=False, audio=False, meta=False, archives=True) and extract:
logger.debug('Checking for archives to extract in directory: %s' % (dirName))
nzbtomedia.extractFiles(dirName)
core.extractFiles(dirName)
inputName, dirName = convert_to_ascii(inputName, dirName)
good_files = 0
num_files = 0
@ -189,7 +189,7 @@ class autoProcessTV:
status = 1
failed = 1
if status == 0 and nzbtomedia.TRANSCODE == 1: # only transcode successful downlaods
if status == 0 and core.TRANSCODE == 1: # only transcode successful downlaods
result, newDirName = transcoder.Transcode_directory(dirName)
if result == 0:
logger.debug("SUCCESS: Transcoding succeeded for files in %s" % (dirName), section)
@ -232,7 +232,7 @@ class autoProcessTV:
else:
if failureLink:
reportNzb(failureLink, clientAgent)
if fork in nzbtomedia.SICKBEARD_FAILED:
if fork in core.SICKBEARD_FAILED:
logger.postprocess("FAILED: The download failed. Sending 'failed' process request to %s branch" % (fork), section)
elif section == "NzbDrone":
logger.postprocess("FAILED: The download failed. Sending failed download to %s for CDH processing" % (fork), section)

View file

@ -1,6 +1,6 @@
import nzbtomedia
from nzbtomedia import logger, nzbToMediaDB
from nzbtomedia.nzbToMediaUtil import backupVersionedFile
import core
from core import logger, nzbToMediaDB
from core.nzbToMediaUtil import backupVersionedFile
MIN_DB_VERSION = 1 # oldest db version we support migrating from
MAX_DB_VERSION = 2

View file

@ -3,7 +3,7 @@ import platform
import shutil
import stat
from time import sleep
import nzbtomedia
import core
from subprocess import call, Popen
import subprocess
@ -11,11 +11,11 @@ def extract(filePath, outputDestination):
success = 0
# Using Windows
if platform.system() == 'Windows':
if not os.path.exists(nzbtomedia.SEVENZIP):
nzbtomedia.logger.error("EXTRACTOR: Could not find 7-zip, Exiting")
if not os.path.exists(core.SEVENZIP):
core.logger.error("EXTRACTOR: Could not find 7-zip, Exiting")
return False
invislocation = os.path.join(nzbtomedia.PROGRAM_DIR, 'nzbtomedia', 'extractor', 'bin', 'invisible.cmd')
cmd_7zip = [invislocation, nzbtomedia.SEVENZIP, "x", "-y"]
invislocation = os.path.join(core.PROGRAM_DIR, 'core', 'extractor', 'bin', 'invisible.cmd')
cmd_7zip = [invislocation, core.SEVENZIP, "x", "-y"]
ext_7zip = [".rar", ".zip", ".tar.gz", "tgz", ".tar.bz2", ".tbz", ".tar.lzma", ".tlz", ".7z", ".xz"]
EXTRACT_COMMANDS = dict.fromkeys(ext_7zip, cmd_7zip)
# Using unix
@ -50,14 +50,14 @@ def extract(filePath, outputDestination):
else:
for k, v in EXTRACT_COMMANDS.items():
if cmd in v[0]:
nzbtomedia.logger.error("EXTRACTOR: %s not found, disabling support for %s" % (cmd, k))
core.logger.error("EXTRACTOR: %s not found, disabling support for %s" % (cmd, k))
del EXTRACT_COMMANDS[k]
devnull.close()
else:
nzbtomedia.logger.warning("EXTRACTOR: Cannot determine which tool to use when called from Transmission")
core.logger.warning("EXTRACTOR: Cannot determine which tool to use when called from Transmission")
if not EXTRACT_COMMANDS:
nzbtomedia.logger.warning("EXTRACTOR: No archive extracting programs found, plugin will be disabled")
core.logger.warning("EXTRACTOR: No archive extracting programs found, plugin will be disabled")
ext = os.path.splitext(filePath)
cmd = []
@ -73,19 +73,19 @@ def extract(filePath, outputDestination):
if ext[1] in EXTRACT_COMMANDS:
cmd = EXTRACT_COMMANDS[ext[1]]
else:
nzbtomedia.logger.debug("EXTRACTOR: Unknown file type: %s" % ext[1])
core.logger.debug("EXTRACTOR: Unknown file type: %s" % ext[1])
return False
# Create outputDestination folder
nzbtomedia.makeDir(outputDestination)
core.makeDir(outputDestination)
if nzbtomedia.PASSWORDSFILE != "" and os.path.isfile(os.path.normpath(nzbtomedia.PASSWORDSFILE)):
passwords = [line.strip() for line in open(os.path.normpath(nzbtomedia.PASSWORDSFILE))]
if core.PASSWORDSFILE != "" and os.path.isfile(os.path.normpath(core.PASSWORDSFILE)):
passwords = [line.strip() for line in open(os.path.normpath(core.PASSWORDSFILE))]
else:
passwords = []
nzbtomedia.logger.info("Extracting %s to %s" % (filePath, outputDestination))
nzbtomedia.logger.debug("Extracting %s %s %s" % (cmd, filePath, outputDestination))
core.logger.info("Extracting %s to %s" % (filePath, outputDestination))
core.logger.debug("Extracting %s %s %s" % (cmd, filePath, outputDestination))
origFiles = []
origDirs = []
@ -106,16 +106,16 @@ def extract(filePath, outputDestination):
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
else:
cmd = nzbtomedia.NICENESS + cmd
cmd = core.NICENESS + cmd
cmd2 = cmd
cmd2.append("-p-") # don't prompt for password.
p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine.
res = p.wait()
if (res >= 0 and os.name == 'nt') or res == 0: # for windows chp returns process id if successful or -1*Error code. Linux returns 0 for successful.
nzbtomedia.logger.info("EXTRACTOR: Extraction was successful for %s to %s" % (filePath, outputDestination))
core.logger.info("EXTRACTOR: Extraction was successful for %s to %s" % (filePath, outputDestination))
success = 1
elif len(passwords) > 0:
nzbtomedia.logger.info("EXTRACTOR: Attempting to extract with passwords")
core.logger.info("EXTRACTOR: Attempting to extract with passwords")
for password in passwords:
if password == "": # if edited in windows or otherwise if blank lines.
continue
@ -126,14 +126,14 @@ def extract(filePath, outputDestination):
p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine.
res = p.wait()
if (res >= 0 and platform == 'Windows') or res == 0:
nzbtomedia.logger.info("EXTRACTOR: Extraction was successful for %s to %s using password: %s" % (
core.logger.info("EXTRACTOR: Extraction was successful for %s to %s using password: %s" % (
filePath, outputDestination, password))
success = 1
break
else:
continue
except:
nzbtomedia.logger.error("EXTRACTOR: Extraction failed for %s. Could not call command %s" % (filePath, cmd))
core.logger.error("EXTRACTOR: Extraction failed for %s. Could not call command %s" % (filePath, cmd))
os.chdir(pwd)
return False
@ -156,5 +156,5 @@ def extract(filePath, outputDestination):
except: pass
return True
else:
nzbtomedia.logger.error("EXTRACTOR: Extraction failed for %s. Result was %s" % (filePath, res))
core.logger.error("EXTRACTOR: Extraction failed for %s. Result was %s" % (filePath, res))
return False

View file

@ -4,7 +4,7 @@ import os
import sys
import threading
import logging
import nzbtomedia
import core
# number of log files to keep
NUM_LOGS = 3
@ -92,7 +92,7 @@ class NTMRotatingLogHandler(object):
logging.getLogger('postprocess').addHandler(console)
logging.getLogger('db').addHandler(console)
self.log_file_path = os.path.join(nzbtomedia.LOG_DIR, self.log_file)
self.log_file_path = os.path.join(core.LOG_DIR, self.log_file)
self.cur_handler = self._config_handler()
@ -205,7 +205,7 @@ class NTMRotatingLogHandler(object):
try:
if logLevel == DEBUG:
if nzbtomedia.LOG_DEBUG == 1:
if core.LOG_DEBUG == 1:
ntm_logger.debug(out_line)
elif logLevel == MESSAGE:
ntm_logger.info(out_line)
@ -216,7 +216,7 @@ class NTMRotatingLogHandler(object):
elif logLevel == POSTPROCESS:
pp_logger.postprocess(out_line)
elif logLevel == DB:
if nzbtomedia.LOG_DB == 1:
if core.LOG_DB == 1:
db_logger.db(out_line)
else:
ntm_logger.info(logLevel, out_line)
@ -227,9 +227,9 @@ class NTMRotatingLogHandler(object):
log(error_msg, ERROR)
if os.environ.has_key('NZBOP_SCRIPTDIR'):
sys.exit(nzbtomedia.NZBGET_POSTPROCESS_ERROR)
sys.exit(core.NZBGET_POSTPROCESS_ERROR)
elif not self.console_logging:
sys.exit(error_msg.encode(nzbtomedia.SYS_ENCODING, 'xmlcharrefreplace'))
sys.exit(error_msg.encode(core.SYS_ENCODING, 'xmlcharrefreplace'))
else:
sys.exit(1)
@ -242,7 +242,7 @@ class DispatchingFormatter:
formatter = self._formatters.get(record.name, self._default_formatter)
return formatter.format(record)
ntm_log_instance = NTMRotatingLogHandler(nzbtomedia.LOG_FILE, NUM_LOGS, LOG_SIZE)
ntm_log_instance = NTMRotatingLogHandler(core.LOG_FILE, NUM_LOGS, LOG_SIZE)
def log(toLog, logLevel=MESSAGE, section='MAIN'):
ntm_log_instance.log(toLog, logLevel, section)

View file

@ -1,42 +1,42 @@
import urllib
import nzbtomedia
import core
import requests
from nzbtomedia import logger
from core import logger
def autoFork(section, inputCategory):
# auto-detect correct section
# config settings
try:
host = nzbtomedia.CFG[section][inputCategory]["host"]
port = nzbtomedia.CFG[section][inputCategory]["port"]
host = core.CFG[section][inputCategory]["host"]
port = core.CFG[section][inputCategory]["port"]
except:
host = None
port = None
try:
username = nzbtomedia.CFG[section][inputCategory]["username"]
password = nzbtomedia.CFG[section][inputCategory]["password"]
username = core.CFG[section][inputCategory]["username"]
password = core.CFG[section][inputCategory]["password"]
except:
username = None
password = None
try:
apikey = nzbtomedia.CFG[section][inputCategory]["apikey"]
apikey = core.CFG[section][inputCategory]["apikey"]
except:
apikey = None
try:
ssl = int(nzbtomedia.CFG[section][inputCategory]["ssl"])
ssl = int(core.CFG[section][inputCategory]["ssl"])
except:
ssl = 0
try:
web_root = nzbtomedia.CFG[section][inputCategory]["web_root"]
web_root = core.CFG[section][inputCategory]["web_root"]
except:
web_root = ""
try:
fork = nzbtomedia.FORKS.items()[nzbtomedia.FORKS.keys().index(nzbtomedia.CFG[section][inputCategory]["fork"])]
fork = core.FORKS.items()[core.FORKS.keys().index(core.CFG[section][inputCategory]["fork"])]
except:
fork = "auto"
@ -61,7 +61,7 @@ def autoFork(section, inputCategory):
fork = ['default', {}]
elif fork == "auto":
params = nzbtomedia.ALL_FORKS
params = core.ALL_FORKS
rem_params = []
logger.info("Attempting to auto-detect %s fork" % inputCategory)
# define the order to test. Default must be first since the default fork doesn't reject parameters.
@ -86,7 +86,7 @@ def autoFork(section, inputCategory):
rem_params.append(param)
for param in rem_params:
params.pop(param)
for fork in sorted(nzbtomedia.FORKS.iteritems(), reverse=False):
for fork in sorted(core.FORKS.iteritems(), reverse=False):
if params == fork[1]:
detected = True
break
@ -97,7 +97,7 @@ def autoFork(section, inputCategory):
fork = ['custom', params]
else:
logger.info("%s:%s fork auto-detection failed" % (section, inputCategory))
fork = nzbtomedia.FORKS.items()[nzbtomedia.FORKS.keys().index(nzbtomedia.FORK_DEFAULT)]
fork = core.FORKS.items()[core.FORKS.keys().index(core.FORK_DEFAULT)]
logger.info("%s:%s fork set to %s" % (section, inputCategory, fork[0]))
return fork[0], fork[1]

View file

@ -1,9 +1,9 @@
import os
import shutil
import copy
import nzbtomedia
import core
from configobj import *
from nzbtomedia import logger
from core import logger
from itertools import chain
@ -82,7 +82,7 @@ class Section(configobj.Section):
class ConfigObj(configobj.ConfigObj, Section):
def __init__(self, *args, **kw):
if len(args) == 0:
args = (nzbtomedia.CONFIG_FILE,)
args = (core.CONFIG_FILE,)
super(configobj.ConfigObj, self).__init__(*args, **kw)
self.interpolation = False
@ -107,17 +107,17 @@ class ConfigObj(configobj.ConfigObj, Section):
try:
# check for autoProcessMedia.cfg and create if it does not exist
if not os.path.isfile(nzbtomedia.CONFIG_FILE):
shutil.copyfile(nzbtomedia.CONFIG_SPEC_FILE, nzbtomedia.CONFIG_FILE)
CFG_OLD = config(nzbtomedia.CONFIG_FILE)
if not os.path.isfile(core.CONFIG_FILE):
shutil.copyfile(core.CONFIG_SPEC_FILE, core.CONFIG_FILE)
CFG_OLD = config(core.CONFIG_FILE)
except Exception, e:
logger.debug("Error %s when copying to .cfg" % (e))
try:
# check for autoProcessMedia.cfg.spec and create if it does not exist
if not os.path.isfile(nzbtomedia.CONFIG_SPEC_FILE):
shutil.copyfile(nzbtomedia.CONFIG_FILE, nzbtomedia.CONFIG_SPEC_FILE)
CFG_NEW = config(nzbtomedia.CONFIG_SPEC_FILE)
if not os.path.isfile(core.CONFIG_SPEC_FILE):
shutil.copyfile(core.CONFIG_FILE, core.CONFIG_SPEC_FILE)
CFG_NEW = config(core.CONFIG_SPEC_FILE)
except Exception, e:
logger.debug("Error %s when copying to .spec" % (e))
@ -229,11 +229,11 @@ class ConfigObj(configobj.ConfigObj, Section):
process_section(section, subsection)
# create a backup of our old config
CFG_OLD.filename = nzbtomedia.CONFIG_FILE + ".old"
CFG_OLD.filename = core.CONFIG_FILE + ".old"
CFG_OLD.write()
# write our new config to autoProcessMedia.cfg
CFG_NEW.filename = nzbtomedia.CONFIG_FILE
CFG_NEW.filename = core.CONFIG_FILE
CFG_NEW.write()
return True
@ -437,7 +437,7 @@ class ConfigObj(configobj.ConfigObj, Section):
try:
# write our new config to autoProcessMedia.cfg
CFG_NEW.filename = nzbtomedia.CONFIG_FILE
CFG_NEW.filename = core.CONFIG_FILE
CFG_NEW.write()
except Exception, e:
logger.debug("Error %s when writing changes to .cfg" % (e))

View file

@ -4,8 +4,8 @@ import re
import sqlite3
import time
import nzbtomedia
from nzbtomedia import logger
import core
from core import logger
def dbFilename(filename="nzbtomedia.db", suffix=None):
"""
@ -17,7 +17,7 @@ def dbFilename(filename="nzbtomedia.db", suffix=None):
"""
if suffix:
filename = "%s.%s" % (filename, suffix)
return nzbtomedia.os.path.join(nzbtomedia.PROGRAM_DIR, filename)
return core.os.path.join(core.PROGRAM_DIR, filename)
class DBConnection:

View file

@ -1,9 +1,9 @@
import os
import re
import nzbtomedia
import core
import shlex
from nzbtomedia import logger
from nzbtomedia.nzbToMediaUtil import listMediaFiles
from core import logger
from core.nzbToMediaUtil import listMediaFiles
reverse_list = [r"\.\d{2}e\d{2}s\.", r"\.[pi]0801\.", r"\.p027\.", r"\.[pi]675\.", r"\.[pi]084\.", r"\.p063\.", r"\b[45]62[xh]\.", r"\.yarulb\.", r"\.vtd[hp]\.",
r"\.ld[.-]?bew\.", r"\.pir.?(dov|dvd|bew|db|rb)\.", r"\brdvd\.", r"\.vts\.", r"\.reneercs\.", r"\.dcv\.", r"\b(pir|mac)dh\b", r"\.reporp\.", r"\.kcaper\.",
@ -34,18 +34,18 @@ def process_all_exceptions(name, dirname):
newfilename = filename
if not newfilename:
newfilename = exception(filename, parentDir, name)
if nzbtomedia.GROUPS:
if core.GROUPS:
newfilename = strip_groups(newfilename)
if newfilename != filename:
rename_file(filename, newfilename)
def strip_groups(filename):
if not nzbtomedia.GROUPS:
if not core.GROUPS:
return filename
dirname, file = os.path.split(filename)
head, fileExtension = os.path.splitext(file)
newname = head.replace(' ', '.')
for group in nzbtomedia.GROUPS:
for group in core.GROUPS:
newname = newname.replace(group, '')
newname = newname.replace('[]', '')
newfile = newname + fileExtension

View file

@ -1,44 +1,44 @@
import os
import nzbtomedia
import core
from subprocess import Popen
from nzbtomedia.transcoder import transcoder
from nzbtomedia.nzbToMediaUtil import import_subs, listMediaFiles, rmDir
from nzbtomedia import logger
from core.transcoder import transcoder
from core.nzbToMediaUtil import import_subs, listMediaFiles, rmDir
from core import logger
def external_script(outputDestination, torrentName, torrentLabel, settings):
final_result = 0 # start at 0.
num_files = 0
try:
nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS = settings["user_script_mediaExtensions"]
if isinstance(nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS, str): nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS = nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS.split(',')
core.USER_SCRIPT_MEDIAEXTENSIONS = settings["user_script_mediaExtensions"]
if isinstance(core.USER_SCRIPT_MEDIAEXTENSIONS, str): core.USER_SCRIPT_MEDIAEXTENSIONS = core.USER_SCRIPT_MEDIAEXTENSIONS.split(',')
except:
nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS = []
core.USER_SCRIPT_MEDIAEXTENSIONS = []
try:
nzbtomedia.USER_SCRIPT = settings["user_script_path"]
core.USER_SCRIPT = settings["user_script_path"]
except:
nzbtomedia.USER_SCRIPT = None
if nzbtomedia.USER_SCRIPT is None or nzbtomedia.USER_SCRIPT == "None": # do nothing and return success.
core.USER_SCRIPT = None
if core.USER_SCRIPT is None or core.USER_SCRIPT == "None": # do nothing and return success.
return [0, ""]
try:
nzbtomedia.USER_SCRIPT_PARAM = settings["user_script_param"]
if isinstance(nzbtomedia.USER_SCRIPT_PARAM, str): nzbtomedia.USER_SCRIPT_PARAM = nzbtomedia.USER_SCRIPT_PARAM.split(',')
core.USER_SCRIPT_PARAM = settings["user_script_param"]
if isinstance(core.USER_SCRIPT_PARAM, str): core.USER_SCRIPT_PARAM = core.USER_SCRIPT_PARAM.split(',')
except:
nzbtomedia.USER_SCRIPT_PARAM = []
core.USER_SCRIPT_PARAM = []
try:
nzbtomedia.USER_SCRIPT_SUCCESSCODES = settings["user_script_successCodes"]
if isinstance(nzbtomedia.USER_SCRIPT_SUCCESSCODES, str): nzbtomedia.USER_SCRIPT_SUCCESSCODES = nzbtomedia.USER_SCRIPT_SUCCESSCODES.split(',')
core.USER_SCRIPT_SUCCESSCODES = settings["user_script_successCodes"]
if isinstance(core.USER_SCRIPT_SUCCESSCODES, str): core.USER_SCRIPT_SUCCESSCODES = core.USER_SCRIPT_SUCCESSCODES.split(',')
except:
nzbtomedia.USER_SCRIPT_SUCCESSCODES = 0
core.USER_SCRIPT_SUCCESSCODES = 0
try:
nzbtomedia.USER_SCRIPT_CLEAN = int(settings["user_script_clean"])
core.USER_SCRIPT_CLEAN = int(settings["user_script_clean"])
except:
nzbtomedia.USER_SCRIPT_CLEAN = 1
core.USER_SCRIPT_CLEAN = 1
try:
nzbtomedia.USER_SCRIPT_RUNONCE = int(settings["user_script_runOnce"])
core.USER_SCRIPT_RUNONCE = int(settings["user_script_runOnce"])
except:
nzbtomedia.USER_SCRIPT_RUNONCE = 1
core.USER_SCRIPT_RUNONCE = 1
if nzbtomedia.CHECK_MEDIA:
if core.CHECK_MEDIA:
for video in listMediaFiles(outputDestination, media=True, audio=False, meta=False, archives=False):
if transcoder.isVideoGood(video, 0):
import_subs(video)
@ -49,15 +49,15 @@ def external_script(outputDestination, torrentName, torrentLabel, settings):
for dirpath, dirnames, filenames in os.walk(outputDestination):
for file in filenames:
filePath = nzbtomedia.os.path.join(dirpath, file)
filePath = core.os.path.join(dirpath, file)
fileName, fileExtension = os.path.splitext(file)
if fileExtension in nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS or "ALL" in nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS:
if fileExtension in core.USER_SCRIPT_MEDIAEXTENSIONS or "ALL" in core.USER_SCRIPT_MEDIAEXTENSIONS:
num_files = num_files + 1
if nzbtomedia.USER_SCRIPT_RUNONCE == 1 and num_files > 1: # we have already run once, so just continue to get number of files.
if core.USER_SCRIPT_RUNONCE == 1 and num_files > 1: # we have already run once, so just continue to get number of files.
continue
command = [nzbtomedia.USER_SCRIPT]
for param in nzbtomedia.USER_SCRIPT_PARAM:
command = [core.USER_SCRIPT]
for param in core.USER_SCRIPT_PARAM:
if param == "FN":
command.append('%s' % file)
continue
@ -71,7 +71,7 @@ def external_script(outputDestination, torrentName, torrentLabel, settings):
command.append('%s' % torrentLabel)
continue
elif param == "DN":
if nzbtomedia.USER_SCRIPT_RUNONCE == 1:
if core.USER_SCRIPT_RUNONCE == 1:
command.append('%s' % outputDestination)
else:
command.append('%s' % dirpath)
@ -86,7 +86,7 @@ def external_script(outputDestination, torrentName, torrentLabel, settings):
try:
p = Popen(command)
res = p.wait()
if str(res) in nzbtomedia.USER_SCRIPT_SUCCESSCODES: # Linux returns 0 for successful.
if str(res) in core.USER_SCRIPT_SUCCESSCODES: # Linux returns 0 for successful.
logger.info("UserScript %s was successfull" % (command[0]))
result = 0
else:
@ -103,16 +103,16 @@ def external_script(outputDestination, torrentName, torrentLabel, settings):
num_files_new = 0
for dirpath, dirnames, filenames in os.walk(outputDestination):
for file in filenames:
filePath = nzbtomedia.os.path.join(dirpath, file)
filePath = core.os.path.join(dirpath, file)
fileName, fileExtension = os.path.splitext(file)
if fileExtension in nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS or nzbtomedia.USER_SCRIPT_MEDIAEXTENSIONS == "ALL":
if fileExtension in core.USER_SCRIPT_MEDIAEXTENSIONS or core.USER_SCRIPT_MEDIAEXTENSIONS == "ALL":
num_files_new = num_files_new + 1
if nzbtomedia.USER_SCRIPT_CLEAN == int(1) and num_files_new == 0 and final_result == 0:
if core.USER_SCRIPT_CLEAN == int(1) and num_files_new == 0 and final_result == 0:
logger.info("All files have been processed. Cleaning outputDirectory %s" % (outputDestination))
rmDir(outputDestination)
elif nzbtomedia.USER_SCRIPT_CLEAN == int(1) and num_files_new != 0:
elif core.USER_SCRIPT_CLEAN == int(1) and num_files_new != 0:
logger.info("%s files were processed, but %s still remain. outputDirectory will not be cleaned." % (
num_files, num_files_new))
return [final_result, '']

View file

@ -11,16 +11,16 @@ import platform
import guessit
import beets
import requests
import nzbtomedia
import core
from babelfish import Language
import subliminal
from nzbtomedia.extractor import extractor
from nzbtomedia.linktastic import linktastic
from nzbtomedia.synchronousdeluge.client import DelugeClient
from nzbtomedia.utorrent.client import UTorrentClient
from nzbtomedia.transmissionrpc.client import Client as TransmissionClient
from nzbtomedia import logger, nzbToMediaDB
from core.extractor import extractor
from core.linktastic import linktastic
from core.synchronousdeluge.client import DelugeClient
from core.utorrent.client import UTorrentClient
from core.transmissionrpc.client import Client as TransmissionClient
from core import logger, nzbToMediaDB
def reportNzb(failure_link, clientAgent):
# Contact indexer site
@ -56,7 +56,7 @@ def sanitizeName(name):
# remove leading/trailing periods and spaces
name = name.strip(' .')
try:
name = name.encode(nzbtomedia.SYS_ENCODING)
name = name.encode(core.SYS_ENCODING)
except: pass
return name
@ -70,7 +70,7 @@ def makeDir(path):
return True
def remoteDir(path):
for local,remote in nzbtomedia.REMOTEPATHS:
for local,remote in core.REMOTEPATHS:
if local in path:
base_dirs = path.replace(local,"").split(os.sep)
if '/' in remote:
@ -88,10 +88,10 @@ def category_search(inputDirectory, inputName, inputCategory, root, categories):
tordir = False
try:
inputName = inputName.encode(nzbtomedia.SYS_ENCODING)
inputName = inputName.encode(core.SYS_ENCODING)
except: pass
try:
inputDirectory = inputDirectory.encode(nzbtomedia.SYS_ENCODING)
inputDirectory = inputDirectory.encode(core.SYS_ENCODING)
except: pass
if inputDirectory is None: # =Nothing to process here.
@ -183,7 +183,7 @@ def is_minSize(inputName, minSize):
# audio files we need to check directory size not file size
inputSize = os.path.getsize(inputName)
if fileExt in (nzbtomedia.AUDIOCONTAINER):
if fileExt in (core.AUDIOCONTAINER):
try:
inputSize = getDirSize(os.path.dirname(inputName))
except:
@ -327,9 +327,9 @@ def TestCon(host, port):
def WakeUp():
host = nzbtomedia.CFG["WakeOnLan"]["host"]
port = int(nzbtomedia.CFG["WakeOnLan"]["port"])
mac = nzbtomedia.CFG["WakeOnLan"]["mac"]
host = core.CFG["WakeOnLan"]["host"]
port = int(core.CFG["WakeOnLan"]["port"])
mac = core.CFG["WakeOnLan"]["mac"]
i = 1
while TestCon(host, port) == "Down" and i < 4:
@ -355,7 +355,7 @@ def CharReplace(Name):
encoded = False
encoding = None
if isinstance(Name, unicode):
return encoded, Name.encode(nzbtomedia.SYS_ENCODING)
return encoded, Name.encode(core.SYS_ENCODING)
for Idx in range(len(Name)):
# /!\ detection is done 2char by 2char for UTF-8 special character
if (len(Name) != 1) & (Idx < (len(Name) - 1)):
@ -380,14 +380,14 @@ def CharReplace(Name):
elif (Name[Idx] >= '\xA6') & (Name[Idx] <= '\xFF'):
encoding = 'iso-8859-15'
break
if encoding and not encoding == nzbtomedia.SYS_ENCODING:
if encoding and not encoding == core.SYS_ENCODING:
encoded = True
Name = Name.decode(encoding).encode(nzbtomedia.SYS_ENCODING)
Name = Name.decode(encoding).encode(core.SYS_ENCODING)
return encoded, Name
def convert_to_ascii(inputName, dirName):
ascii_convert = int(nzbtomedia.CFG["ASCII"]["convert"])
ascii_convert = int(core.CFG["ASCII"]["convert"])
if ascii_convert == 0 or os.name == 'nt': # just return if we don't want to convert or on windows os and "\" is replaced!.
return inputName, dirName
@ -477,7 +477,7 @@ def parse_deluge(args):
inputHash = args[1]
inputID = args[1]
try:
inputCategory = nzbtomedia.TORRENT_CLASS.core.get_torrent_status(inputID, ['label']).get()['label']
inputCategory = core.TORRENT_CLASS.core.get_torrent_status(inputID, ['label']).get()['label']
except:
inputCategory = ''
return inputDirectory, inputName, inputCategory, inputHash, inputID
@ -564,7 +564,7 @@ def getDirs(section, subsection, link = 'hard'):
newPath = None
fileExt = os.path.splitext(mediafile)[1]
try:
if fileExt in nzbtomedia.AUDIOCONTAINER:
if fileExt in core.AUDIOCONTAINER:
f = beets.mediafile.MediaFile(mediafile)
# get artist and album info
@ -573,7 +573,7 @@ def getDirs(section, subsection, link = 'hard'):
# create new path
newPath = os.path.join(path, "%s - %s" % (sanitizeName(artist), sanitizeName(album)))
elif fileExt in nzbtomedia.MEDIACONTAINER:
elif fileExt in core.MEDIACONTAINER:
f = guessit.guess_video_info(mediafile)
# get title
@ -595,7 +595,7 @@ def getDirs(section, subsection, link = 'hard'):
newPath = os.path.join(path, sanitizeName(title))
try:
newPath = newPath.encode(nzbtomedia.SYS_ENCODING)
newPath = newPath.encode(core.SYS_ENCODING)
except: pass
# Just fail-safe incase we already have afile with this clean-name (was actually a bug from earlier code, but let's be safe).
@ -609,7 +609,7 @@ def getDirs(section, subsection, link = 'hard'):
newfile = os.path.join(newPath, sanitizeName(os.path.split(mediafile)[1]))
try:
newfile = newfile.encode(nzbtomedia.SYS_ENCODING)
newfile = newfile.encode(core.SYS_ENCODING)
except: pass
# link file to its new path
@ -629,21 +629,21 @@ def getDirs(section, subsection, link = 'hard'):
return folders
try:
watch_dir = os.path.join(nzbtomedia.CFG[section][subsection]["watch_dir"], subsection)
watch_dir = os.path.join(core.CFG[section][subsection]["watch_dir"], subsection)
if os.path.exists(watch_dir):
to_return.extend(processDir(watch_dir))
elif os.path.exists(nzbtomedia.CFG[section][subsection]["watch_dir"]):
to_return.extend(processDir(nzbtomedia.CFG[section][subsection]["watch_dir"]))
elif os.path.exists(core.CFG[section][subsection]["watch_dir"]):
to_return.extend(processDir(core.CFG[section][subsection]["watch_dir"]))
except Exception as e:
logger.error("Failed to add directories from %s for post-processing: %s" % (nzbtomedia.CFG[section][subsection]["watch_dir"], e))
logger.error("Failed to add directories from %s for post-processing: %s" % (core.CFG[section][subsection]["watch_dir"], e))
if nzbtomedia.USELINK == 'move':
if core.USELINK == 'move':
try:
outputDirectory = os.path.join(nzbtomedia.OUTPUTDIRECTORY, subsection)
outputDirectory = os.path.join(core.OUTPUTDIRECTORY, subsection)
if os.path.exists(outputDirectory):
to_return.extend(processDir(outputDirectory))
except Exception as e:
logger.error("Failed to add directories from %s for post-processing: %s" % (nzbtomedia.OUTPUTDIRECTORY, e))
logger.error("Failed to add directories from %s for post-processing: %s" % (core.OUTPUTDIRECTORY, e))
if not to_return:
logger.debug("No directories identified in %s:%s for post-processing" % (section,subsection))
@ -679,15 +679,15 @@ def cleanDir(path, section, subsection):
if not os.path.exists(path):
logger.info('Directory %s has been processed and removed ...' % (path), 'CLEANDIR')
return
if nzbtomedia.FORCE_CLEAN:
if core.FORCE_CLEAN:
logger.info('Doing Forceful Clean of %s' % (path), 'CLEANDIR')
rmDir(path)
return
try:
minSize = int(nzbtomedia.CFG[section][subsection]['minSize'])
minSize = int(core.CFG[section][subsection]['minSize'])
except:minSize = 0
try:
delete_ignored = int(nzbtomedia.CFG[section][subsection]['delete_ignored'])
delete_ignored = int(core.CFG[section][subsection]['delete_ignored'])
except:delete_ignored = 0
try:
num_files = len(listMediaFiles(path, minSize=minSize, delete_ignored=delete_ignored))
@ -711,27 +711,27 @@ def create_torrent_class(clientAgent):
if clientAgent == 'utorrent':
try:
logger.debug("Connecting to %s: %s" % (clientAgent, nzbtomedia.UTORRENTWEBUI))
tc = UTorrentClient(nzbtomedia.UTORRENTWEBUI, nzbtomedia.UTORRENTUSR, nzbtomedia.UTORRENTPWD)
logger.debug("Connecting to %s: %s" % (clientAgent, core.UTORRENTWEBUI))
tc = UTorrentClient(core.UTORRENTWEBUI, core.UTORRENTUSR, core.UTORRENTPWD)
except:
logger.error("Failed to connect to uTorrent")
if clientAgent == 'transmission':
try:
logger.debug("Connecting to %s: http://%s:%s" % (
clientAgent, nzbtomedia.TRANSMISSIONHOST, nzbtomedia.TRANSMISSIONPORT))
tc = TransmissionClient(nzbtomedia.TRANSMISSIONHOST, nzbtomedia.TRANSMISSIONPORT,
nzbtomedia.TRANSMISSIONUSR,
nzbtomedia.TRANSMISSIONPWD)
clientAgent, core.TRANSMISSIONHOST, core.TRANSMISSIONPORT))
tc = TransmissionClient(core.TRANSMISSIONHOST, core.TRANSMISSIONPORT,
core.TRANSMISSIONUSR,
core.TRANSMISSIONPWD)
except:
logger.error("Failed to connect to Transmission")
if clientAgent == 'deluge':
try:
logger.debug("Connecting to %s: http://%s:%s" % (clientAgent, nzbtomedia.DELUGEHOST, nzbtomedia.DELUGEPORT))
logger.debug("Connecting to %s: http://%s:%s" % (clientAgent, core.DELUGEHOST, core.DELUGEPORT))
tc = DelugeClient()
tc.connect(host=nzbtomedia.DELUGEHOST, port=nzbtomedia.DELUGEPORT, username=nzbtomedia.DELUGEUSR,
password=nzbtomedia.DELUGEPWD)
tc.connect(host=core.DELUGEHOST, port=core.DELUGEPORT, username=core.DELUGEUSR,
password=core.DELUGEPWD)
except:
logger.error("Failed to connect to Deluge")
@ -740,12 +740,12 @@ def create_torrent_class(clientAgent):
def pause_torrent(clientAgent, inputHash, inputID, inputName):
logger.debug("Stopping torrent %s in %s while processing" % (inputName, clientAgent))
try:
if clientAgent == 'utorrent' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.stop(inputHash)
if clientAgent == 'transmission' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.stop_torrent(inputID)
if clientAgent == 'deluge' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.core.pause_torrent([inputID])
if clientAgent == 'utorrent' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.stop(inputHash)
if clientAgent == 'transmission' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.stop_torrent(inputID)
if clientAgent == 'deluge' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.core.pause_torrent([inputID])
time.sleep(5)
except:
logger.warning("Failed to stop torrent %s in %s" % (inputName, clientAgent))
@ -753,27 +753,27 @@ def pause_torrent(clientAgent, inputHash, inputID, inputName):
def resume_torrent(clientAgent, inputHash, inputID, inputName):
logger.debug("Starting torrent %s in %s" % (inputName, clientAgent))
try:
if clientAgent == 'utorrent' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.start(inputHash)
if clientAgent == 'transmission' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.start_torrent(inputID)
if clientAgent == 'deluge' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.core.resume_torrent([inputID])
if clientAgent == 'utorrent' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.start(inputHash)
if clientAgent == 'transmission' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.start_torrent(inputID)
if clientAgent == 'deluge' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.core.resume_torrent([inputID])
time.sleep(5)
except:
logger.warning("Failed to start torrent %s in %s" % (inputName, clientAgent))
def remove_torrent(clientAgent, inputHash, inputID, inputName):
if nzbtomedia.DELETE_ORIGINAL == 1 or nzbtomedia.USELINK == 'move':
if core.DELETE_ORIGINAL == 1 or core.USELINK == 'move':
logger.debug("Deleting torrent %s from %s" % (inputName, clientAgent))
try:
if clientAgent == 'utorrent' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.removedata(inputHash)
nzbtomedia.TORRENT_CLASS.remove(inputHash)
if clientAgent == 'transmission' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.remove_torrent(inputID, True)
if clientAgent == 'deluge' and nzbtomedia.TORRENT_CLASS != "":
nzbtomedia.TORRENT_CLASS.core.remove_torrent(inputID, True)
if clientAgent == 'utorrent' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.removedata(inputHash)
core.TORRENT_CLASS.remove(inputHash)
if clientAgent == 'transmission' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.remove_torrent(inputID, True)
if clientAgent == 'deluge' and core.TORRENT_CLASS != "":
core.TORRENT_CLASS.core.remove_torrent(inputID, True)
time.sleep(5)
except:
logger.warning("Failed to delete torrent %s in %s" % (inputName, clientAgent))
@ -783,12 +783,12 @@ def remove_torrent(clientAgent, inputHash, inputID, inputName):
def find_download(clientAgent, download_id):
logger.debug("Searching for Download on %s ..." % (clientAgent))
if clientAgent == 'utorrent':
torrents = nzbtomedia.TORRENT_CLASS.list()[1]['torrents']
torrents = core.TORRENT_CLASS.list()[1]['torrents']
for torrent in torrents:
if download_id in torrent:
return True
if clientAgent == 'transmission':
torrents = nzbtomedia.TORRENT_CLASS.get_torrents()
torrents = core.TORRENT_CLASS.get_torrents()
for torrent in torrents:
hash = torrent.hashString
if hash == download_id:
@ -796,10 +796,10 @@ def find_download(clientAgent, download_id):
if clientAgent == 'deluge':
return False
if clientAgent == 'sabnzbd':
baseURL = "http://%s:%s/api" % (nzbtomedia.SABNZBDHOST, nzbtomedia.SABNZBDPORT)
baseURL = "http://%s:%s/api" % (core.SABNZBDHOST, core.SABNZBDPORT)
url = baseURL
params = {}
params['apikey'] = nzbtomedia.SABNZBDAPIKEY
params['apikey'] = core.SABNZBDAPIKEY
params['mode'] = "get_files"
params['output'] = 'json'
params['value'] = download_id
@ -817,10 +817,10 @@ def find_download(clientAgent, download_id):
def get_nzoid(inputName):
nzoid = None
logger.debug("Searching for nzoid from SAbnzbd ...")
baseURL = "http://%s:%s/api" % (nzbtomedia.SABNZBDHOST, nzbtomedia.SABNZBDPORT)
baseURL = "http://%s:%s/api" % (core.SABNZBDHOST, core.SABNZBDPORT)
url = baseURL
params = {}
params['apikey'] = nzbtomedia.SABNZBDAPIKEY
params['apikey'] = core.SABNZBDAPIKEY
params['mode'] = "queue"
params['output'] = 'json'
try:
@ -861,7 +861,7 @@ def cleanFileName(filename):
def is_archive_file(filename):
"""Check if the filename is allowed for the Archive"""
for regext in nzbtomedia.COMPRESSEDCONTAINER:
for regext in core.COMPRESSEDCONTAINER:
if regext.search(filename):
return regext.split(filename)[0]
return False
@ -873,9 +873,9 @@ def isMediaFile(mediafile, media=True, audio=True, meta=True, archives=True):
if fileName.startswith('._'):
return False
if (media and fileExt.lower() in nzbtomedia.MEDIACONTAINER)\
or (audio and fileExt.lower() in nzbtomedia.AUDIOCONTAINER)\
or (meta and fileExt.lower() in nzbtomedia.METACONTAINER)\
if (media and fileExt.lower() in core.MEDIACONTAINER)\
or (audio and fileExt.lower() in core.AUDIOCONTAINER)\
or (meta and fileExt.lower() in core.METACONTAINER)\
or (archives and is_archive_file(mediafile)):
return True
else:
@ -1022,7 +1022,7 @@ def extractFiles(src, dst=None):
logger.error("Unable to remove file %s due to: %s" % (inputFile, e))
def import_subs(filename):
if not nzbtomedia.GETSUBS:
if not core.GETSUBS:
return
try:
subliminal.cache_region.configure('dogpile.cache.memory')
@ -1030,7 +1030,7 @@ def import_subs(filename):
pass
languages = set()
for item in nzbtomedia.SLANGUAGES:
for item in core.SLANGUAGES:
try:
languages.add(Language(item))
except:
@ -1116,7 +1116,7 @@ class RunningProcess():
class WindowsProcess():
def __init__(self):
self.mutexname = "nzbtomedia_" + nzbtomedia.PID_FILE.replace('\\','/') # {D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"
self.mutexname = "nzbtomedia_" + core.PID_FILE.replace('\\','/') # {D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"
if platform.system() == 'Windows':
from win32event import CreateMutex
from win32api import CloseHandle, GetLastError
@ -1143,7 +1143,7 @@ class WindowsProcess():
class PosixProcess():
def __init__(self):
self.pidpath = nzbtomedia.PID_FILE
self.pidpath = core.PID_FILE
self.lock_socket = None
def alreadyrunning(self):

View file

@ -19,5 +19,5 @@ __title__ = "synchronous-deluge"
__version__ = "0.1"
__author__ = "Christian Dale"
from nzbtomedia.synchronousdeluge.exceptions import DelugeRPCError
from core.synchronousdeluge.exceptions import DelugeRPCError

View file

@ -3,7 +3,7 @@ import struct
import socket
import ssl
from nzbtomedia.synchronousdeluge import rencode
from core.synchronousdeluge import rencode
__all__ = ["DelugeTransfer"]

View file

@ -4,21 +4,21 @@ import platform
import subprocess
import urllib2
import traceback
import nzbtomedia
import core
import json
import shutil
import re
from nzbtomedia import logger
from nzbtomedia.nzbToMediaUtil import makeDir
from core import logger
from core.nzbToMediaUtil import makeDir
def isVideoGood(videofile, status):
fileNameExt = os.path.basename(videofile)
fileName, fileExt = os.path.splitext(fileNameExt)
disable = False
if fileExt not in nzbtomedia.MEDIACONTAINER or not nzbtomedia.FFPROBE or not nzbtomedia.CHECK_MEDIA or fileExt in ['.iso']:
if fileExt not in core.MEDIACONTAINER or not core.FFPROBE or not core.CHECK_MEDIA or fileExt in ['.iso']:
disable = True
else:
test_details, res = getVideoDetails(nzbtomedia.TEST_FILE)
test_details, res = getVideoDetails(core.TEST_FILE)
if res !=0 or test_details.get("error"):
disable = True
logger.info("DISABLED: ffprobe failed to analyse test file. Stopping corruption check.", 'TRANSCODER')
@ -55,7 +55,7 @@ def isVideoGood(videofile, status):
def zip_out(file, img, bitbucket):
procin = None
cmd = [nzbtomedia.SEVENZIP, '-so', 'e', img, file]
cmd = [core.SEVENZIP, '-so', 'e', img, file]
try:
procin = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=bitbucket)
except:
@ -66,16 +66,16 @@ def getVideoDetails(videofile, img=None, bitbucket=None):
video_details = {}
result = 1
file = videofile
if not nzbtomedia.FFPROBE:
if not core.FFPROBE:
return video_details, result
if 'avprobe' in nzbtomedia.FFPROBE:
if 'avprobe' in core.FFPROBE:
print_format = '-of'
else:
print_format = '-print_format'
try:
if img:
videofile = '-'
command = [nzbtomedia.FFPROBE, '-v', 'quiet', print_format, 'json', '-show_format', '-show_streams', '-show_error', videofile]
command = [core.FFPROBE, '-v', 'quiet', print_format, 'json', '-show_format', '-show_streams', '-show_error', videofile]
print_cmd(command)
if img:
procin = zip_out(file, img, bitbucket)
@ -89,7 +89,7 @@ def getVideoDetails(videofile, img=None, bitbucket=None):
except: pass
if not video_details:
try:
command = [nzbtomedia.FFPROBE, '-v', 'quiet', print_format, 'json', '-show_format', '-show_streams', videofile]
command = [core.FFPROBE, '-v', 'quiet', print_format, 'json', '-show_format', '-show_streams', videofile]
if img:
procin = zip_out(file, img)
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=procin.stdout)
@ -112,14 +112,14 @@ def buildCommands(file, newDir, movieName, bitbucket):
dir, name = os.path.split(file)
name, ext = os.path.splitext(name)
check = re.match("VTS_([0-9][0-9])_[0-9]+", name)
if check and nzbtomedia.CONCAT:
if check and core.CONCAT:
name = movieName
elif check:
name = ('%s.cd%s' % (movieName, check.groups()[0]))
elif nzbtomedia.CONCAT and re.match("(.+)[cC][dD][0-9]", name):
elif core.CONCAT and re.match("(.+)[cC][dD][0-9]", name):
name = re.sub("([\ \.\-\_\=\:]+[cC][dD][0-9])", "", name)
if ext == nzbtomedia.VEXTENSION and newDir == dir: # we need to change the name to prevent overwriting itself.
nzbtomedia.VEXTENSION = '-transcoded' + nzbtomedia.VEXTENSION # adds '-transcoded.ext'
if ext == core.VEXTENSION and newDir == dir: # we need to change the name to prevent overwriting itself.
core.VEXTENSION = '-transcoded' + core.VEXTENSION # adds '-transcoded.ext'
else:
img, data = file.iteritems().next()
name = data['name']
@ -127,7 +127,7 @@ def buildCommands(file, newDir, movieName, bitbucket):
inputFile = '-'
file = '-'
newfilePath = os.path.normpath(os.path.join(newDir, name) + nzbtomedia.VEXTENSION)
newfilePath = os.path.normpath(os.path.join(newDir, name) + core.VEXTENSION)
map_cmd = []
video_cmd = []
@ -144,53 +144,53 @@ def buildCommands(file, newDir, movieName, bitbucket):
subStreams = []
map_cmd.extend(['-map', '0'])
if nzbtomedia.VCODEC:
video_cmd.extend(['-c:v', nzbtomedia.VCODEC])
if nzbtomedia.VCODEC == 'libx264' and nzbtomedia.VPRESET:
video_cmd.extend(['-pre', nzbtomedia.VPRESET])
if core.VCODEC:
video_cmd.extend(['-c:v', core.VCODEC])
if core.VCODEC == 'libx264' and core.VPRESET:
video_cmd.extend(['-pre', core.VPRESET])
else:
video_cmd.extend(['-c:v', 'copy'])
if nzbtomedia.VFRAMERATE:
video_cmd.extend(['-r', str(nzbtomedia.VFRAMERATE)])
if nzbtomedia.VBITRATE:
video_cmd.extend(['-b:v', str(nzbtomedia.VBITRATE)])
if nzbtomedia.VRESOLUTION:
video_cmd.extend(['-vf', 'scale=' + nzbtomedia.VRESOLUTION])
if nzbtomedia.VPRESET:
video_cmd.extend(['-preset', nzbtomedia.VPRESET])
if nzbtomedia.VCRF:
video_cmd.extend(['-crf', str(nzbtomedia.VCRF)])
if nzbtomedia.VLEVEL:
video_cmd.extend(['-level', str(nzbtomedia.VLEVEL)])
if core.VFRAMERATE:
video_cmd.extend(['-r', str(core.VFRAMERATE)])
if core.VBITRATE:
video_cmd.extend(['-b:v', str(core.VBITRATE)])
if core.VRESOLUTION:
video_cmd.extend(['-vf', 'scale=' + core.VRESOLUTION])
if core.VPRESET:
video_cmd.extend(['-preset', core.VPRESET])
if core.VCRF:
video_cmd.extend(['-crf', str(core.VCRF)])
if core.VLEVEL:
video_cmd.extend(['-level', str(core.VLEVEL)])
if nzbtomedia.ACODEC:
audio_cmd.extend(['-c:a', nzbtomedia.ACODEC])
if nzbtomedia.ACODEC == 'aac': # Allow users to use the experimental AAC codec that's built into recent versions of ffmpeg
if core.ACODEC:
audio_cmd.extend(['-c:a', core.ACODEC])
if core.ACODEC == 'aac': # Allow users to use the experimental AAC codec that's built into recent versions of ffmpeg
audio_cmd.extend(['-strict', '-2'])
else:
audio_cmd.extend(['-c:a', 'copy'])
if nzbtomedia.ACHANNELS:
audio_cmd.extend(['-ac', str(nzbtomedia.ACHANNELS)])
if nzbtomedia.ABITRATE:
audio_cmd.extend(['-b:a', str(nzbtomedia.ABITRATE)])
if nzbtomedia.OUTPUTQUALITYPERCENT:
audio_cmd.extend(['-q:a', str(nzbtomedia.OUTPUTQUALITYPERCENT)])
if core.ACHANNELS:
audio_cmd.extend(['-ac', str(core.ACHANNELS)])
if core.ABITRATE:
audio_cmd.extend(['-b:a', str(core.ABITRATE)])
if core.OUTPUTQUALITYPERCENT:
audio_cmd.extend(['-q:a', str(core.OUTPUTQUALITYPERCENT)])
if nzbtomedia.SCODEC and nzbtomedia.ALLOWSUBS:
sub_cmd.extend(['-c:s', nzbtomedia.SCODEC])
elif nzbtomedia.ALLOWSUBS: # Not every subtitle codec can be used for every video container format!
if core.SCODEC and core.ALLOWSUBS:
sub_cmd.extend(['-c:s', core.SCODEC])
elif core.ALLOWSUBS: # Not every subtitle codec can be used for every video container format!
sub_cmd.extend(['-c:s', 'copy'])
else: # http://en.wikibooks.org/wiki/FFMPEG_An_Intermediate_Guide/subtitle_options
sub_cmd.extend(['-sn']) # Don't copy the subtitles over
if nzbtomedia.OUTPUTFASTSTART:
if core.OUTPUTFASTSTART:
other_cmd.extend(['-movflags', '+faststart'])
else:
videoStreams = [item for item in video_details["streams"] if item["codec_type"] == "video"]
audioStreams = [item for item in video_details["streams"] if item["codec_type"] == "audio"]
subStreams = [item for item in video_details["streams"] if item["codec_type"] == "subtitle"]
if nzbtomedia.VEXTENSION not in ['.mkv', '.mpegts']:
if core.VEXTENSION not in ['.mkv', '.mpegts']:
subStreams = [item for item in video_details["streams"] if item["codec_type"] == "subtitle" and item["codec_name"] != "hdmv_pgs_subtitle" and item["codec_name"] != "pgssub"]
for video in videoStreams:
@ -204,16 +204,16 @@ def buildCommands(file, newDir, movieName, bitbucket):
try:
height = video["height"]
except: height = 0
scale = nzbtomedia.VRESOLUTION
scale = core.VRESOLUTION
try:
framerate = float(fr.split('/')[0])/float(fr.split('/')[1])
except: framerate = 0
if codec in nzbtomedia.VCODEC_ALLOW or not nzbtomedia.VCODEC:
if codec in core.VCODEC_ALLOW or not core.VCODEC:
video_cmd.extend(['-c:v', 'copy'])
else:
video_cmd.extend(['-c:v', nzbtomedia.VCODEC])
if nzbtomedia.VFRAMERATE and not (nzbtomedia.VFRAMERATE * 0.999 <= fr <= nzbtomedia.VFRAMERATE * 1.001):
video_cmd.extend(['-r', str(nzbtomedia.VFRAMERATE)])
video_cmd.extend(['-c:v', core.VCODEC])
if core.VFRAMERATE and not (core.VFRAMERATE * 0.999 <= fr <= core.VFRAMERATE * 1.001):
video_cmd.extend(['-r', str(core.VFRAMERATE)])
if scale:
w_scale = width/float(scale.split(':')[0])
h_scale = height/float(scale.split(':')[1])
@ -225,18 +225,18 @@ def buildCommands(file, newDir, movieName, bitbucket):
scale = str(int((width/h_scale)/2)*2) + ":" + scale.split(':')[1]
if h_scale > 1:
video_cmd.extend(['-vf', 'scale=' + scale])
if nzbtomedia.VBITRATE:
video_cmd.extend(['-b:v', str(nzbtomedia.VBITRATE)])
if nzbtomedia.VPRESET:
video_cmd.extend(['-preset', nzbtomedia.VPRESET])
if nzbtomedia.VCRF:
video_cmd.extend(['-crf', str(nzbtomedia.VCRF)])
if nzbtomedia.VLEVEL:
video_cmd.extend(['-level', str(nzbtomedia.VLEVEL)])
if core.VBITRATE:
video_cmd.extend(['-b:v', str(core.VBITRATE)])
if core.VPRESET:
video_cmd.extend(['-preset', core.VPRESET])
if core.VCRF:
video_cmd.extend(['-crf', str(core.VCRF)])
if core.VLEVEL:
video_cmd.extend(['-level', str(core.VLEVEL)])
no_copy = ['-vf', '-r', '-crf', '-level', '-preset', '-b:v']
if video_cmd[1] == 'copy' and any(i in video_cmd for i in no_copy):
video_cmd[1] = nzbtomedia.VCODEC
if nzbtomedia.VCODEC == 'copy': # force copy. therefore ignore all other video transcoding.
video_cmd[1] = core.VCODEC
if core.VCODEC == 'copy': # force copy. therefore ignore all other video transcoding.
video_cmd = ['-c:v', 'copy']
map_cmd.extend(['-map', '0:' + str(video["index"])])
break # Only one video needed
@ -245,12 +245,12 @@ def buildCommands(file, newDir, movieName, bitbucket):
a_mapped = []
if audioStreams:
try:
audio1 = [ item for item in audioStreams if item["tags"]["language"] == nzbtomedia.ALANGUAGE ]
audio1 = [ item for item in audioStreams if item["tags"]["language"] == core.ALANGUAGE ]
except: # no language tags. Assume only 1 language.
audio1 = audioStreams
audio2 = [ item for item in audio1 if item["codec_name"] in nzbtomedia.ACODEC_ALLOW ]
audio2 = [ item for item in audio1 if item["codec_name"] in core.ACODEC_ALLOW ]
try:
audio3 = [ item for item in audioStreams if item["tags"]["language"] != nzbtomedia.ALANGUAGE ]
audio3 = [ item for item in audioStreams if item["tags"]["language"] != core.ALANGUAGE ]
except:
audio3 = []
@ -273,11 +273,11 @@ def buildCommands(file, newDir, movieName, bitbucket):
try:
channels = int(audio1[0]["channels"])
except: channels = 0
if nzbtomedia.ACODEC:
audio_cmd.extend(['-c:a:' + str(used_audio), nzbtomedia.ACODEC])
if core.ACODEC:
audio_cmd.extend(['-c:a:' + str(used_audio), core.ACODEC])
else:
audio_cmd.extend(['-c:a:' + str(used_audio), 'copy'])
if nzbtomedia.ACODEC == 'aac':
if core.ACODEC == 'aac':
audio_cmd.extend(['-strict', '-2'])
elif audio3: # just pick the default audio track
map_cmd.extend(['-map', '0:' + str(audio3[0]["index"])])
@ -288,29 +288,29 @@ def buildCommands(file, newDir, movieName, bitbucket):
try:
channels = int(audio3[0]["channels"])
except: channels = 0
if nzbtomedia.ACODEC:
audio_cmd.extend(['-c:a:' + str(used_audio), nzbtomedia.ACODEC])
if core.ACODEC:
audio_cmd.extend(['-c:a:' + str(used_audio), core.ACODEC])
else:
audio_cmd.extend(['-c:a:' + str(used_audio), 'copy'])
if nzbtomedia.ACODEC == 'aac':
if core.ACODEC == 'aac':
audio_cmd.extend(['-strict', '-2'])
if nzbtomedia.ACHANNELS and channels and channels > nzbtomedia.ACHANNELS:
audio_cmd.extend(['-ac:a:' + str(used_audio), str(nzbtomedia.ACHANNELS)])
if core.ACHANNELS and channels and channels > core.ACHANNELS:
audio_cmd.extend(['-ac:a:' + str(used_audio), str(core.ACHANNELS)])
if audio_cmd[1] == 'copy':
audio_cmd[1] = nzbtomedia.ACODEC
if nzbtomedia.ABITRATE and not (nzbtomedia.ABITRATE * 0.9 < bitrate < nzbtomedia.ABITRATE * 1.1):
audio_cmd.extend(['-b:a:' + str(used_audio), str(nzbtomedia.ABITRATE)])
audio_cmd[1] = core.ACODEC
if core.ABITRATE and not (core.ABITRATE * 0.9 < bitrate < core.ABITRATE * 1.1):
audio_cmd.extend(['-b:a:' + str(used_audio), str(core.ABITRATE)])
if audio_cmd[1] == 'copy':
audio_cmd[1] = nzbtomedia.ACODEC
if nzbtomedia.OUTPUTQUALITYPERCENT:
audio_cmd.extend(['-q:a:' + str(used_audio), str(nzbtomedia.OUTPUTQUALITYPERCENT)])
audio_cmd[1] = core.ACODEC
if core.OUTPUTQUALITYPERCENT:
audio_cmd.extend(['-q:a:' + str(used_audio), str(core.OUTPUTQUALITYPERCENT)])
if audio_cmd[1] == 'copy':
audio_cmd[1] = nzbtomedia.ACODEC
audio_cmd[1] = core.ACODEC
if nzbtomedia.ACODEC2_ALLOW:
if core.ACODEC2_ALLOW:
used_audio += 1
audio4 = [ item for item in audio1 if item["codec_name"] in nzbtomedia.ACODEC2_ALLOW ]
audio4 = [ item for item in audio1 if item["codec_name"] in core.ACODEC2_ALLOW ]
if audio4: # right language and codec.
map_cmd.extend(['-map', '0:' + str(audio4[0]["index"])])
a_mapped.extend([audio4[0]["index"]])
@ -330,11 +330,11 @@ def buildCommands(file, newDir, movieName, bitbucket):
try:
channels = int(audio1[0]["channels"])
except: channels = 0
if nzbtomedia.ACODEC2:
audio_cmd2.extend(['-c:a:' + str(used_audio), nzbtomedia.ACODEC2])
if core.ACODEC2:
audio_cmd2.extend(['-c:a:' + str(used_audio), core.ACODEC2])
else:
audio_cmd2.extend(['-c:a:' + str(used_audio), 'copy'])
if nzbtomedia.ACODEC2 == 'aac':
if core.ACODEC2 == 'aac':
audio_cmd2.extend(['-strict', '-2'])
elif audio3: # just pick the default audio track
map_cmd.extend(['-map', '0:' + str(audio3[0]["index"])])
@ -345,28 +345,28 @@ def buildCommands(file, newDir, movieName, bitbucket):
try:
channels = int(audio3[0]["channels"])
except: channels = 0
if nzbtomedia.ACODEC2:
audio_cmd2.extend(['-c:a:' + str(used_audio), nzbtomedia.ACODEC2])
if core.ACODEC2:
audio_cmd2.extend(['-c:a:' + str(used_audio), core.ACODEC2])
else:
audio_cmd2.extend(['-c:a:' + str(used_audio), 'copy'])
if nzbtomedia.ACODEC2 == 'aac':
if core.ACODEC2 == 'aac':
audio_cmd2.extend(['-strict', '-2'])
if nzbtomedia.ACHANNELS2 and channels and channels > nzbtomedia.ACHANNELS2:
audio_cmd2.extend(['-ac:a:' + str(used_audio), str(nzbtomedia.ACHANNELS2)])
if core.ACHANNELS2 and channels and channels > core.ACHANNELS2:
audio_cmd2.extend(['-ac:a:' + str(used_audio), str(core.ACHANNELS2)])
if audio_cmd2[1] == 'copy':
audio_cmd2[1] = nzbtomedia.ACODEC2
if nzbtomedia.ABITRATE2 and not (nzbtomedia.ABITRATE2 * 0.9 < bitrate < nzbtomedia.ABITRATE2 * 1.1):
audio_cmd2.extend(['-b:a:' + str(used_audio), str(nzbtomedia.ABITRATE2)])
audio_cmd2[1] = core.ACODEC2
if core.ABITRATE2 and not (core.ABITRATE2 * 0.9 < bitrate < core.ABITRATE2 * 1.1):
audio_cmd2.extend(['-b:a:' + str(used_audio), str(core.ABITRATE2)])
if audio_cmd2[1] == 'copy':
audio_cmd2[1] = nzbtomedia.ACODEC2
if nzbtomedia.OUTPUTQUALITYPERCENT:
audio_cmd2.extend(['-q:a:' + str(used_audio), str(nzbtomedia.OUTPUTQUALITYPERCENT)])
audio_cmd2[1] = core.ACODEC2
if core.OUTPUTQUALITYPERCENT:
audio_cmd2.extend(['-q:a:' + str(used_audio), str(core.OUTPUTQUALITYPERCENT)])
if audio_cmd2[1] == 'copy':
audio_cmd2[1] = nzbtomedia.ACODEC2
audio_cmd2[1] = core.ACODEC2
audio_cmd.extend(audio_cmd2)
if nzbtomedia.AINCLUDE and audio3 and nzbtomedia.ACODEC3:
if core.AINCLUDE and audio3 and core.ACODEC3:
for audio in audioStreams:
if audio["index"] in a_mapped:
continue
@ -379,45 +379,45 @@ def buildCommands(file, newDir, movieName, bitbucket):
try:
channels = int(audio["channels"])
except: channels = 0
if audio["codec_name"] in nzbtomedia.ACODEC3_ALLOW:
if audio["codec_name"] in core.ACODEC3_ALLOW:
audio_cmd3.extend(['-c:a:' + str(used_audio), 'copy'])
else:
if nzbtomedia.ACODEC3:
audio_cmd3.extend(['-c:a:' + str(used_audio), nzbtomedia.ACODEC3])
if core.ACODEC3:
audio_cmd3.extend(['-c:a:' + str(used_audio), core.ACODEC3])
else:
audio_cmd3.extend(['-c:a:' + str(used_audio), 'copy'])
if nzbtomedia.ACODEC3 == 'aac':
if core.ACODEC3 == 'aac':
audio_cmd3.extend(['-strict', '-2'])
if nzbtomedia.ACHANNELS3 and channels and channels > nzbtomedia.ACHANNELS3:
audio_cmd3.extend(['-ac:a:' + str(used_audio), str(nzbtomedia.ACHANNELS3)])
if core.ACHANNELS3 and channels and channels > core.ACHANNELS3:
audio_cmd3.extend(['-ac:a:' + str(used_audio), str(core.ACHANNELS3)])
if audio_cmd3[1] == 'copy':
audio_cmd3[1] = nzbtomedia.ACODEC3
if nzbtomedia.ABITRATE3 and not (nzbtomedia.ABITRATE3 * 0.9 < bitrate < nzbtomedia.ABITRATE3 * 1.1):
audio_cmd3.extend(['-b:a:' + str(used_audio), str(nzbtomedia.ABITRATE3)])
audio_cmd3[1] = core.ACODEC3
if core.ABITRATE3 and not (core.ABITRATE3 * 0.9 < bitrate < core.ABITRATE3 * 1.1):
audio_cmd3.extend(['-b:a:' + str(used_audio), str(core.ABITRATE3)])
if audio_cmd3[1] == 'copy':
audio_cmd3[1] = nzbtomedia.ACODEC3
if nzbtomedia.OUTPUTQUALITYPERCENT > 0:
audio_cmd3.extend(['-q:a:' + str(used_audio), str(nzbtomedia.OUTPUTQUALITYPERCENT)])
audio_cmd3[1] = core.ACODEC3
if core.OUTPUTQUALITYPERCENT > 0:
audio_cmd3.extend(['-q:a:' + str(used_audio), str(core.OUTPUTQUALITYPERCENT)])
if audio_cmd3[1] == 'copy':
audio_cmd3[1] = nzbtomedia.ACODEC3
audio_cmd3[1] = core.ACODEC3
audio_cmd.extend(audio_cmd3)
s_mapped = []
subs1 = []
burnt = 0
n = 0
for lan in nzbtomedia.SLANGUAGES:
for lan in core.SLANGUAGES:
try:
subs1 = [ item for item in subStreams if item["tags"]["language"] == lan ]
except: subs1 = []
if nzbtomedia.BURN and not subs1 and not burnt and os.path.isfile(file):
if core.BURN and not subs1 and not burnt and os.path.isfile(file):
for subfile in get_subs(file):
if lan in os.path.split(subfile)[1]:
video_cmd.extend(['-vf', 'subtitles=' + subfile])
burnt = 1
for sub in subs1:
if nzbtomedia.BURN and not burnt and os.path.isfile(inputFile):
if core.BURN and not burnt and os.path.isfile(inputFile):
subloc = 0
for index in range(len(subStreams)):
if subStreams[index]["index"] == sub["index"]:
@ -425,33 +425,33 @@ def buildCommands(file, newDir, movieName, bitbucket):
break
video_cmd.extend(['-vf', 'subtitles=' + inputFile + ":si=" + subloc])
burnt = 1
if not nzbtomedia.ALLOWSUBS:
if not core.ALLOWSUBS:
break
map_cmd.extend(['-map', '0:' + str(sub["index"])])
s_mapped.extend([sub["index"]])
if nzbtomedia.SINCLUDE:
if core.SINCLUDE:
for sub in subStreams:
if not nzbtomedia.ALLOWSUBS:
if not core.ALLOWSUBS:
break
if sub["index"] in s_mapped:
continue
map_cmd.extend(['-map', '0:' + str(sub["index"])])
s_mapped.extend([sub["index"]])
if nzbtomedia.OUTPUTFASTSTART:
if core.OUTPUTFASTSTART:
other_cmd.extend(['-movflags', '+faststart'])
command = [nzbtomedia.FFMPEG, '-loglevel', 'warning']
command = [core.FFMPEG, '-loglevel', 'warning']
if nzbtomedia.HWACCEL:
if core.HWACCEL:
command.extend(['-hwaccel', 'auto'])
if nzbtomedia.GENERALOPTS:
command.extend(nzbtomedia.GENERALOPTS)
if core.GENERALOPTS:
command.extend(core.GENERALOPTS)
command.extend([ '-i', inputFile])
if nzbtomedia.SEMBED and os.path.isfile(file):
if core.SEMBED and os.path.isfile(file):
for subfile in get_subs(file):
sub_details, result = getVideoDetails(subfile)
if not sub_details or not sub_details.get("streams"):
@ -462,11 +462,11 @@ def buildCommands(file, newDir, movieName, bitbucket):
n += 1
map_cmd.extend(['-map', str(n) + ':0'])
if not nzbtomedia.ALLOWSUBS or (not s_mapped and not n):
if not core.ALLOWSUBS or (not s_mapped and not n):
sub_cmd.extend(['-sn'])
else:
if nzbtomedia.SCODEC:
sub_cmd.extend(['-c:s', nzbtomedia.SCODEC])
if core.SCODEC:
sub_cmd.extend(['-c:s', core.SCODEC])
else:
sub_cmd.extend(['-c:s', 'copy'])
@ -478,7 +478,7 @@ def buildCommands(file, newDir, movieName, bitbucket):
command.extend(other_cmd)
command.append(newfilePath)
if platform.system() != 'Windows':
command = nzbtomedia.NICENESS + command
command = core.NICENESS + command
return command
def get_subs(file):
@ -497,14 +497,14 @@ def extract_subs(file, newfilePath, bitbucket):
if not video_details:
return
if nzbtomedia.SUBSDIR:
subdir = nzbtomedia.SUBSDIR
if core.SUBSDIR:
subdir = core.SUBSDIR
else:
subdir = os.path.split(newfilePath)[0]
name = os.path.splitext(os.path.split(newfilePath)[1])[0]
try:
subStreams = [item for item in video_details["streams"] if item["codec_type"] == "subtitle" and item["tags"]["language"] in nzbtomedia.SLANGUAGES and item["codec_name"] != "hdmv_pgs_subtitle" and item["codec_name"] != "pgssub"]
subStreams = [item for item in video_details["streams"] if item["codec_type"] == "subtitle" and item["tags"]["language"] in core.SLANGUAGES and item["codec_name"] != "hdmv_pgs_subtitle" and item["codec_name"] != "pgssub"]
except:
subStreams = [item for item in video_details["streams"] if item["codec_type"] == "subtitle" and item["codec_name"] != "hdmv_pgs_subtitle" and item["codec_name"] != "pgssub"]
num = len(subStreams)
@ -525,9 +525,9 @@ def extract_subs(file, newfilePath, bitbucket):
if os.path.isfile(outputFile):
outputFile = os.path.join(subdir, "%s.%s.%s.srt" %(name, lan, n))
command = [nzbtomedia.FFMPEG, '-loglevel', 'warning', '-i', file, '-vn', '-an', '-codec:' + str(idx), 'srt', outputFile]
command = [core.FFMPEG, '-loglevel', 'warning', '-i', file, '-vn', '-an', '-codec:' + str(idx), 'srt', outputFile]
if platform.system() != 'Windows':
command = nzbtomedia.NICENESS + command
command = core.NICENESS + command
logger.info("Extracting %s subtitle from: %s" % (lan, file))
print_cmd(command)
@ -557,11 +557,11 @@ def processList(List, newDir, bitbucket):
for item in List:
newfile = None
ext = os.path.splitext(item)[1].lower()
if ext in ['.iso', '.bin'] and not ext in nzbtomedia.IGNOREEXTENSIONS:
if ext in ['.iso', '.bin'] and not ext in core.IGNOREEXTENSIONS:
logger.debug("Attempting to rip disk image: %s" % (item), "TRANSCODER")
newList.extend(ripISO(item, newDir, bitbucket))
remList.append(item)
elif re.match(".+VTS_[0-9][0-9]_[0-9].[Vv][Oo][Bb]", item) and not '.vob' in nzbtomedia.IGNOREEXTENSIONS:
elif re.match(".+VTS_[0-9][0-9]_[0-9].[Vv][Oo][Bb]", item) and not '.vob' in core.IGNOREEXTENSIONS:
logger.debug("Found VIDEO_TS image file: %s" % (item), "TRANSCODER")
if not vtsPath:
try:
@ -571,7 +571,7 @@ def processList(List, newDir, bitbucket):
remList.append(item)
elif re.match(".+VIDEO_TS.", item) or re.match(".+VTS_[0-9][0-9]_[0-9].", item):
remList.append(item)
elif nzbtomedia.CONCAT and re.match(".+[cC][dD][0-9].", item):
elif core.CONCAT and re.match(".+[cC][dD][0-9].", item):
remList.append(item)
combine.append(item)
else: continue
@ -598,11 +598,11 @@ def ripISO(item, newDir, bitbucket):
newFiles = []
failure_dir = 'failure'
# Mount the ISO in your OS and call combineVTS.
if not nzbtomedia.SEVENZIP:
if not core.SEVENZIP:
logger.error("No 7zip installed. Can't extract image file %s" % (item), "TRANSCODER")
newFiles = [failure_dir]
return newFiles
cmd = [nzbtomedia.SEVENZIP, 'l', item]
cmd = [core.SEVENZIP, 'l', item]
try:
logger.debug("Attempting to extract .vob from image file %s" % (item), "TRANSCODER")
print_cmd(cmd)
@ -623,12 +623,12 @@ def ripISO(item, newDir, bitbucket):
break
if not concat:
break
if nzbtomedia.CONCAT:
if core.CONCAT:
combined.extend(concat)
continue
name = '%s.cd%s' % (os.path.splitext(os.path.split(item)[1])[0] ,str(n+1))
newFiles.append({item: {'name': name , 'files': concat}})
if nzbtomedia.CONCAT:
if core.CONCAT:
name = os.path.splitext(os.path.split(item)[1])[0]
newFiles.append({item: {'name': name , 'files': combined}})
if not newFiles:
@ -654,11 +654,11 @@ def combineVTS(vtsPath):
break
if not concat:
break
if nzbtomedia.CONCAT:
if core.CONCAT:
combined = combined + concat + '|'
continue
newFiles.append('concat:%s' % concat[:-1])
if nzbtomedia.CONCAT:
if core.CONCAT:
newFiles.append('concat:%s' % combined[:-1])
return newFiles
@ -683,12 +683,12 @@ def print_cmd(command):
logger.debug("calling command:%s" % (cmd))
def Transcode_directory(dirName):
if not nzbtomedia.FFMPEG:
if not core.FFMPEG:
return 1, dirName
logger.info("Checking for files to be transcoded")
final_result = 0 # initialize as successful
if nzbtomedia.OUTPUTVIDEOPATH:
newDir = nzbtomedia.OUTPUTVIDEOPATH
if core.OUTPUTVIDEOPATH:
newDir = core.OUTPUTVIDEOPATH
makeDir(newDir)
else:
newDir = dirName
@ -697,20 +697,20 @@ def Transcode_directory(dirName):
else:
bitbucket = open('/dev/null')
movieName = os.path.splitext(os.path.split(dirName)[1])[0]
List = nzbtomedia.listMediaFiles(dirName, media=True, audio=False, meta=False, archives=False)
List = core.listMediaFiles(dirName, media=True, audio=False, meta=False, archives=False)
List, remList, newList, success = processList(List, newDir, bitbucket)
if not success:
bitbucket.close()
return 1, dirName
for file in List:
if isinstance(file, str) and os.path.splitext(file)[1] in nzbtomedia.IGNOREEXTENSIONS:
if isinstance(file, str) 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 nzbtomedia.SEXTRACT and isinstance(file, str):
if core.SEXTRACT and isinstance(file, str):
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)
@ -740,12 +740,12 @@ def Transcode_directory(dirName):
except:
logger.error("Transcoding of video %s has failed" % (newfilePath))
if nzbtomedia.SUBSDIR and result == 0 and isinstance(file, str):
if core.SUBSDIR and result == 0 and isinstance(file, str):
for sub in get_subs(file):
name = os.path.splitext(os.path.split(file)[1])[0]
subname = os.path.split(sub)[1]
newname = os.path.splitext(os.path.split(newfilePath)[1])[0]
newpath = os.path.join(nzbtomedia.SUBSDIR, subname.replace(name, newname))
newpath = os.path.join(core.SUBSDIR, subname.replace(name, newname))
if not os.path.isfile(newpath):
os.rename(sub, newpath)
@ -754,7 +754,7 @@ def Transcode_directory(dirName):
shutil.copymode(file, newfilePath)
except: pass
logger.info("Transcoding of video to %s succeeded" % (newfilePath))
if os.path.isfile(newfilePath) and (file in newList or not nzbtomedia.DUPLICATE):
if os.path.isfile(newfilePath) and (file in newList or not core.DUPLICATE):
try:
os.unlink(file)
except: pass
@ -762,7 +762,7 @@ def Transcode_directory(dirName):
logger.error("Transcoding of video to %s failed with result %s" % (newfilePath, str(result)))
# this will be 0 (successful) it all are successful, else will return a positive integer for failure.
final_result = final_result + result
if final_result == 0 and not nzbtomedia.DUPLICATE:
if final_result == 0 and not core.DUPLICATE:
for file in remList:
try:
os.unlink(file)
@ -770,7 +770,7 @@ def Transcode_directory(dirName):
if not os.listdir(newDir): #this is an empty directory and we didn't transcode into it.
os.rmdir(newDir)
newDir = dirName
if not nzbtomedia.PROCESSOUTPUT and nzbtomedia.DUPLICATE: # We postprocess the original files to CP/SB
if not core.PROCESSOUTPUT and core.DUPLICATE: # We postprocess the original files to CP/SB
newDir = dirName
bitbucket.close()
return final_result, newDir

View file

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
from core.transmissionrpc.constants import DEFAULT_PORT, DEFAULT_TIMEOUT, PRIORITY, RATIO_LIMIT, LOGGER
from core.transmissionrpc.error import TransmissionError, HTTPHandlerError
from core.transmissionrpc.httphandler import HTTPHandler, DefaultHTTPHandler
from core.transmissionrpc.torrent import Torrent
from core.transmissionrpc.session import Session
from core.transmissionrpc.client import Client
from core.transmissionrpc.utils import add_stdout_logger, add_file_logger
__author__ = 'Erik Svensson <erik.public@gmail.com>'
__version_major__ = 0
__version_minor__ = 11
__version__ = '{0}.{1}'.format(__version_major__, __version_minor__)
__copyright__ = 'Copyright (c) 2008-2013 Erik Svensson'
__license__ = 'MIT'

View file

@ -10,12 +10,12 @@ import os
import base64
import json
from nzbtomedia.transmissionrpc.constants import DEFAULT_PORT, DEFAULT_TIMEOUT
from nzbtomedia.transmissionrpc.error import TransmissionError, HTTPHandlerError
from nzbtomedia.transmissionrpc.utils import LOGGER, get_arguments, make_rpc_name, argument_value_convert, rpc_bool
from nzbtomedia.transmissionrpc.httphandler import DefaultHTTPHandler
from nzbtomedia.transmissionrpc.torrent import Torrent
from nzbtomedia.transmissionrpc.session import Session
from core.transmissionrpc.constants import DEFAULT_PORT, DEFAULT_TIMEOUT
from core.transmissionrpc.error import TransmissionError, HTTPHandlerError
from core.transmissionrpc.utils import LOGGER, get_arguments, make_rpc_name, argument_value_convert, rpc_bool
from core.transmissionrpc.httphandler import DefaultHTTPHandler
from core.transmissionrpc.torrent import Torrent
from core.transmissionrpc.session import Session
from six import PY3, integer_types, string_types, iteritems

View file

@ -4,7 +4,7 @@
import logging
from nzbtomedia.transmissionrpc.six import iteritems
from core.transmissionrpc.six import iteritems
LOGGER = logging.getLogger('transmissionrpc')

View file

@ -2,7 +2,7 @@
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
from nzbtomedia.transmissionrpc.six import string_types, integer_types
from core.transmissionrpc.six import string_types, integer_types
class TransmissionError(Exception):
"""

View file

@ -4,7 +4,7 @@
import sys
from nzbtomedia.transmissionrpc.error import HTTPHandlerError
from core.transmissionrpc.error import HTTPHandlerError
from six import PY3
if PY3:

View file

@ -2,9 +2,9 @@
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
from nzbtomedia.transmissionrpc.utils import Field
from core.transmissionrpc.utils import Field
from nzbtomedia.transmissionrpc.six import iteritems, integer_types
from core.transmissionrpc.six import iteritems, integer_types
class Session(object):
"""

View file

@ -5,8 +5,8 @@
import sys
import datetime
from nzbtomedia.transmissionrpc.constants import PRIORITY, RATIO_LIMIT, IDLE_LIMIT
from nzbtomedia.transmissionrpc.utils import Field, format_timedelta
from core.transmissionrpc.constants import PRIORITY, RATIO_LIMIT, IDLE_LIMIT
from core.transmissionrpc.utils import Field, format_timedelta
from six import integer_types, string_types, text_type, iteritems

View file

@ -10,7 +10,7 @@ try:
except ImportError:
import simplejson as json
from nzbtomedia.utorrent.upload import MultiPartForm
from core.utorrent.upload import MultiPartForm
class UTorrentClient(object):

View file

@ -12,8 +12,8 @@ import stat
import traceback
import gh_api as github
import nzbtomedia
from nzbtomedia import logger
import core
from core import logger
class CheckVersion():
"""
@ -46,7 +46,7 @@ class CheckVersion():
"""
# check if we're a windows build
if os.path.isdir(os.path.join(nzbtomedia.PROGRAM_DIR, u'.git')):
if os.path.isdir(os.path.join(core.PROGRAM_DIR, u'.git')):
install_type = 'git'
else:
install_type = 'source'
@ -62,13 +62,13 @@ class CheckVersion():
force: if true the VERSION_NOTIFY setting will be ignored and a check will be forced
"""
if not nzbtomedia.VERSION_NOTIFY and not force:
if not core.VERSION_NOTIFY and not force:
logger.log(u"Version checking is disabled, not checking for the newest version")
return False
logger.log(u"Checking if " + self.install_type + " needs an update")
if not self.updater.need_update():
nzbtomedia.NEWEST_VERSION_STRING = None
core.NEWEST_VERSION_STRING = None
logger.log(u"No update needed")
return False
@ -81,13 +81,13 @@ class CheckVersion():
class UpdateManager():
def get_github_repo_user(self):
return nzbtomedia.GIT_USER
return core.GIT_USER
def get_github_repo(self):
return nzbtomedia.GIT_REPO
return core.GIT_REPO
def get_github_branch(self):
return nzbtomedia.GIT_BRANCH
return core.GIT_BRANCH
class GitUpdateManager(UpdateManager):
def __init__(self):
@ -107,8 +107,8 @@ class GitUpdateManager(UpdateManager):
def _find_working_git(self):
test_cmd = 'version'
if nzbtomedia.GIT_PATH:
main_git = '"' + nzbtomedia.GIT_PATH + '"'
if core.GIT_PATH:
main_git = '"' + core.GIT_PATH + '"'
else:
main_git = 'git'
@ -163,15 +163,15 @@ class GitUpdateManager(UpdateManager):
cmd = git_path + ' ' + args
try:
logger.log(u"Executing " + cmd + " with your shell in " + nzbtomedia.PROGRAM_DIR, logger.DEBUG)
logger.log(u"Executing " + cmd + " with your shell in " + core.PROGRAM_DIR, logger.DEBUG)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
shell=True, cwd=nzbtomedia.PROGRAM_DIR)
shell=True, cwd=core.PROGRAM_DIR)
output, err = p.communicate()
exit_status = p.returncode
if output:
output = output.strip()
if nzbtomedia.LOG_GIT:
if core.LOG_GIT:
logger.log(u"git output: " + output, logger.DEBUG)
except OSError:
@ -183,17 +183,17 @@ class GitUpdateManager(UpdateManager):
exit_status = 0
elif exit_status == 1:
if nzbtomedia.LOG_GIT:
if core.LOG_GIT:
logger.log(cmd + u" returned : " + output, logger.DEBUG)
exit_status = 1
elif exit_status == 128 or 'fatal:' in output or err:
if nzbtomedia.LOG_GIT:
if core.LOG_GIT:
logger.log(cmd + u" returned : " + output, logger.DEBUG)
exit_status = 128
else:
if nzbtomedia.LOG_GIT:
if core.LOG_GIT:
logger.log(cmd + u" returned : " + output + u", treat as error for now", logger.DEBUG)
exit_status = 1
@ -217,20 +217,20 @@ class GitUpdateManager(UpdateManager):
return False
self._cur_commit_hash = cur_commit_hash
if self._cur_commit_hash:
nzbtomedia.NZBTOMEDIA_VERSION = self._cur_commit_hash
core.NZBTOMEDIA_VERSION = self._cur_commit_hash
return True
else:
return False
def _find_git_branch(self):
nzbtomedia.NZBTOMEDIA_BRANCH = self.get_github_branch()
core.NZBTOMEDIA_BRANCH = self.get_github_branch()
branch_info, err, exit_status = self._run_git(self._git_path, 'symbolic-ref -q HEAD') # @UnusedVariable
if exit_status == 0 and branch_info:
branch = branch_info.strip().replace('refs/heads/', '', 1)
if branch:
nzbtomedia.NZBTOMEDIA_BRANCH = branch
nzbtomedia.GIT_BRANCH = branch
return nzbtomedia.GIT_BRANCH
core.NZBTOMEDIA_BRANCH = branch
core.GIT_BRANCH = branch
return core.GIT_BRANCH
def _check_github_for_update(self):
"""
@ -340,7 +340,7 @@ class SourceUpdateManager(UpdateManager):
def _find_installed_version(self):
version_file = os.path.join(nzbtomedia.PROGRAM_DIR, u'version.txt')
version_file = os.path.join(core.PROGRAM_DIR, u'version.txt')
if not os.path.isfile(version_file):
self._cur_commit_hash = None
@ -355,7 +355,7 @@ class SourceUpdateManager(UpdateManager):
if not self._cur_commit_hash:
self._cur_commit_hash = None
else:
nzbtomedia.NZBTOMEDIA_VERSION = self._cur_commit_hash
core.NZBTOMEDIA_VERSION = self._cur_commit_hash
def need_update(self):
@ -416,7 +416,7 @@ class SourceUpdateManager(UpdateManager):
def set_newest_text(self):
# if we're up to date then don't set this
nzbtomedia.NEWEST_VERSION_STRING = None
core.NEWEST_VERSION_STRING = None
if not self._cur_commit_hash:
logger.log(u"Unknown current version number, don't know if we should update or not", logger.ERROR)
@ -436,11 +436,11 @@ class SourceUpdateManager(UpdateManager):
"""
base_url = 'https://github.com/' + self.github_repo_user + '/' + self.github_repo
tar_download_url = base_url + '/tarball/' + self.branch
version_path = os.path.join(nzbtomedia.PROGRAM_DIR, u'version.txt')
version_path = os.path.join(core.PROGRAM_DIR, u'version.txt')
try:
# prepare the update dir
sb_update_dir = os.path.join(nzbtomedia.PROGRAM_DIR, u'sb-update')
sb_update_dir = os.path.join(core.PROGRAM_DIR, u'sb-update')
if os.path.isdir(sb_update_dir):
logger.log(u"Clearing out update folder " + sb_update_dir + " before extracting")
@ -481,12 +481,12 @@ class SourceUpdateManager(UpdateManager):
content_dir = os.path.join(sb_update_dir, update_dir_contents[0])
# walk temp folder and move files to main folder
logger.log(u"Moving files from " + content_dir + " to " + nzbtomedia.PROGRAM_DIR)
logger.log(u"Moving files from " + content_dir + " to " + core.PROGRAM_DIR)
for dirname, dirnames, filenames in os.walk(content_dir): # @UnusedVariable
dirname = dirname[len(content_dir) + 1:]
for curfile in filenames:
old_path = os.path.join(content_dir, dirname, curfile)
new_path = os.path.join(nzbtomedia.PROGRAM_DIR, dirname, curfile)
new_path = os.path.join(core.PROGRAM_DIR, dirname, curfile)
#Avoid DLL access problem on WIN32/64
#These files needing to be updated manually

View file

@ -500,19 +500,19 @@
import os
import sys
import datetime
import nzbtomedia
from nzbtomedia.autoProcess.autoProcessComics import autoProcessComics
from nzbtomedia.autoProcess.autoProcessGames import autoProcessGames
from nzbtomedia.autoProcess.autoProcessMovie import autoProcessMovie
from nzbtomedia.autoProcess.autoProcessMusic import autoProcessMusic
from nzbtomedia.autoProcess.autoProcessTV import autoProcessTV
from nzbtomedia.nzbToMediaUtil import getDirs, extractFiles, cleanDir, update_downloadInfoStatus, get_downloadInfo, CharReplace, convert_to_ascii, get_nzoid
from nzbtomedia.nzbToMediaUserScript import external_script
from nzbtomedia import logger, nzbToMediaDB
import core
from core.autoProcess.autoProcessComics import autoProcessComics
from core.autoProcess.autoProcessGames import autoProcessGames
from core.autoProcess.autoProcessMovie import autoProcessMovie
from core.autoProcess.autoProcessMusic import autoProcessMusic
from core.autoProcess.autoProcessTV import autoProcessTV
from core.nzbToMediaUtil import getDirs, extractFiles, cleanDir, update_downloadInfoStatus, get_downloadInfo, CharReplace, convert_to_ascii, get_nzoid
from core.nzbToMediaUserScript import external_script
from core import logger, nzbToMediaDB
# post-processing
def process(inputDirectory, inputName=None, status=0, clientAgent='manual', download_id=None, inputCategory=None, failureLink=None):
if nzbtomedia.SAFE_MODE and inputDirectory == nzbtomedia.NZB_DEFAULTDIR:
if core.SAFE_MODE and inputDirectory == core.NZB_DEFAULTDIR:
logger.error(
'The input directory:[%s] is the Default Download Directory. Please configure category directories to prevent processing of other media.' % (
inputDirectory))
@ -521,7 +521,7 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down
if not download_id and clientAgent == 'sabnzbd':
download_id = get_nzoid(inputName)
if clientAgent != 'manual' and not nzbtomedia.DOWNLOADINFO:
if clientAgent != 'manual' and not core.DOWNLOADINFO:
logger.debug('Adding NZB download info for directory %s to database' % (inputDirectory))
myDB = nzbToMediaDB.DBConnection()
@ -543,9 +543,9 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down
if inputCategory is None:
inputCategory = 'UNCAT'
usercat = inputCategory
section = nzbtomedia.CFG.findsection(inputCategory).isenabled()
section = core.CFG.findsection(inputCategory).isenabled()
if section is None:
section = nzbtomedia.CFG.findsection("ALL").isenabled()
section = core.CFG.findsection("ALL").isenabled()
if section is None:
logger.error(
'Category:[%s] is not defined or is not enabled. Please rename it or ensure it is enabled for the appropriate section in your autoProcessMedia.cfg and try again.' % (
@ -574,7 +574,7 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down
extract = 0
try:
if int(section[usercat]['remote_path']) and not nzbtomedia.REMOTEPATHS:
if int(section[usercat]['remote_path']) and not core.REMOTEPATHS:
logger.error('Remote Path is enabled for %s:%s but no Network mount points are defined. Please check your autoProcessMedia.cfg, exiting!' % (
sectionName, inputCategory))
return [-1, ""]
@ -621,10 +621,10 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down
def main(args, section=None):
# Initialize the config
nzbtomedia.initialize(section)
core.initialize(section)
# clientAgent for NZBs
clientAgent = nzbtomedia.NZB_CLIENTAGENT
clientAgent = core.NZB_CLIENTAGENT
logger.info("#########################################################")
logger.info("## ..::[%s]::.. ##" % os.path.basename(__file__))
@ -642,7 +642,7 @@ def main(args, section=None):
# Check if the script is called from nzbget 11.0 or later
if os.environ['NZBOP_VERSION'][0:5] < '11.0':
logger.error("NZBGet Version %s is not supported. Please update NZBGet." %(str(os.environ['NZBOP_VERSION'])))
sys.exit(nzbtomedia.NZBGET_POSTPROCESS_ERROR)
sys.exit(core.NZBGET_POSTPROCESS_ERROR)
logger.info("Script triggered from NZBGet Version %s." %(str(os.environ['NZBOP_VERSION'])))
@ -695,7 +695,7 @@ def main(args, section=None):
clientAgent=clientAgent, download_id=download_id, inputCategory=os.environ['NZBPP_CATEGORY'],
failureLink=failureLink)
# SABnzbd Pre 0.7.17
elif len(args) == nzbtomedia.SABNZB_NO_OF_ARGUMENTS:
elif len(args) == core.SABNZB_NO_OF_ARGUMENTS:
# SABnzbd argv:
# 1 The final directory of the job (full path)
# 2 The original name of the NZB file
@ -709,7 +709,7 @@ def main(args, section=None):
result = process(args[1], inputName=args[2], status=args[7], inputCategory=args[5], clientAgent=clientAgent,
download_id='')
# SABnzbd 0.7.17+
elif len(args) >= nzbtomedia.SABNZB_0717_NO_OF_ARGUMENTS:
elif len(args) >= core.SABNZB_0717_NO_OF_ARGUMENTS:
# SABnzbd argv:
# 1 The final directory of the job (full path)
# 2 The original name of the NZB file
@ -727,16 +727,16 @@ def main(args, section=None):
# Perform Manual Post-Processing
logger.warning("Invalid number of arguments received from client, Switching to manual run mode ...")
for section, subsections in nzbtomedia.SECTIONS.items():
for section, subsections in core.SECTIONS.items():
for subsection in subsections:
if not nzbtomedia.CFG[section][subsection].isenabled():
if not core.CFG[section][subsection].isenabled():
continue
for dirName in getDirs(section, subsection, link = 'move'):
logger.info("Starting manual run for %s:%s - Folder:%s" % (section, subsection, dirName))
logger.info("Checking database for download info for %s ..." % (os.path.basename(dirName)))
nzbtomedia.DOWNLOADINFO = get_downloadInfo(os.path.basename(dirName), 0)
if nzbtomedia.DOWNLOADINFO:
core.DOWNLOADINFO = get_downloadInfo(os.path.basename(dirName), 0)
if core.DOWNLOADINFO:
logger.info(
"Found download info for %s, setting variables now ..." % (os.path.basename(dirName)))
else:
@ -746,23 +746,23 @@ def main(args, section=None):
)
try:
clientAgent = str(nzbtomedia.DOWNLOADINFO[0]['client_agent'])
clientAgent = str(core.DOWNLOADINFO[0]['client_agent'])
except:
clientAgent = 'manual'
try:
download_id = str(nzbtomedia.DOWNLOADINFO[0]['input_id'])
download_id = str(core.DOWNLOADINFO[0]['input_id'])
except:
download_id = None
if clientAgent.lower() not in nzbtomedia.NZB_CLIENTS and clientAgent != 'manual':
if clientAgent.lower() not in core.NZB_CLIENTS and clientAgent != 'manual':
continue
try:
dirName = dirName.encode(nzbtomedia.SYS_ENCODING)
dirName = dirName.encode(core.SYS_ENCODING)
except: pass
inputName = os.path.basename(dirName)
try:
inputName = inputName.encode(nzbtomedia.SYS_ENCODING)
inputName = inputName.encode(core.SYS_ENCODING)
except: pass
results = process(dirName, inputName, 0, clientAgent=clientAgent,
@ -777,16 +777,16 @@ def main(args, section=None):
if result[1]:
print result[1] + "!" # For SABnzbd Status display.
if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11
del nzbtomedia.MYAPP
return (nzbtomedia.NZBGET_POSTPROCESS_SUCCESS)
del core.MYAPP
return (core.NZBGET_POSTPROCESS_SUCCESS)
else:
logger.error("A problem was reported in the %s script." % args[0])
if result[1]:
print result[1] + "!" # For SABnzbd Status display.
if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11
del nzbtomedia.MYAPP
return (nzbtomedia.NZBGET_POSTPROCESS_ERROR)
del nzbtomedia.MYAPP
del core.MYAPP
return (core.NZBGET_POSTPROCESS_ERROR)
del core.MYAPP
return (result[0])

View file

@ -1,18 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
from nzbtomedia.transmissionrpc.constants import DEFAULT_PORT, DEFAULT_TIMEOUT, PRIORITY, RATIO_LIMIT, LOGGER
from nzbtomedia.transmissionrpc.error import TransmissionError, HTTPHandlerError
from nzbtomedia.transmissionrpc.httphandler import HTTPHandler, DefaultHTTPHandler
from nzbtomedia.transmissionrpc.torrent import Torrent
from nzbtomedia.transmissionrpc.session import Session
from nzbtomedia.transmissionrpc.client import Client
from nzbtomedia.transmissionrpc.utils import add_stdout_logger, add_file_logger
__author__ = 'Erik Svensson <erik.public@gmail.com>'
__version_major__ = 0
__version_minor__ = 11
__version__ = '{0}.{1}'.format(__version_major__, __version_minor__)
__copyright__ = 'Copyright (c) 2008-2013 Erik Svensson'
__license__ = 'MIT'

View file

@ -3,26 +3,26 @@ import os
import sys
import datetime
import re
import nzbtomedia
from nzbtomedia.nzbToMediaAutoFork import autoFork
from nzbtomedia import nzbToMediaDB
from nzbtomedia.transcoder import transcoder
from nzbtomedia.nzbToMediaUtil import get_downloadInfo, server_responding
import core
from core.nzbToMediaAutoFork import autoFork
from core import nzbToMediaDB
from core.transcoder import transcoder
from core.nzbToMediaUtil import get_downloadInfo, server_responding
# Initialize the config
nzbtomedia.initialize()
core.initialize()
#label = nzbtomedia.TORRENT_CLASS.core.get_torrent_status("f33a9c4b15cbd9170722d700069af86746817ade", ["label"]).get()['label']
#label = core.TORRENT_CLASS.core.get_torrent_status("f33a9c4b15cbd9170722d700069af86746817ade", ["label"]).get()['label']
#print label
if transcoder.isVideoGood(nzbtomedia.TEST_FILE, 0):
if transcoder.isVideoGood(core.TEST_FILE, 0):
print "FFPROBE Works"
else:
print "FFPROBE FAILED"
test = nzbtomedia.CFG['SickBeard','NzbDrone']['tv'].isenabled()
test = core.CFG['SickBeard','NzbDrone']['tv'].isenabled()
print test
section = nzbtomedia.CFG.findsection('tv').isenabled()
section = core.CFG.findsection('tv').isenabled()
print section
print len(section)
fork, fork_params = autoFork('SickBeard', 'tv')
@ -44,4 +44,4 @@ print Language('eng')
import subliminal
subliminal.cache_region.configure('dogpile.cache.memory')
del nzbtomedia.MYAPP
del core.MYAPP