def flushLastdown(self):
     lastDown().flushLastdown()
     message = 'Downloaded subtitles database flushed'
     tmpl = PageTemplate(file="interface/templates/home.tmpl")
     tmpl.message = message
     tmpl.displaymessage = "Yes"
     tmpl.modalheader = "Information"
     return str(tmpl)
Exemplo n.º 2
0
 def flushLastdown(self):
     lastDown().flushLastdown()
     message = 'Downloaded subtitles database flushed'
     tmpl = PageTemplate(file="interface/templates/home.tmpl")
     tmpl.message = message
     tmpl.displaymessage = "Yes"
     tmpl.modalheader = "Information"
     return str(tmpl)
def DownloadSub(Wanted,SubList):    
      
    log.debug("downloadSubs: Download dict: %r" % Wanted)
    destdir = Wanted['folder']
    destsrt = os.path.join(Wanted['folder'], Wanted['file'])
    if autosub.DUTCH in SubList[0]['Lang'] :
        destsrt += Wanted['NLext']
    elif autosub.ENGLISH in SubList[0]['Lang'] :
        destsrt += Wanted['ENext']
    else:
        return False

    SubData = None
    Downloaded = False 
    for Sub in SubList:
        log.debug("downloadSubs: Trying to download %s subtitle(s) from %s using this link %s" % (Wanted['langs'],Sub['website'],Sub['url']))      

        if Sub['website'] == 'opensubtitles.org':
            log.debug("downloadSubs: Api for opensubtitles.org is chosen for subtitle %s" % Wanted['file'])
            SubData = openSubtitles(Sub['url'],Sub['SubCodec'])
        elif Sub['website'] == 'addic7ed.com':
            log.debug("downloadSubs: Scraper for Addic7ed.com is chosen for subtitle %s" % Wanted['file'])
            SubData = autosub.ADDIC7EDAPI.download(Sub['url'])
        else:
            log.debug("downloadSubs: Scraper for %s is chosen for subtitle %s" % (Sub['website'],Wanted['file']))
            SubData = subseeker(Sub['url'],Sub['website'])
        if SubData:
            if WriteSubFile(SubData,destsrt):
                Downloaded = True           
                break
    if Downloaded:
        log.info("downloadSubs: Subtitle %s is downloaded from %s" % (Sub['releaseName'],Sub['website']))
    else:
        log.debug("downloadSubs: Could not download any correct subtitle file for %s" % Wanted['file'])
        return False   
    Wanted['subtitle'] = "%s downloaded from %s" % (Sub['releaseName'].strip(),Sub['website'])
    VideoTimeStamp = Wanted['timestamp']
    Wanted['timestamp'] = unicode(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.path.getmtime(destsrt))))
    lastDown().setlastDown(Sub['Lang'],dict = Wanted)
    Wanted['timestamp'] = VideoTimeStamp
    # Send notification 

    VideoFile = os.path.join(Wanted['folder'] , Wanted['file'] + Wanted['container'])
    notify.notify(Sub['Lang'], destsrt.encode('ascii','replace'), VideoFile.encode('ascii','replace'), Sub['website'].split('.')[0])

    if autosub.POSTPROCESSCMD:
        postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + destsrt + '" "' + VideoFile + '" "' + Sub['Lang'] + '" "' + Wanted["title"] + '" "' + Wanted["season"] + '" "' + Wanted["episode"] + '" '
        log.debug("downloadSubs: Postprocess: running %s" % postprocesscmdconstructed)
        log.info("downloadSubs: Running PostProcess")
        postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(postprocesscmdconstructed)
        log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
        if postprocesserr:
            log.error("downloadSubs: PostProcess: %s" % postprocesserr)
    if autosub.NODE_ID == 73855751279:
        log.debug('DownloadSub: Starting my postprocess')
        MyPostProcess(Wanted,destsrt,Sub['Lang'])
    log.debug('downloadSubs: Finished for %s' % Wanted["file"])
    return True
