redglory

autoProcessMovie.py

Jul 29th, 2013
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 25.44 KB | None | 0 0
  1. import sys
  2. import urllib
  3. import urllib2
  4. import os
  5. import shutil
  6. import ConfigParser
  7. import datetime
  8. import time
  9. import json
  10. import logging
  11. import subprocess
  12. import shlex
  13. import Transcoder
  14. from nzbToMediaEnv import *
  15. from nzbToMediaSceneExceptions import process_all_exceptions
  16. from xml.dom.minidom import parseString
  17.  
  18. Logger = logging.getLogger()
  19.  
  20. class AuthURLOpener(urllib.FancyURLopener):
  21.     def __init__(self, user, pw):
  22.         self.username = user
  23.         self.password = pw
  24.         self.numTries = 0
  25.         urllib.FancyURLopener.__init__(self)
  26.  
  27.     def prompt_user_passwd(self, host, realm):
  28.         if self.numTries == 0:
  29.             self.numTries = 1
  30.             return (self.username, self.password)
  31.         else:
  32.             return ('', '')
  33.  
  34.     def openit(self, url):
  35.         self.numTries = 0
  36.         return urllib.FancyURLopener.open(self, url)
  37.  
  38. def get_imdb(nzbName, dirName):
  39.  
  40.     imdbid = ""    
  41.  
  42.     a = nzbName.find('.cp(') + 4 #search for .cptt( in nzbName
  43.     b = nzbName[a:].find(')') + a
  44.     if a > 3: # a == 3 if not exist
  45.         imdbid = nzbName[a:b]
  46.    
  47.     if imdbid:
  48.         Logger.info("Found movie id %s in name", imdbid)
  49.         return imdbid
  50.    
  51.     a = dirName.find('.cp(') + 4 #search for .cptt( in dirname
  52.     b = dirName[a:].find(')') + a
  53.     if a > 3: # a == 3 if not exist
  54.         imdbid = dirName[a:b]
  55.    
  56.     if imdbid:
  57.         Logger.info("Found movie id %s in directory", imdbid)
  58.         return imdbid
  59.  
  60.     else:
  61.         Logger.warning("Could not find an imdb id in directory or name")
  62.         Logger.info("Postprocessing will continue, but the movie may not be identified correctly by CouchPotato")
  63.         return ""
  64.  
  65. def get_movie_info(myOpener, baseURL, imdbid, download_id):
  66.    
  67.     if not imdbid and not download_id:
  68.         return ""
  69.     url = baseURL + "movie.list/?status=active"
  70.  
  71.     Logger.debug("Opening URL: %s", url)
  72.  
  73.     try:
  74.         urlObj = myOpener.openit(url)
  75.     except:
  76.         Logger.exception("Unable to open URL")
  77.         return ""
  78.  
  79.     movie_id = ""
  80.     try:
  81.         result = json.load(urlObj)
  82.         movieid = [item["id"] for item in result["movies"]]
  83.         library = [item["library"]["identifier"] for item in result["movies"]]
  84.         releases = [item["releases"] for item in result["movies"]]
  85.         imdbid_list = []
  86.         if not imdbid:
  87.             movieindex = [index for index in range(len(movieid)) if len(releases[index]) > 0]
  88.             for index in movieindex:
  89.                 releaseindex = [index2 for index2 in range(len(releases[index])) if len(releases[index][index2]) > 0 and "download_id" in releases[index][index2]["info"] and releases[index][index2]["info"]["download_id"].lower() == download_id.lower()]
  90.                 if len(releaseindex) > 0:
  91.                     imdbid_list.append(library[index])
  92.             unique_imdbid_list = list(set(imdbid_list)) # convert this to a unique list to be sure we only have one imdbid
  93.             if len(unique_imdbid_list) == 1: # we found it.
  94.                 imdbid = unique_imdbid_list[0]
  95.                 Logger.info("Found movie id %s in database via download_id %s", imdbid, download_id)
  96.             else:
  97.                 return ""
  98.  
  99.         for index in range(len(movieid)):
  100.             if library[index] == imdbid:
  101.                 movie_id = str(movieid[index])
  102.                 Logger.info("Found movie id %s in CPS database for movie %s", movie_id, imdbid)
  103.                 break
  104.     except:
  105.         if not imdbid:
  106.             Logger.exception("Could not parse database results to determine imdbid or movie id")
  107.         else:
  108.             Logger.exception("Could not parse database results to determine movie id for imdbid: %s", imdbid)
  109.  
  110.     return movie_id
  111.  
  112. def get_status(myOpener, baseURL, movie_id, clientAgent, download_id):
  113.    
  114.     if not movie_id:
  115.         return "", clientAgent, "none", "none"
  116.     url = baseURL + "movie.get/?id=" + str(movie_id)
  117.     Logger.debug("Looking for status of movie: %s - with release sent to clientAgent: %s and download_id: %s", movie_id, clientAgent, download_id)
  118.     Logger.debug("Opening URL: %s", url)
  119.  
  120.     try:
  121.         urlObj = myOpener.openit(url)
  122.     except:
  123.         Logger.exception("Unable to open URL")
  124.         return "", clientAgent, "none", "none"
  125.     result = json.load(urlObj)
  126.     try:
  127.         movie_status = result["movie"]["status"]["identifier"]
  128.         Logger.debug("This movie is marked as status %s in CouchPotatoServer", movie_status)
  129.     except: # index out of range/doesn't exist?
  130.         Logger.exception("Could not find a status for this movie")
  131.         movie_status = ""
  132.     try:
  133.         release_status = "none"
  134.         if download_id != "" and download_id != "none": # we have the download id from the downloader. Let's see if it's valid.
  135.             release_statuslist = [item["status"]["identifier"] for item in result["movie"]["releases"] if "download_id" in item["info"] and item["info"]["download_id"].lower() == download_id.lower()]
  136.             clientAgentlist = [item["info"]["download_downloader"] for item in result["movie"]["releases"] if "download_id" in item["info"] and item["info"]["download_id"].lower() == download_id.lower()]
  137.             if len(release_statuslist) == 1: # we have found a release by this id. :)
  138.                 release_status = release_statuslist[0]
  139.                 clientAgent = clientAgentlist[0]
  140.                 Logger.debug("Found a single release with download_id: %s for clientAgent: %s. Release status is: %s", download_id, clientAgent, release_status)
  141.                 return movie_status, clientAgent, download_id, release_status
  142.             elif len(release_statuslist) > 1: # we have found many releases by this id. Check for snatched status
  143.                 clients = [item for item in clientAgentlist if item.lower() == clientAgent.lower()]
  144.                 clientAgent = clients[0]
  145.                 if len(clients) == 1: # ok.. a unique entry for download_id and clientAgent ;)
  146.                     release_status = [item["status"]["identifier"] for item in result["movie"]["releases"] if "download_id" in item["info"] and item["info"]["download_id"].lower() == download_id.lower() and item["info"]["download_downloader"] == clientAgent][0]
  147.                     Logger.debug("Found a single release for download_id: %s and clientAgent: %s. Release status is: %s", download_id, clientAgent, release_status)
  148.                 else: # doesn't matter. only really used as secondary confirmation of movie status change. Let's continue.                
  149.                     Logger.debug("Found several releases for download_id: %s and clientAgent: %s. Cannot determine the release status", download_id, clientAgent)
  150.                 return movie_status, clientAgent, download_id, release_status
  151.             else: # clearly the id we were passed doesn't match the database. Reset it and search all snatched releases.... hence the next if (not elif ;) )
  152.                 download_id = ""
  153.         if download_id == "none": # if we couldn't find this initially, there is no need to check next time around.
  154.             return movie_status, clientAgent, download_id, release_status
  155.         elif download_id == "": # in case we didn't get this from the downloader.
  156.             download_idlist = [item["info"]["download_id"] for item in result["movie"]["releases"] if item["status"]["identifier"] == "snatched"]
  157.             clientAgentlist = [item["info"]["download_downloader"] for item in result["movie"]["releases"] if item["status"]["identifier"] == "snatched"]
  158.             if len(clientAgentlist) == 1:
  159.                 if clientAgent == "manual":
  160.                     clientAgent = clientAgentlist[0]
  161.                     download_id = download_idlist[0]
  162.                     release_status = "snatched"
  163.                 elif clientAgent.lower() == clientAgentlist[0].lower():
  164.                     download_id = download_idlist[0]
  165.                     clientAgent = clientAgentlist[0]
  166.                     release_status = "snatched"
  167.                 Logger.debug("Found a single download_id: %s and clientAgent: %s. Release status is: %s", download_id, clientAgent, release_status)
  168.             elif clientAgent == "manual":
  169.                 download_id = "none"
  170.                 release_status = "none"
  171.             else:
  172.                 index = [index for index in range(len(clientAgentlist)) if clientAgentlist[index].lower() == clientAgent.lower()]            
  173.                 if len(index) == 1:
  174.                     download_id = download_idlist[index[0]]
  175.                     clientAgent = clientAgentlist[index[0]]
  176.                     release_status = "snatched"
  177.                     Logger.debug("Found download_id: %s for clientAgent: %s. Release status is: %s", download_id, clientAgent, release_status)
  178.                 else:
  179.                     Logger.info("Found a total of %s releases snatched for clientAgent: %s. Cannot determine download_id. Will perform a renamenr scan to try and process.", len(index), clientAgent)                
  180.                     download_id = "none"
  181.                     release_status = "none"
  182.         else: #something went wrong here.... we should never get to this.
  183.             Logger.info("Could not find a download_id in the database for this movie")
  184.             release_status = "none"
  185.     except: # index out of range/doesn't exist?
  186.         Logger.exception("Could not find a download_id for this movie")
  187.         download_id = "none"
  188.     return movie_status, clientAgent, download_id, release_status
  189.  
  190. def process(dirName, nzbName=None, status=0, clientAgent = "manual", download_id = ""):
  191.  
  192.     status = int(status)
  193.     config = ConfigParser.ConfigParser()
  194.     configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
  195.     Logger.info("Loading config from %s", configFilename)
  196.  
  197.     if not os.path.isfile(configFilename):
  198.         Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
  199.         return 1 # failure
  200.  
  201.     config.read(configFilename)
  202.  
  203.     host = config.get("CouchPotato", "host")
  204.     port = config.get("CouchPotato", "port")
  205.     username = config.get("CouchPotato", "username")
  206.     password = config.get("CouchPotato", "password")
  207.     apikey = config.get("CouchPotato", "apikey")
  208.     delay = float(config.get("CouchPotato", "delay"))
  209.     method = config.get("CouchPotato", "method")
  210.     delete_failed = int(config.get("CouchPotato", "delete_failed"))
  211.     wait_for = int(config.get("CouchPotato", "wait_for"))
  212.  
  213.     try:
  214.         ssl = int(config.get("CouchPotato", "ssl"))
  215.     except (ConfigParser.NoOptionError, ValueError):
  216.         ssl = 0
  217.  
  218.     try:
  219.         web_root = config.get("CouchPotato", "web_root")
  220.     except ConfigParser.NoOptionError:
  221.         web_root = ""
  222.        
  223.     try:    
  224.         transcode = int(config.get("Transcoder", "transcode"))
  225.     except (ConfigParser.NoOptionError, ValueError):
  226.         transcode = 0
  227.  
  228.     myOpener = AuthURLOpener(username, password)
  229.  
  230.     nzbName = str(nzbName) # make sure it is a string
  231.    
  232.     imdbid = get_imdb(nzbName, dirName)
  233.  
  234.     if ssl:
  235.         protocol = "https://"
  236.     else:
  237.         protocol = "http://"
  238.     # don't delay when we are calling this script manually.
  239.     if nzbName == "Manual Run":
  240.         delay = 0
  241.  
  242.     baseURL = protocol + host + ":" + port + web_root + "/api/" + apikey + "/"
  243.    
  244.     movie_id = get_movie_info(myOpener, baseURL, imdbid, download_id) # get the CPS database movie id this movie.
  245.    
  246.     initial_status, clientAgent, download_id, initial_release_status = get_status(myOpener, baseURL, movie_id, clientAgent, download_id)
  247.    
  248.     process_all_exceptions(nzbName.lower(), dirName)
  249.  
  250.     if status == 0:
  251.         if transcode == 1:
  252.             result = Transcoder.Transcode_directory(dirName)
  253.             if result == 0:
  254.                 Logger.debug("Transcoding succeeded for files in %s", dirName)
  255.             else:
  256.                 Logger.warning("Transcoding failed for files in %s", dirName)
  257.  
  258.         if method == "manage":
  259.             command = "manage.update"
  260.         else:
  261.             command = "renamer.scan"
  262.             if clientAgent != "manual" and download_id != "none":
  263.                 command = command + "/?movie_folder=" + dirName + "&downloader=" + clientAgent + "&download_id=" + download_id
  264.  
  265.         url = baseURL + command
  266.  
  267.         Logger.info("Waiting for %s seconds to allow CPS to process newly extracted files", str(delay))
  268.  
  269.         time.sleep(delay)
  270.  
  271.         Logger.debug("Opening URL: %s", url)
  272.  
  273.         try:
  274.             urlObj = myOpener.openit(url)
  275.         except:
  276.             Logger.exception("Unable to open URL")
  277.             return 1 # failure
  278.  
  279.         result = json.load(urlObj)
  280.         Logger.info("CouchPotatoServer returned %s", result)
  281.         if result['success']:
  282.             Logger.info("%s scan started on CouchPotatoServer for %s", method, nzbName)
  283.         else:
  284.             Logger.error("%s scan has NOT started on CouchPotatoServer for %s. Exiting", method, nzbName)
  285.             return 1 # failure
  286.  
  287.     else:
  288.         Logger.info("Download of %s has failed.", nzbName)
  289.         Logger.info("Trying to re-cue the next highest ranked release")
  290.        
  291.         if not movie_id:
  292.             Logger.warning("Cound not find a movie in the database for release %s", nzbName)
  293.             Logger.warning("Please manually ignore this release and refresh the wanted movie")
  294.             Logger.error("Exiting autoProcessMovie script")
  295.             return 1 # failure
  296.  
  297.         url = baseURL + "searcher.try_next/?id=" + movie_id
  298.  
  299.         Logger.debug("Opening URL: %s", url)
  300.  
  301.         try:
  302.             urlObj = myOpener.openit(url)
  303.         except:
  304.             Logger.exception("Unable to open URL")
  305.             return 1 # failure
  306.  
  307.         result = urlObj.readlines()
  308.         for line in result:
  309.             Logger.info("%s", line)
  310.  
  311.         Logger.info("Movie %s set to try the next best release on CouchPotatoServer", movie_id)
  312.         if delete_failed and not dirName in ['sys.argv[0]','/','']:
  313.             Logger.info("Deleting failed files and folder %s", dirName)
  314.             try:
  315.                 shutil.rmtree(dirName)
  316.             except:
  317.                 Logger.exception("Unable to delete folder %s", dirName)
  318.         return 0 # success
  319.    
  320.     if nzbName == "Manual Run":
  321.         return 0 # success
  322.  
  323.     # we will now check to see if CPS has finished renaming before returning to TorrentToMedia and unpausing.
  324.     start = datetime.datetime.now()  # set time for timeout
  325.     pause_for = wait_for * 10 # keep this so we only ever have 6 complete loops.
  326.     while (datetime.datetime.now() - start) < datetime.timedelta(minutes=wait_for):  # only wait 2 (default) minutes, then return.
  327.         movie_status, clientAgent, download_id, release_status = get_status(myOpener, baseURL, movie_id, clientAgent, download_id) # get the current status fo this movie.
  328.         if movie_status != initial_status:  # Something has changed. CPS must have processed this movie.
  329.             Logger.info("SUCCESS: This movie is now marked as status %s in CouchPotatoServer", movie_status)
  330.             return 0 # success
  331.         time.sleep(pause_for) # Just stop this looping infinitely and hogging resources for 2 minutes ;)
  332.     else:
  333.         if release_status != initial_release_status and release_status != "none":  # Something has changed. CPS must have processed this movie.
  334.             Logger.info("SUCCESS: This release is now marked as status %s in CouchPotatoServer", release_status)
  335.             return 0 # success
  336.         else: # The status hasn't changed. we have waited 2 minutes which is more than enough. uTorrent can resule seeding now.
  337.             Logger.warning("The movie does not appear to have changed status after %s minutes. Please check CouchPotato Logs", wait_for)
  338.             return 1 # failure
  339.  
  340. def get_xbmc_json_obj():
  341.    
  342.     config = ConfigParser.ConfigParser()
  343.     configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
  344.    
  345.     if not os.path.isfile(configFilename):
  346.         Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
  347.         return 1 # failure
  348.  
  349.     config.read(configFilename)
  350.  
  351.     #setings for xbmc part of script
  352.     host = config.get("XBMC", "host")
  353.     port = config.get("XBMC", "port")
  354.     username = config.get("XBMC", "username")
  355.     password = config.get("XBMC", "password")
  356.     http_address = 'http://%s:%s/jsonrpc' % (host, port)
  357.    
  358.     try:
  359.          import json
  360.     except ImportError:
  361.          import simplejson as json
  362.     import urllib2, base64
  363.  
  364.     class XBMCJSON:
  365.  
  366.          def __init__(self, server):
  367.               self.server = server
  368.               self.version = '2.0'
  369.  
  370.          def __call__(self, **kwargs):
  371.               method = '.'.join(map(str, self.n))
  372.               self.n = []
  373.               return XBMCJSON.__dict__['Request'](self, method, kwargs)
  374.  
  375.          def __getattr__(self,name):
  376.               if not self.__dict__.has_key('n'):
  377.                     self.n=[]
  378.               self.n.append(name)
  379.               return self
  380.  
  381.          def Request(self, method, kwargs):
  382.               data = [{}]
  383.               data[0]['method'] = method
  384.               data[0]['params'] = kwargs
  385.               data[0]['jsonrpc'] = self.version
  386.               data[0]['id'] = 1
  387.  
  388.               data = json.JSONEncoder().encode(data)
  389.               content_length = len(data)
  390.  
  391.               content = {
  392.                     'Content-Type': 'application/json',
  393.                     'Content-Length': content_length,
  394.               }
  395.      
  396.               request = urllib2.Request(self.server, data, content)
  397.               base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
  398.               request.add_header("Authorization", "Basic %s" % base64string)
  399.  
  400.               f = urllib2.urlopen(request)
  401.               response = f.read()
  402.               f.close()
  403.               response = json.JSONDecoder().decode(response)
  404.  
  405.               try:
  406.                     return response[0]['result']               
  407.               except:
  408.                     return response[0]['error']
  409.                    
  410.     xbmc = XBMCJSON(http_address)
  411.     Logger.info('- XBMC JSON Object successfully created!')
  412.     return xbmc
  413.  
  414. def update_videolibrary(xbmc):
  415.  
  416.     ## Command to update XBMC Video library
  417.     xbmc.VideoLibrary.Scan()
  418.     Logger.info('- XBMC: Updating Video Library.' )
  419.  
  420. #### END ###
  421.  
  422. def runCmd(cmd):
  423.     Logger.info(str(shlex.split(cmd)))
  424.     proc = subprocess.Popen(shlex.split(cmd),
  425.                  stdout=subprocess.PIPE,
  426.                  stderr=subprocess.PIPE,
  427.                  stdin=subprocess.PIPE)
  428.     out, err = proc.communicate()
  429.     ret = proc.returncode
  430.     proc.wait()
  431.     return (ret, out, err, proc)
  432.    
  433. def run_ember():
  434.  
  435.     ###########################################
  436.     #### Ember Media Manager Auto Scraping ####
  437.     ###########################################
  438.     ### Command lines
  439.     ### -------------
  440.     ### -fullask
  441.     ### -fullauto
  442.     ### -missask
  443.     ### -missauto
  444.     ### -newask
  445.     ### -newauto
  446.     ### -markask
  447.     ### -markauto
  448.     ### -file
  449.     ### -folder
  450.     ### -export
  451.     ### -template
  452.     ### -resize
  453.     ### -all
  454.     ### -nfo
  455.     ### -posters
  456.     ### -fanart
  457.     ### -extra
  458.     ### -nowindow
  459.     ### -run
  460.     ###########################################
  461.  
  462.     # Lauch Ember Media Manager and store PID for future kill
  463.     startTime = datetime.datetime.now()
  464.     returnCode, stdOut, stdErr, sp = runCmd('"D:\EmberMM\Ember Media Manager.exe" -newauto -all -nowindow')
  465.     Logger.info('- Ember Media Manager: running on PID: (' + str(sp.pid) + ')' + ' started at: ' + str(startTime))
  466.     endTime = datetime.datetime.now()
  467.     # Kill Lauch Media Manager's PID
  468.     subprocess.call("taskkill /F /T /PID %i"%sp.pid)    
  469.     Logger.info('- Ember Media Manager ran for ' + str((endTime - startTime)))    
  470.     Logger.info('- Killed Ember Media Manager on PID: (' + str(sp.pid) + ')' )    
  471.     # Return Ember processing code
  472.     return returnCode    
  473.  
  474. def run_artdownloader(movie, xbmc):
  475.     #####################################################################################################################
  476.     ###                  $$$ Art types $$$               ######      $$$ Mediatypes $$$  ######   $$$ Medianames $$$  ###
  477.     #####################################################################################################################
  478.     #                          Movies                      ##         mediatype=movie       #                           #
  479.     #------------------------------------------------------##        mediatype=tvshow       # dbid=$INFO[ListItem.DBID] #                             #
  480.     # poster | fanart | extrafanart | extrathumbs | thumb  ##      mediatype=musicvideo     #                           #
  481.     # clearlogo | clearart | discart | banner              ##                               #                           #
  482.     #####################################################################################################################
  483.     #                          TV Shows                    ##
  484.     #------------------------------------------------------##
  485.     # poster | clearlogo | fanart | extrafanart | banner   ##
  486.     # seasonposter | extrathumbs | clearart | tvthumb      ##
  487.     # seasonthumb | seasonbanner | characterart            ##
  488.     #########################################################
  489.     #                        Musicvideos                   ##
  490.     #------------------------------------------------------##
  491.     # poster | fanart | extrafanart | clearart | discart   ##
  492.     # clearlogo | extrathumbs                              ##
  493.     #####################################################################################################################
  494.     #                                           $$$ RunScript Command examples $$$                                      #
  495.     #-------------------------------------------------------------------------------------------------------------------#
  496.     #       XBMC.runscript(script.artwork.downloader, mode=custom, mediatype=movie, silent=true, extrafanart)           #
  497.     #####################################################################################################################
  498.     a=1
  499.  
  500. def get_url(http_address, mode, output, apikey):
  501.     if mode == "qstatus":
  502.         url = http_address + "/api?mode=" + mode + '&output=xml&apikey=' + apikey
  503.     elif mode == "history":
  504.         url = http_address + "/api?mode=" + mode + '&start=0&limit=4&output=' + output + '&apikey=' + apikey
  505.     return url    
  506.  
  507. def check_sabnzbd():
  508.  
  509.     ### Read SABnzbd config settings
  510.     config = ConfigParser.ConfigParser()
  511.     configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
  512.    
  513.     if not os.path.isfile(configFilename):
  514.         Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
  515.         return 1 # failure
  516.  
  517.     config.read(configFilename)
  518.  
  519. # setings for xbmc part of script
  520.     apikey = config.get("SABnzbd", "apikey")
  521.     host = config.get("SABnzbd", "host")
  522.     port = config.get("SABnzbd", "port")
  523.     username = config.get("SABnzbd", "username")
  524.     password = config.get("SABnzbd", "password")
  525.     http_address = 'http://%s:%s/sabnzbd' % (host, port)
  526.  
  527.     ### Wait for SABnzbd to finish all downloads
  528.  
  529.     # Get URL for Queue Status
  530.     url = get_url(http_address, 'qstatus', 'xml', apikey)
  531.    
  532.     # Load the queue:
  533.     queue = urllib2.urlopen(url)
  534.     queuedata = queue.read()
  535.     queue.close()
  536.     ## ACTIVE DOWNLOAD ?##
  537.     # Script checks for active download it will loop here until download is complete
  538.     while True:
  539.         complete = queuedata.count("<noofslots>0</noofslots>")
  540.         if complete != 1:
  541.             Logger.info('- SABnzbd: Downloading...')
  542.             time.sleep(300)
  543.            
  544.             # reload queue or loop will be stuck with old data from first read
  545.             queue = urllib2.urlopen(url)
  546.             queuedata = queue.read()
  547.             queue.close()
  548.            
  549.         # triger to continue    
  550.         if complete == 1:
  551.             Logger.info('- SABnzbd: No active downloads. ')
  552.             break
  553.            
  554.     ## HISTORY - POSTPROCESSING ACTIVE ?##
  555.    
  556.     # Get URL for Post-Processing Status
  557.     url = get_url(http_address, 'history', 'json', apikey)
  558.        
  559.     while True:
  560.         history = urllib2.Request(url)
  561.         response = urllib2.urlopen(history)
  562.         historydata = response.read()
  563.        
  564.         ##looking for stuff we need in history
  565.         Postprocesing = historydata.count('Repairing') or historydata.count('Unpacking') or historydata.count('Verifying')
  566.         Repairing = historydata.count('Repairing')
  567.         Unpacking = historydata.count('Unpacking')
  568.         Verifying = historydata.count('Verifying')
  569.        
  570.         ##logging
  571.         if Repairing >= 1 or Unpacking >= 1 or Verifying >= 1 or Postprocesing  >= 1:
  572.         #    Logger.info('- SABnzbd: Repairing files...')
  573.         #elif Unpacking >= 1:
  574.         #    Logger.info('- SABnzbd: Unpacking files...')
  575.         #elif Verifying >= 1:
  576.         #    Logger.info('- SABnzbd: Verifying files...')
  577.         #if Postprocesing  >= 1:
  578.             Logger.info('- SABnzbd is post-processing...')
  579.             ## loop script while sab is doing something with files
  580.             # time.sleep(120)
  581.             return 2            
  582.         else:
  583.             Logger.info('- SABnzbd: Finished all jobs.')
  584.             return 0
Add Comment
Please, Sign In to add comment