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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,7 +3,7 @@ import platform
import shutil import shutil
import stat import stat
from time import sleep from time import sleep
import nzbtomedia import core
from subprocess import call, Popen from subprocess import call, Popen
import subprocess import subprocess
@ -11,11 +11,11 @@ def extract(filePath, outputDestination):
success = 0 success = 0
# Using Windows # Using Windows
if platform.system() == 'Windows': if platform.system() == 'Windows':
if not os.path.exists(nzbtomedia.SEVENZIP): if not os.path.exists(core.SEVENZIP):
nzbtomedia.logger.error("EXTRACTOR: Could not find 7-zip, Exiting") core.logger.error("EXTRACTOR: Could not find 7-zip, Exiting")
return False return False
invislocation = os.path.join(nzbtomedia.PROGRAM_DIR, 'nzbtomedia', 'extractor', 'bin', 'invisible.cmd') invislocation = os.path.join(core.PROGRAM_DIR, 'core', 'extractor', 'bin', 'invisible.cmd')
cmd_7zip = [invislocation, nzbtomedia.SEVENZIP, "x", "-y"] cmd_7zip = [invislocation, core.SEVENZIP, "x", "-y"]
ext_7zip = [".rar", ".zip", ".tar.gz", "tgz", ".tar.bz2", ".tbz", ".tar.lzma", ".tlz", ".7z", ".xz"] ext_7zip = [".rar", ".zip", ".tar.gz", "tgz", ".tar.bz2", ".tbz", ".tar.lzma", ".tlz", ".7z", ".xz"]
EXTRACT_COMMANDS = dict.fromkeys(ext_7zip, cmd_7zip) EXTRACT_COMMANDS = dict.fromkeys(ext_7zip, cmd_7zip)
# Using unix # Using unix
@ -50,14 +50,14 @@ def extract(filePath, outputDestination):
else: else:
for k, v in EXTRACT_COMMANDS.items(): for k, v in EXTRACT_COMMANDS.items():
if cmd in v[0]: 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] del EXTRACT_COMMANDS[k]
devnull.close() devnull.close()
else: 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: 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) ext = os.path.splitext(filePath)
cmd = [] cmd = []
@ -73,19 +73,19 @@ def extract(filePath, outputDestination):
if ext[1] in EXTRACT_COMMANDS: if ext[1] in EXTRACT_COMMANDS:
cmd = EXTRACT_COMMANDS[ext[1]] cmd = EXTRACT_COMMANDS[ext[1]]
else: else:
nzbtomedia.logger.debug("EXTRACTOR: Unknown file type: %s" % ext[1]) core.logger.debug("EXTRACTOR: Unknown file type: %s" % ext[1])
return False return False
# Create outputDestination folder # Create outputDestination folder
nzbtomedia.makeDir(outputDestination) core.makeDir(outputDestination)
if nzbtomedia.PASSWORDSFILE != "" and os.path.isfile(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(nzbtomedia.PASSWORDSFILE))] passwords = [line.strip() for line in open(os.path.normpath(core.PASSWORDSFILE))]
else: else:
passwords = [] passwords = []
nzbtomedia.logger.info("Extracting %s to %s" % (filePath, outputDestination)) core.logger.info("Extracting %s to %s" % (filePath, outputDestination))
nzbtomedia.logger.debug("Extracting %s %s %s" % (cmd, filePath, outputDestination)) core.logger.debug("Extracting %s %s %s" % (cmd, filePath, outputDestination))
origFiles = [] origFiles = []
origDirs = [] origDirs = []
@ -106,16 +106,16 @@ def extract(filePath, outputDestination):
info = subprocess.STARTUPINFO() info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
else: else:
cmd = nzbtomedia.NICENESS + cmd cmd = core.NICENESS + cmd
cmd2 = cmd cmd2 = cmd
cmd2.append("-p-") # don't prompt for password. cmd2.append("-p-") # don't prompt for password.
p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine. p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine.
res = p.wait() 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. 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 success = 1
elif len(passwords) > 0: 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: for password in passwords:
if password == "": # if edited in windows or otherwise if blank lines. if password == "": # if edited in windows or otherwise if blank lines.
continue continue
@ -126,14 +126,14 @@ def extract(filePath, outputDestination):
p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine. p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine.
res = p.wait() res = p.wait()
if (res >= 0 and platform == 'Windows') or res == 0: 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)) filePath, outputDestination, password))
success = 1 success = 1
break break
else: else:
continue continue
except: 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) os.chdir(pwd)
return False return False
@ -156,5 +156,5 @@ def extract(filePath, outputDestination):
except: pass except: pass
return True return True
else: 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 return False