def DownloadSub(Wanted,SubList):    
      
    log.debug("downloadSubs: Download dict: %r" % Wanted)
    destdir = Wanted['folder']
    destsrt = os.path.join(Wanted['folder'], Wanted['file'])
    if autosub.DUTCH in SubList[0]['Lang'] :
        destsrt += Wanted['NLext']
    elif autosub.ENGLISH in SubList[0]['Lang'] :
        destsrt += Wanted['ENext']
    else:
        return False

    SubData = None
    Downloaded = False 
    for Sub in SubList:
        log.debug("downloadSubs: Trying to download %s subtitle(s) from %s using this link %s" % (Wanted['langs'],Sub['website'],Sub['url']))      

        if Sub['website'] == 'opensubtitles.org':
            log.debug("downloadSubs: Api for opensubtitles.org is chosen for subtitle %s" % Wanted['file'])
            SubData = openSubtitles(Sub['url'],Sub['SubCodec'])
        elif Sub['website'] == 'addic7ed.com':
            log.debug("downloadSubs: Scraper for Addic7ed.com is chosen for subtitle %s" % Wanted['file'])
            SubData = autosub.ADDIC7EDAPI.download(Sub['url'])
        else:
            log.debug("downloadSubs: Scraper for %s is chosen for subtitle %s" % (Sub['website'],Wanted['file']))
            SubData = subseeker(Sub['url'],Sub['website'])
        if SubData:
            if WriteSubFile(SubData,destsrt):
                Downloaded = True           
                break
    if Downloaded:
        log.info("downloadSubs: Subtitle %s is downloaded from %s" % (Sub['releaseName'],Sub['website']))
    else:
        log.debug("downloadSubs: Could not download any correct subtitle file for %s" % Wanted['file'])
        return False   
    Wanted['subtitle'] = "%s downloaded from %s" % (Sub['releaseName'].strip(),Sub['website'])
    Wanted['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.path.getmtime(destsrt)))

    lastDown().setlastDown(Sub['Lang'],dict = Wanted)
    # Send notification 

    VideoFile = os.path.join(Wanted['folder'] , Wanted['file'] + Wanted['container'])
    if (autosub.NOTIFYNL and Sub['Lang'] == autosub.DUTCH) or (autosub.NOTIFYEN and Sub['Lang'] == autosub.ENGLISH) :
        notify.notify(Sub['Lang'], destsrt.encode('ascii','replace'), VideoFile.encode('ascii','replace'), Sub['website'])

    if autosub.POSTPROCESSCMD:
        postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + destsrt + '" "' + VideoFile + '" "' + Sub['Lang'] + '" "' + Wanted["title"] + '" "' + Wanted["season"] + '" "' + Wanted["episode"] + '" '
        log.debug("downloadSubs: Postprocess: running %s" % postprocesscmdconstructed)
        log.info("downloadSubs: Running PostProcess")
        postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(postprocesscmdconstructed)
        log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
        if postprocesserr:
            log.error("downloadSubs: PostProcess: %s" % postprocesserr)
    if autosub.NODE_ID == 73855751279:
        log.debug('DownloadSub: Starting my postprocess')
        MyPostProcess(Wanted,destsrt,Sub['Lang'])
    log.debug('downloadSubs: Finished for %s' % Wanted["file"])
    return True
Exemplo n.º 5
0
def DownloadSub(Wanted,SubList):    
    
    log.debug("downloadSubs: Starting DownloadSub function")    
   
    log.debug("downloadSubs: Download dict seems OK. Dumping it for debug: %r" % Wanted) 
    destsrt = Wanted['destinationFileLocationOnDisk']
    destdir = os.path.split(destsrt)[0]
    if not os.path.exists(destdir):
        log.debug("checkSubs: no destination directory %s" %destdir)
        return False
    elif not os.path.exists(destdir):
        log.debug("checkSubs: no destination directory %s" %destdir)
        return False        

    SubData = None
    Downloaded = False 
    for Sub in SubList:   
        log.debug("downloadSubs: Trying to download subtitle from %s using this link %s" % (Sub['website'],Sub['url']))      

        if Sub['website'] == 'opensubtitles.org':
            log.debug("downloadSubs: Api for opensubtitles.org is chosen for subtitle %s" % destsrt)
            SubData = openSubtitles(Sub['url'],Sub['SubCodec'])
        elif Sub['website'] == 'addic7ed.com':
            log.debug("downloadSubs: Scraper for Addic7ed.com is chosen for subtitle %s" % destsrt)
            SubData = autosub.ADDIC7EDAPI.download(Sub['url'])
        else:
            log.debug("downloadSubs: Scraper for %s is chosen for subtitle %s" % (Sub['website'],destsrt))
            SubData = subseeker(Sub['url'],Sub['website'])
        if SubData:
            if WriteSubFile(SubData,destsrt):
                Downloaded = True           
                break
    if Downloaded:
        log.info("downloadSubs: Subtitle %s is downloaded from %s" % (Sub['releaseName'],Sub['website']))
    else:
        log.error("downloadSubs: Could not download any correct subtitle file for %s" % Wanted['originalFileLocationOnDisk'])
        return False   
    Wanted['subtitle'] = "%s downloaded from %s" % (Sub['releaseName'],Sub['website'])
    Wanted['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(os.path.getmtime(destsrt)))

    lastDown().setlastDown(dict = Wanted)
    # Send notification 

    notify.notify(Wanted['downlang'], destsrt, Wanted["originalFileLocationOnDisk"], Sub['website'])
    if autosub.POSTPROCESSCMD:
        postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + Wanted['destinationFileLocationOnDisk'] + '" "' + Wanted["originalFileLocationOnDisk"] + '" "' + Wanted["downlang"] + '" "' + Wanted["title"] + '" "' + Wanted["season"] + '" "' + Wanted["episode"] + '" '
        log.debug("downloadSubs: Postprocess: running %s" % postprocesscmdconstructed)
        log.info("downloadSubs: Running PostProcess")
        postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(postprocesscmdconstructed)
        log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
        if postprocesserr:
            log.error("downloadSubs: PostProcess: %s" % postprocesserr)
            #log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
    
    log.debug('downloadSubs: Finished for %s' % Wanted["originalFileLocationOnDisk"])
    return True
def DownloadSub(downloadDict):
    #Before we download, lest check if there are enough APICalls left
    if not autosub.Helpers.checkAPICalls():
        log.error("downloadSubs: out of api calls")
        return False
    
    log.debug("downloadSubs: Starting DownloadSub function")
    
    if 'destinationFileLocationOnDisk' in downloadDict.keys() and 'downloadLink' in downloadDict.keys():
        log.debug("downloadSubs: Download dict seems ook. Dumping it for debug: %r" %downloadDict) 
        destsrt = downloadDict['destinationFileLocationOnDisk']
        downloadLink = downloadDict['downloadLink']
        
        try:
            bierdopjeapi = API(downloadLink)
            log.debug("downloadSubs: Trying to download the following subtitle %s" %downloadLink)
        except:
            log.error("downloadSubs: The server returned an error for request %s" % downloadLink)
            return False
        
        destdir = os.path.split(destsrt)[0] #make sure the download dest is there
        if not os.path.exists(destdir):
            log.debug("checkSubs: no destination directory %s" %destdir)
            return False
        elif not os.path.lexists(destdir):
            log.debug("checkSubs: no destination directory %s" %destdir)
            return False
        
        #Lets first download the subtitle to a tempfile and then write it to the destination
        tmpfile = tempfile.TemporaryFile('w+b')
        
        try:
            if bierdopjeapi.resp:
                tmpfile.write(bierdopjeapi.resp.read())
                tmpfile.write('\n') #If subtitle is exclusive for bierdopje, they add some footer which doesn't have a line feed >.>
            bierdopjeapi.close()
        except:
            log.error("downloadSubs: Error while downloading subtitle %s. Common cases: bierdopje.com not reachable or the subtitle is corrupt on bierdopje.com. " % destsrt)
            return False
        
        tmpfile.seek(0) #Return to the start of the file
        try:
            log.debug("downloadSubs: Trying to save the subtitle to the filesystem")
            open(destsrt, 'wb').write(tmpfile.read())
            tmpfile.close()
        except IOError:
            log.error("downloadSubs: Could not write subtitle file. Permission denied? Enough diskspace?")
            tmpfile.close()
            return False
        
        log.info("downloadSubs: DOWNLOADED: %s" % destsrt)
        
        downloadDict['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
        
        lastDown().setlastDown(dict = downloadDict)
        
        notify.notify(downloadDict['downlang'], destsrt, downloadDict["originalFileLocationOnDisk"])

        if autosub.POSTPROCESSCMD:
            postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + downloadDict["destinationFileLocationOnDisk"] + '" "' + downloadDict["originalFileLocationOnDisk"] + '"'
            log.debug("downloadSubs: Postprocess: running %s" % postprocesscmdconstructed)
            log.info("downloadSubs: Running PostProcess")
            postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(postprocesscmdconstructed)
            if postprocesserr:
                log.error("downloadSubs: PostProcess: %s" % postprocesserr)
            log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
        
        log.debug('downloadSubs: ')
        return True
        
    else:
        log.error("downloadSub: No downloadLink or locationOnDisk found at downloadItem, skipping")
        return False
Exemplo n.º 7
0
def DownloadSub(allResults, a7Response, downloadItem):    
    
    log.debug("downloadSubs: Starting DownloadSub function")    
    
    if not 'destinationFileLocationOnDisk' in downloadItem.keys():
        log.error("downloadSub: No locationOnDisk found at downloadItem, skipping")
        return False
    
    log.debug("downloadSubs: Download dict seems OK. Dumping it for debug: %r" % downloadItem) 
    destsrt = downloadItem['destinationFileLocationOnDisk']
    destdir = os.path.split(destsrt)[0]
    if not os.path.exists(destdir):
        log.debug("checkSubs: no destination directory %s" %destdir)
        return False
    elif not os.path.lexists(destdir):
        log.debug("checkSubs: no destination directory %s" %destdir)
        return False        
    
    HIfallback = {}
    fileStringIO = None
    Downloaded = False 
    for result in allResults:   
        url = result['url']
        release = result['releasename']
        website = result['website']             
       
        log.debug("downloadSubs: Trying to download subtitle from %s using this link %s" % (website,url))      

        if website == 'undertexter.se':
            log.debug("downloadSubs: Scraper for Undertexter.se is chosen for subtitle %s" % destsrt)
            fileStringIO = undertexter(url) 
        elif website == 'subscene.com':    
            log.debug("downloadSubs: Scraper for Subscene.com is chosen for subtitle %s" % destsrt)
            fileStringIO = subscene(url)
        elif website == 'podnapisi.net':
            log.debug("downloadSubs: Scraper for Podnapisi.net is chosen for subtitle %s" % destsrt)
            fileStringIO = podnapisi(url)
        elif website == 'opensubtitles.org':
            log.debug("downloadSubs: Scraper for opensubtitles.org is chosen for subtitle %s" % destsrt)
            fileStringIO = openSubtitles(url)
        elif website == 'addic7ed.com' and a7Response:
            log.debug("downloadSubs: Scraper for Addic7ed.com is chosen for subtitle %s" % destsrt)
            if result['HI']:
                if not HIfallback:
                    log.debug("downloadSubs: Addic7ed HI version: store as fallback")
                    HIfallback = result            
                continue
            fileStringIO = addic7ed(url)   
        else:
            log.error("downloadSubs: %s is not recognized. Something went wrong!" % website)
        if fileStringIO:
            log.debug("downloadSubs: Subtitle is downloading from %s" % website)      
            if not GetSubFile(fileStringIO,destsrt):
                if website == 'opensubtitles.org':
                    log.error("downloadSubs: Downloaded file from opensubtitles is not a sub file, try to avoid Captcha")
                    Referer = autosub.OPENSUBTTITLESSESSION.headers['referer']
                    OS.OpenSubtitlesLogout()
                    OS.TimeOut(60)
                    OS.OpenSubtitlesLogin()
                    autosub.OPENSUBTTITLESSESSION.headers.update({'referer': Referer})
                    if not GetSubFile(fileStringIO,destsrt):
                        log.error("downloadSubs: Downloaded file is still not a correct .srt file. Skipping it!")
                else:
                    log.error("downloadSubs: Sub from %s not a correct .srt file. Skipping it." % website)
            else:
                Downloaded = True
                log.info("downloadSubs: Subtitle %s is downloaded from %s" % (destsrt,website))
                break
        else:
            if HIfallback:
                log.debug("downloadSubs: Downloading HI subtitle as fallback")
                fileStringIO = addic7ed(url)
                if not GetSubFile(fileStringIO,destsrt):
                    log.error("downloadSubs: Hearing impact sub from %s not a correct .srt file. Skipping it." % website)
                else:
                    Downloaded = True
                    release = HIfallback['releasename']
                    website = HIfallback['website']
                    break
    if not Downloaded:
        log.error("downloadSubs: Could not download a correct subtitle file for %s" % destsrt)
        return False

    downloadItem['subtitle'] = "%s downloaded from %s" % (release,website)
    downloadItem['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
    
    lastDown().setlastDown(dict = downloadItem)
    # Send notification        
    notify.notify(downloadItem['downlang'], destsrt, downloadItem["originalFileLocationOnDisk"], website)
    if autosub.POSTPROCESSCMD:
        postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + downloadItem["destinationFileLocationOnDisk"] + '" "' + downloadItem["originalFileLocationOnDisk"] + '" "' + downloadItem["downlang"] + '" "' + downloadItem["title"] + '" "' + downloadItem["season"] + '" "' + downloadItem["episode"] + '" '
        log.debug("downloadSubs: Postprocess: running %s" % postprocesscmdconstructed)
        log.info("downloadSubs: Running PostProcess")
        postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(postprocesscmdconstructed)
        log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
        if postprocesserr:
            log.error("downloadSubs: PostProcess: %s" % postprocesserr)
            #log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
    
    log.debug('downloadSubs: Finished for %s' % downloadItem["originalFileLocationOnDisk"])
    return True
Exemplo n.º 8
0
 def flushLastdown(self):
     lastDown().flushLastdown()
     message = 'Last downloaded subtitle database flushed'
     tmpl = PageTemplate(file="interface/templates/message.tmpl")
     tmpl.message = message
     return str(tmpl)
Exemplo n.º 9
0
def DownloadSub(allResults, a7Response, downloadItem):

    log.debug("downloadSubs: Starting DownloadSub function")

    if not 'destinationFileLocationOnDisk' in downloadItem.keys():
        log.error(
            "downloadSub: No locationOnDisk found at downloadItem, skipping")
        return False

    log.debug(
        "downloadSubs: Download dict seems OK. Dumping it for debug: %r" %
        downloadItem)
    destsrt = downloadItem['destinationFileLocationOnDisk']
    destdir = os.path.split(destsrt)[0]
    if not os.path.exists(destdir):
        log.debug("checkSubs: no destination directory %s" % destdir)
        return False
    elif not os.path.lexists(destdir):
        log.debug("checkSubs: no destination directory %s" % destdir)
        return False

    HIfallback = {}
    fileStringIO = None
    Downloaded = False
    for result in allResults:
        url = result['url']
        release = result['releasename']
        website = result['website']

        log.debug(
            "downloadSubs: Trying to download subtitle from %s using this link %s"
            % (website, url))

        if website == 'undertexter.se':
            log.debug(
                "downloadSubs: Scraper for Undertexter.se is chosen for subtitle %s"
                % destsrt)
            fileStringIO = undertexter(url)
        elif website == 'subscene.com':
            log.debug(
                "downloadSubs: Scraper for Subscene.com is chosen for subtitle %s"
                % destsrt)
            fileStringIO = subscene(url)
        elif website == 'podnapisi.net':
            log.debug(
                "downloadSubs: Scraper for Podnapisi.net is chosen for subtitle %s"
                % destsrt)
            fileStringIO = podnapisi(url)
        elif website == 'opensubtitles.org':
            log.debug(
                "downloadSubs: Scraper for opensubtitles.org is chosen for subtitle %s"
                % destsrt)
            fileStringIO = openSubtitles(url)
        elif website == 'addic7ed.com' and a7Response:
            log.debug(
                "downloadSubs: Scraper for Addic7ed.com is chosen for subtitle %s"
                % destsrt)
            if result['HI']:
                if not HIfallback:
                    log.debug(
                        "downloadSubs: Addic7ed HI version: store as fallback")
                    HIfallback = result
                continue
            fileStringIO = addic7ed(url)
        else:
            log.error(
                "downloadSubs: %s is not recognized. Something went wrong!" %
                website)
        if fileStringIO:
            log.debug("downloadSubs: Subtitle is downloading from %s" %
                      website)
            if not GetSubFile(fileStringIO, destsrt):
                if website == 'opensubtitles.org':
                    log.error(
                        "downloadSubs: Downloaded file from opensubtitles is not a sub file, try to avoid Captcha"
                    )
                    Referer = autosub.OPENSUBTTITLESSESSION.headers['referer']
                    OS.OpenSubtitlesLogout()
                    OS.TimeOut(60)
                    OS.OpenSubtitlesLogin()
                    autosub.OPENSUBTTITLESSESSION.headers.update(
                        {'referer': Referer})
                    if not GetSubFile(fileStringIO, destsrt):
                        log.error(
                            "downloadSubs: Downloaded file is still not a correct .srt file. Skipping it!"
                        )
                else:
                    log.error(
                        "downloadSubs: Sub from %s not a correct .srt file. Skipping it."
                        % website)
            else:
                Downloaded = True
                log.info("downloadSubs: Subtitle %s is downloaded from %s" %
                         (destsrt, website))
                break
        else:
            if HIfallback:
                log.debug("downloadSubs: Downloading HI subtitle as fallback")
                fileStringIO = addic7ed(url)
                if not GetSubFile(fileStringIO, destsrt):
                    log.error(
                        "downloadSubs: Hearing impact sub from %s not a correct .srt file. Skipping it."
                        % website)
                else:
                    Downloaded = True
                    release = HIfallback['releasename']
                    website = HIfallback['website']
                    break
    if not Downloaded:
        log.error(
            "downloadSubs: Could not download a correct subtitle file for %s" %
            destsrt)
        return False

    downloadItem['subtitle'] = "%s downloaded from %s" % (release, website)
    downloadItem['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')

    lastDown().setlastDown(dict=downloadItem)
    # Send notification
    notify.notify(downloadItem['downlang'], destsrt,
                  downloadItem["originalFileLocationOnDisk"], website)
    if autosub.POSTPROCESSCMD:
        postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + downloadItem[
            "destinationFileLocationOnDisk"] + '" "' + downloadItem[
                "originalFileLocationOnDisk"] + '" "' + downloadItem[
                    "downlang"] + '" "' + downloadItem[
                        "title"] + '" "' + downloadItem[
                            "season"] + '" "' + downloadItem["episode"] + '" '
        log.debug("downloadSubs: Postprocess: running %s" %
                  postprocesscmdconstructed)
        log.info("downloadSubs: Running PostProcess")
        postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(
            postprocesscmdconstructed)
        log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
        if postprocesserr:
            log.error("downloadSubs: PostProcess: %s" % postprocesserr)
            #log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)

    log.debug('downloadSubs: Finished for %s' %
              downloadItem["originalFileLocationOnDisk"])
    return True
def DownloadSub(allResults, a7Response, downloadItem):    
    
    log.debug("downloadSubs: Starting DownloadSub function")    
    
    if not 'destinationFileLocationOnDisk' in downloadItem.keys():
        log.error("downloadSub: No locationOnDisk found at downloadItem, skipping")
        return False
    
    log.debug("downloadSubs: Download dict seems OK. Dumping it for debug: %r" % downloadItem) 
    destsrt = downloadItem['destinationFileLocationOnDisk']
    destdir = os.path.split(destsrt)[0]
    if not os.path.exists(destdir):
        log.debug("checkSubs: no destination directory %s" %destdir)
        return False
    elif not os.path.lexists(destdir):
        log.debug("checkSubs: no destination directory %s" %destdir)
        return False        
    
    HIfallback = {}
    fileStringIO = None
        
    for result in allResults:   
        url = result['url']
        release = result['releasename']
        website = result['website']             
       
        log.debug("downloadSubs: Trying to download subtitle from %s using this link %s" % (website,url))      

        if website == 'undertexter.se':
            log.debug("downloadSubs: Scraper for Undertexter.se is chosen for subtitle %s" % destsrt)
            fileStringIO = undertexter(url) 
        elif website == 'subscene.com':    
            log.debug("downloadSubs: Scraper for Subscene.com is chosen for subtitle %s" % destsrt)
            fileStringIO = subscene(url)
        elif website == 'podnapisi.net':
            log.debug("downloadSubs: Scraper for Podnapisi.net is chosen for subtitle %s" % destsrt)
            fileStringIO = podnapisi(url)
        elif website == 'opensubtitles.org':
            log.debug("downloadSubs: Scraper for opensubtitles.org is chosen for subtitle %s" % destsrt)
            fileStringIO = openSubtitles(url)
            time.sleep(6)
        elif website == 'addic7ed.com' and a7Response:
            log.debug("downloadSubs: Scraper for Addic7ed.com is chosen for subtitle %s" % destsrt)
            if result['HI']:
                if not HIfallback:
                    log.debug("downloadSubs: Addic7ed HI version: store as fallback")
                    HIfallback = result            
                continue
            fileStringIO = addic7ed(url)   
        else:
            log.error("downloadSubs: %s is not recognized. Something went wrong!" % website)

        if fileStringIO:
            log.debug("downloadSubs: Subtitle is downloading from %s" % website)      
            break
   
        log.debug("downloadSubs: Trying to download another subtitle for this episode")
    
    
    if not fileStringIO:
        if HIfallback:
            log.debug("downloadSubs: Downloading HI subtitle as fallback")
            fileStringIO = addic7ed(url)
            release = HIfallback['releasename']
            website = HIfallback['website']
        else: return False
    if not fileStringIO: 
        log.debug("downloadSubs: No suitable subtitle was found")
        return False
    
    #Lets first download the subtitle to a tempfile and then write it to the destination
    tmpfile = tempfile.TemporaryFile('w+b')
        
    try:
        tmpfile.write(fileStringIO.getvalue())
        tmpfile.write('\n') #If subtitle has some footer which doesn't have a line feed >.>
        tmpfile.seek(0) #Return to the start of the file
    except:
        log.error("downloadSubs: Error while downloading subtitle %s. Subtitle might be corrupt %s." % (destsrt, website))

    try:
        log.debug("downloadSubs: Trying to save the subtitle to the filesystem")
        open(destsrt, 'wb').write(tmpfile.read())
        tmpfile.close()
    except IOError:
        log.error("downloadSubs: Could not write subtitle file. Permission denied? Enough diskspace?")
        tmpfile.close()
        return False
        
    log.info("downloadSubs: DOWNLOADED: %s" % destsrt)
        
    downloadItem['subtitle'] = "%s downloaded from %s" % (release,website)
    downloadItem['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
    
    lastDown().setlastDown(dict = downloadItem)
    # Send notification        
    notify.notify(downloadItem['downlang'], destsrt, downloadItem["originalFileLocationOnDisk"], website)
    if autosub.POSTPROCESSCMD:
        postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + downloadItem["destinationFileLocationOnDisk"] + '" "' + downloadItem["originalFileLocationOnDisk"] + '" "' + downloadItem["downlang"] + '" "' + downloadItem["title"] + '" "' + downloadItem["season"] + '" "' + downloadItem["episode"] + '" '
        log.debug("downloadSubs: Postprocess: running %s" % postprocesscmdconstructed)
        log.info("downloadSubs: Running PostProcess")
        postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(postprocesscmdconstructed)
        log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
        if postprocesserr:
            log.error("downloadSubs: PostProcess: %s" % postprocesserr)
            #log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
    
    log.debug('downloadSubs: Finished for %s' % downloadItem["originalFileLocationOnDisk"])
    return True