View file

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

View file

@ -1,42 +1,42 @@
import urllib import urllib
import nzbtomedia import core
import requests import requests
from nzbtomedia import logger from core import logger
def autoFork(section, inputCategory): def autoFork(section, inputCategory):
# auto-detect correct section # auto-detect correct section
# config settings # config settings
try: try:
host = nzbtomedia.CFG[section][inputCategory]["host"] host = core.CFG[section][inputCategory]["host"]
port = nzbtomedia.CFG[section][inputCategory]["port"] port = core.CFG[section][inputCategory]["port"]
except: except:
host = None host = None
port = None port = None
try: try:
username = nzbtomedia.CFG[section][inputCategory]["username"] username = core.CFG[section][inputCategory]["username"]
password = nzbtomedia.CFG[section][inputCategory]["password"] password = core.CFG[section][inputCategory]["password"]
except: except:
username = None username = None
password = None password = None
try: try:
apikey = nzbtomedia.CFG[section][inputCategory]["apikey"] apikey = core.CFG[section][inputCategory]["apikey"]
except: except:
apikey = None apikey = None
try: try:
ssl = int(nzbtomedia.CFG[section][inputCategory]["ssl"]) ssl = int(core.CFG[section][inputCategory]["ssl"])
except: except:
ssl = 0 ssl = 0
try: try:
web_root = nzbtomedia.CFG[section][inputCategory]["web_root"] web_root = core.CFG[section][inputCategory]["web_root"]
except: except:
web_root = "" web_root = ""
try: 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: except:
fork = "auto" fork = "auto"
@ -61,7 +61,7 @@ def autoFork(section, inputCategory):
fork = ['default', {}] fork = ['default', {}]
elif fork == "auto": elif fork == "auto":
params = nzbtomedia.ALL_FORKS params = core.ALL_FORKS
rem_params = [] rem_params = []
logger.info("Attempting to auto-detect %s fork" % inputCategory) 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. # 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) rem_params.append(param)
for param in rem_params: for param in rem_params:
params.pop(param) 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]: if params == fork[1]:
detected = True detected = True
break break
@ -97,7 +97,7 @@ def autoFork(section, inputCategory):
fork = ['custom', params] fork = ['custom', params]
else: else:
logger.info("%s:%s fork auto-detection failed" % (section, inputCategory)) 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])) logger.info("%s:%s fork set to %s" % (section, inputCategory, fork[0]))
return fork[0], fork[1] return fork[0], fork[1]

View file

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

View file

@ -4,8 +4,8 @@ import re
import sqlite3 import sqlite3
import time import time
import nzbtomedia import core
from nzbtomedia import logger from core import logger
def dbFilename(filename="nzbtomedia.db", suffix=None): def dbFilename(filename="nzbtomedia.db", suffix=None):
""" """
@ -17,7 +17,7 @@ def dbFilename(filename="nzbtomedia.db", suffix=None):
""" """
if suffix: if suffix:
filename = "%s.%s" % (filename, 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: class DBConnection:

View file

@ -1,9 +1,9 @@
import os import os
import re import re
import nzbtomedia import core
import shlex import shlex
from nzbtomedia import logger from core import logger
from nzbtomedia.nzbToMediaUtil import listMediaFiles 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]\.", 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\.", 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 newfilename = filename
if not newfilename: if not newfilename:
newfilename = exception(filename, parentDir, name) newfilename = exception(filename, parentDir, name)
if nzbtomedia.GROUPS: if core.GROUPS:
newfilename = strip_groups(newfilename) newfilename = strip_groups(newfilename)
if newfilename != filename: if newfilename != filename:
rename_file(filename, newfilename) rename_file(filename, newfilename)
def strip_groups(filename): def strip_groups(filename):
if not nzbtomedia.GROUPS: if not core.GROUPS:
return filename return filename
dirname, file = os.path.split(filename) dirname, file = os.path.split(filename)
head, fileExtension = os.path.splitext(file) head, fileExtension = os.path.splitext(file)
newname = head.replace(' ', '.') newname = head.replace(' ', '.')
for group in nzbtomedia.GROUPS: for group in core.GROUPS:
newname = newname.replace(group, '') newname = newname.replace(group, '')
newname = newname.replace('[]', '') newname = newname.replace('[]', '')
newfile = newname + fileExtension newfile = newname + fileExtension

View file

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

View file

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

View file

@ -19,5 +19,5 @@ __title__ = "synchronous-deluge"
__version__ = "0.1" __version__ = "0.1"
__author__ = "Christian Dale" __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 socket
import ssl import ssl
from nzbtomedia.synchronousdeluge import rencode from core.synchronousdeluge import rencode
__all__ = ["DelugeTransfer"] __all__ = ["DelugeTransfer"]

View file

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

View file

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

View file

@ -2,7 +2,7 @@
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com> # Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license. # 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): class TransmissionError(Exception):
""" """

View file

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

View file

@ -2,9 +2,9 @@
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com> # Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license. # 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): class Session(object):
""" """

View file

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

View file

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

View file

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

View file

@ -500,19 +500,19 @@
import os import os
import sys import sys
import datetime import datetime
import nzbtomedia import core
from nzbtomedia.autoProcess.autoProcessComics import autoProcessComics from core.autoProcess.autoProcessComics import autoProcessComics
from nzbtomedia.autoProcess.autoProcessGames import autoProcessGames from core.autoProcess.autoProcessGames import autoProcessGames
from nzbtomedia.autoProcess.autoProcessMovie import autoProcessMovie from core.autoProcess.autoProcessMovie import autoProcessMovie
from nzbtomedia.autoProcess.autoProcessMusic import autoProcessMusic from core.autoProcess.autoProcessMusic import autoProcessMusic
from nzbtomedia.autoProcess.autoProcessTV import autoProcessTV from core.autoProcess.autoProcessTV import autoProcessTV
from nzbtomedia.nzbToMediaUtil import getDirs, extractFiles, cleanDir, update_downloadInfoStatus, get_downloadInfo, CharReplace, convert_to_ascii, get_nzoid from core.nzbToMediaUtil import getDirs, extractFiles, cleanDir, update_downloadInfoStatus, get_downloadInfo, CharReplace, convert_to_ascii, get_nzoid
from nzbtomedia.nzbToMediaUserScript import external_script from core.nzbToMediaUserScript import external_script
from nzbtomedia import logger, nzbToMediaDB from core import logger, nzbToMediaDB
# post-processing # post-processing
def process(inputDirectory, inputName=None, status=0, clientAgent='manual', download_id=None, inputCategory=None, failureLink=None): 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( logger.error(
'The input directory:[%s] is the Default Download Directory. Please configure category directories to prevent processing of other media.' % ( 'The input directory:[%s] is the Default Download Directory. Please configure category directories to prevent processing of other media.' % (
inputDirectory)) inputDirectory))
@ -521,7 +521,7 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down
if not download_id and clientAgent == 'sabnzbd': if not download_id and clientAgent == 'sabnzbd':
download_id = get_nzoid(inputName) 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)) logger.debug('Adding NZB download info for directory %s to database' % (inputDirectory))
myDB = nzbToMediaDB.DBConnection() myDB = nzbToMediaDB.DBConnection()
@ -543,9 +543,9 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down
if inputCategory is None: if inputCategory is None:
inputCategory = 'UNCAT' inputCategory = 'UNCAT'
usercat = inputCategory usercat = inputCategory
section = nzbtomedia.CFG.findsection(inputCategory).isenabled() section = core.CFG.findsection(inputCategory).isenabled()
if section is None: if section is None:
section = nzbtomedia.CFG.findsection("ALL").isenabled() section = core.CFG.findsection("ALL").isenabled()
if section is None: if section is None:
logger.error( 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.' % ( '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 extract = 0
try: 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!' % ( logger.error('Remote Path is enabled for %s:%s but no Network mount points are defined. Please check your autoProcessMedia.cfg, exiting!' % (
sectionName, inputCategory)) sectionName, inputCategory))
return [-1, ""] return [-1, ""]
@ -621,10 +621,10 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down
def main(args, section=None): def main(args, section=None):
# Initialize the config # Initialize the config
nzbtomedia.initialize(section) core.initialize(section)
# clientAgent for NZBs # clientAgent for NZBs
clientAgent = nzbtomedia.NZB_CLIENTAGENT clientAgent = core.NZB_CLIENTAGENT
logger.info("#########################################################") logger.info("#########################################################")
logger.info("## ..::[%s]::.. ##" % os.path.basename(__file__)) 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 # Check if the script is called from nzbget 11.0 or later
if os.environ['NZBOP_VERSION'][0:5] < '11.0': 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']))) 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']))) 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'], clientAgent=clientAgent, download_id=download_id, inputCategory=os.environ['NZBPP_CATEGORY'],
failureLink=failureLink) failureLink=failureLink)
# SABnzbd Pre 0.7.17 # SABnzbd Pre 0.7.17
elif len(args) == nzbtomedia.SABNZB_NO_OF_ARGUMENTS: elif len(args) == core.SABNZB_NO_OF_ARGUMENTS:
# SABnzbd argv: # SABnzbd argv:
# 1 The final directory of the job (full path) # 1 The final directory of the job (full path)
# 2 The original name of the NZB file # 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, result = process(args[1], inputName=args[2], status=args[7], inputCategory=args[5], clientAgent=clientAgent,
download_id='') download_id='')
# SABnzbd 0.7.17+ # SABnzbd 0.7.17+
elif len(args) >= nzbtomedia.SABNZB_0717_NO_OF_ARGUMENTS: elif len(args) >= core.SABNZB_0717_NO_OF_ARGUMENTS:
# SABnzbd argv: # SABnzbd argv:
# 1 The final directory of the job (full path) # 1 The final directory of the job (full path)
# 2 The original name of the NZB file # 2 The original name of the NZB file
@ -727,16 +727,16 @@ def main(args, section=None):
# Perform Manual Post-Processing # Perform Manual Post-Processing
logger.warning("Invalid number of arguments received from client, Switching to manual run mode ...") 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: for subsection in subsections:
if not nzbtomedia.CFG[section][subsection].isenabled(): if not core.CFG[section][subsection].isenabled():
continue continue
for dirName in getDirs(section, subsection, link = 'move'): for dirName in getDirs(section, subsection, link = 'move'):
logger.info("Starting manual run for %s:%s - Folder:%s" % (section, subsection, dirName)) 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))) logger.info("Checking database for download info for %s ..." % (os.path.basename(dirName)))
nzbtomedia.DOWNLOADINFO = get_downloadInfo(os.path.basename(dirName), 0) core.DOWNLOADINFO = get_downloadInfo(os.path.basename(dirName), 0)
if nzbtomedia.DOWNLOADINFO: if core.DOWNLOADINFO:
logger.info( logger.info(
"Found download info for %s, setting variables now ..." % (os.path.basename(dirName))) "Found download info for %s, setting variables now ..." % (os.path.basename(dirName)))
else: else:
@ -746,23 +746,23 @@ def main(args, section=None):
) )
try: try:
clientAgent = str(nzbtomedia.DOWNLOADINFO[0]['client_agent']) clientAgent = str(core.DOWNLOADINFO[0]['client_agent'])
except: except:
clientAgent = 'manual' clientAgent = 'manual'
try: try:
download_id = str(nzbtomedia.DOWNLOADINFO[0]['input_id']) download_id = str(core.DOWNLOADINFO[0]['input_id'])
except: except:
download_id = None 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 continue
try: try:
dirName = dirName.encode(nzbtomedia.SYS_ENCODING) dirName = dirName.encode(core.SYS_ENCODING)
except: pass except: pass
inputName = os.path.basename(dirName) inputName = os.path.basename(dirName)
try: try:
inputName = inputName.encode(nzbtomedia.SYS_ENCODING) inputName = inputName.encode(core.SYS_ENCODING)
except: pass except: pass
results = process(dirName, inputName, 0, clientAgent=clientAgent, results = process(dirName, inputName, 0, clientAgent=clientAgent,
@ -777,16 +777,16 @@ def main(args, section=None):
if result[1]: if result[1]:
print result[1] + "!" # For SABnzbd Status display. print result[1] + "!" # For SABnzbd Status display.
if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11 if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11
del nzbtomedia.MYAPP del core.MYAPP
return (nzbtomedia.NZBGET_POSTPROCESS_SUCCESS) return (core.NZBGET_POSTPROCESS_SUCCESS)
else: else:
logger.error("A problem was reported in the %s script." % args[0]) logger.error("A problem was reported in the %s script." % args[0])
if result[1]: if result[1]:
print result[1] + "!" # For SABnzbd Status display. print result[1] + "!" # For SABnzbd Status display.
if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11 if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11
del nzbtomedia.MYAPP del core.MYAPP
return (nzbtomedia.NZBGET_POSTPROCESS_ERROR) return (core.NZBGET_POSTPROCESS_ERROR)
del nzbtomedia.MYAPP del core.MYAPP
return (result[0]) 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 sys
import datetime import datetime
import re import re
import nzbtomedia import core
from nzbtomedia.nzbToMediaAutoFork import autoFork from core.nzbToMediaAutoFork import autoFork
from nzbtomedia import nzbToMediaDB from core import nzbToMediaDB
from nzbtomedia.transcoder import transcoder from core.transcoder import transcoder
from nzbtomedia.nzbToMediaUtil import get_downloadInfo, server_responding from core.nzbToMediaUtil import get_downloadInfo, server_responding
# Initialize the config # 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 #print label
if transcoder.isVideoGood(nzbtomedia.TEST_FILE, 0): if transcoder.isVideoGood(core.TEST_FILE, 0):
print "FFPROBE Works" print "FFPROBE Works"
else: else:
print "FFPROBE FAILED" print "FFPROBE FAILED"
test = nzbtomedia.CFG['SickBeard','NzbDrone']['tv'].isenabled() test = core.CFG['SickBeard','NzbDrone']['tv'].isenabled()
print test print test
section = nzbtomedia.CFG.findsection('tv').isenabled() section = core.CFG.findsection('tv').isenabled()
print section print section
print len(section) print len(section)
fork, fork_params = autoFork('SickBeard', 'tv') fork, fork_params = autoFork('SickBeard', 'tv')
@ -44,4 +44,4 @@ print Language('eng')
import subliminal import subliminal
subliminal.cache_region.configure('dogpile.cache.memory') subliminal.cache_region.configure('dogpile.cache.memory')
del nzbtomedia.MYAPP del core.MYAPP