Example #1
0
def update():
    #download ZIP file
    start = time.clock()

    localfile = ROOT_DIR+"/update.zip"

    response = urllib2.urlopen(REMOTE_FILE_XML)
    html = response.read()
    remote_file = common.parseDOM(html,"file")[0].encode("utf-8") #remote version
    downloadtools.downloadfile(remote_file, localfile, notStop=False)

    end = time.clock()
    logger.info("org.harddevelop.kodi.tv Downloaded in %d seconds " % (end-start+1))

    separatorChar = "/"

    if xbmc.getCondVisibility( "system.platform.windows" ):
        logger.debug("Detected Windows system...")
        separatorChar = "\\"

    #unzip
    unzipper = ziptools.ziptools()
    logger.info("org.harddevelop.kodi.tv destpathname=%s" % ROOT_DIR)
    addons_dir = xbmc.translatePath(ROOT_DIR[:ROOT_DIR.rfind(separatorChar)+1])
    current_plugin_dir = xbmc.translatePath(ROOT_DIR[ROOT_DIR.rfind(separatorChar)+1:])
    logger.debug("using dir: "+addons_dir+" to extract content")

    unzipper.extractReplacingMainFolder(localfile,addons_dir,current_plugin_dir) #github issues
    #unzipper.extract(localfile,ROOT_DIR)

    #clean downloaded zip file
    logger.info("org.harddevelop.kodi.tv clean zip file...")
    os.remove(localfile)
    logger.info("org.harddevelop.kodi.tv clean done!")
Example #2
0
def update(params):
    # Descarga el ZIP
    logger.info("streamondemand.core.updater update")
    remotefilename = REMOTE_FILE
    localfilename = LOCAL_FILE + params.get("version") + ".zip"
    logger.info("streamondemand.core.updater remotefilename=%s" %
                remotefilename)
    logger.info("streamondemand.core.updater localfilename=%s" % localfilename)
    logger.info("streamondemand.core.updater descarga fichero...")
    inicio = time.clock()

    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename, continuar=False)

    fin = time.clock()
    logger.info("streamondemand.core.updater Descargado en %d segundos " %
                (fin - inicio + 1))

    # Lo descomprime
    logger.info("streamondemand.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("streamondemand.core.updater destpathname=%s" % destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("streamondemand.core.updater borra fichero...")
    os.remove(localfilename)
    logger.info("streamondemand.core.updater ...fichero borrado")
def update(params):
    # Descarga el ZIP
    logger.info("streamondemand-pureita.core.updater update")
    remotefilename = "https://github.com/Fenice82/plugin.video.streamondemand-pureita/archive/master.zip"
    localfilename = LOCAL_FILE
    logger.info("streamondemand-pureita.core.updater remotefilename=%s" %
                remotefilename)
    logger.info("streamondemand-pureita.core.updater localfilename=%s" %
                localfilename)
    logger.info("streamondemand-pureita.core.updater descarga fichero...")
    inicio = time.clock()

    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename, continuar=False)

    fin = time.clock()
    logger.info(
        "streamondemand-pureita.core.updater Descargado en %d segundos " %
        (fin - inicio + 1))

    # Lo descomprime
    logger.info("streamondemand-pureita.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("streamondemand-pureita.core.updater destpathname=%s" %
                destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("streamondemand-pureita.core.updater borra fichero...")
    os.remove(localfilename)
    logger.info("streamondemand-pureita.core.updater ...fichero borrado")
Example #4
0
def download_and_install(remote_file_name, local_file_name):
    logger.info("from " + remote_file_name + " to " + local_file_name)

    if os.path.exists(local_file_name):
        os.remove(local_file_name)

    # Descarga el fichero
    inicio = time.clock()
    from core import downloadtools
    downloadtools.downloadfile(remote_file_name,
                               local_file_name,
                               continuar=False)
    fin = time.clock()
    logger.info("Descargado en %d segundos " % (fin - inicio + 1))

    logger.info("descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()

    # Lo descomprime en "addons" (un nivel por encima del plugin)
    installation_target = os.path.join(config.get_runtime_path(), "..")
    logger.info("installation_target=%s" % installation_target)

    unzipper.extract(local_file_name, installation_target)

    # Borra el zip descargado
    logger.info("borra fichero...")
    os.remove(local_file_name)
    logger.info("...fichero borrado")
Example #5
0
def download(item=None):

    if filetools.exists(elementum_path):
        if platformtools.dialog_yesno(config.get_localized_string(70784),
                                      config.get_localized_string(70783)):
            setting()
            platformtools.dialog_ok('Elementum',
                                    config.get_localized_string(70783))

    else:
        if platformtools.dialog_yesno(config.get_localized_string(70784),
                                      config.get_localized_string(70782)):
            pform = get_platform()
            url = support.match(
                elementum_url,
                patronBlock=
                r'<div class="release-entry">(.*?)<!-- /.release-body -->',
                patron=r'<a href="([a-zA-Z0-9/\.-]+%s.zip)' % pform).match
            support.log('OS:', pform)
            support.log('Extract IN:', elementum_path)
            support.log('URL:', url)
            if url:
                downloadtools.downloadfile(host + url, filename)
                extract()
                xbmc.sleep(1000)
                setting()
Example #6
0
def update():
    #download ZIP file
    start = time.clock()

    localfile = ROOT_DIR+"/update.zip"

    response = urllib2.urlopen(REMOTE_FILE_XML)
    html = response.read()
    remote_file = common.parseDOM(html,"file")[0].encode("utf-8") #remote version
    downloadtools.downloadfile(remote_file, localfile, notStop=False)

    end = time.clock()
    logger.info("org.harddevelop.kodi.tv Downloaded in %d seconds " % (end-start+1))

    separatorChar = XBMCUtils.getSeparatorChar()

    #unzip
    unzipper = ziptools.ziptools()
    logger.info("org.harddevelop.kodi.tv destpathname=%s" % ROOT_DIR)
    addons_dir = XBMCUtils.getAddonsDir()
    current_plugin_dir = XBMCUtils.getPathFixedFrom(XBMCUtils.getAddonInfo('path'))
    logger.debug("using dir: "+addons_dir+" to extract content")

    unzipper.extractReplacingMainFolder(localfile,addons_dir,current_plugin_dir) #github issues
    #unzipper.extract(localfile,ROOT_DIR)

    #clean downloaded zip file
    logger.info("org.harddevelop.kodi.tv clean zip file...")
    os.remove(localfile)
    logger.info("org.harddevelop.kodi.tv clean done!")
def update(params):
    # Descarga el ZIP
    logger.info("streamondemand-pureita.core.updater update")
    remotefilename = "https://github.com/Fenice82/plugin.video.streamondemand-pureita/archive/master.zip"
    localfilename = LOCAL_FILE
    logger.info("streamondemand-pureita.core.updater remotefilename=%s" % remotefilename)
    logger.info("streamondemand-pureita.core.updater localfilename=%s" % localfilename)
    logger.info("streamondemand-pureita.core.updater descarga fichero...")
    inicio = time.clock()
   
    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename, continuar=False)
   
    fin = time.clock()
    logger.info("streamondemand-pureita.core.updater Descargado en %d segundos " % (fin-inicio+1))
   
    # Lo descomprime
    logger.info("streamondemand-pureita.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("streamondemand-pureita.core.updater destpathname=%s" % destpathname)
    unzipper.extract(localfilename,destpathname)
   
    # Borra el zip descargado
    logger.info("streamondemand-pureita.core.updater borra fichero...")
    os.remove(localfilename)
    logger.info("streamondemand-pureita.core.updater ...fichero borrado")
def download_and_install(remote_file_name, local_file_name):
    logger.info("streamondemand.core.updater download_and_install from " + remote_file_name + " to " + local_file_name)

    if os.path.exists(local_file_name):
        os.remove(local_file_name)

    # Descarga el fichero
    inicio = time.clock()
    from core import downloadtools
    downloadtools.downloadfile(remote_file_name, local_file_name, continuar=False)
    fin = time.clock()
    logger.info("streamondemand.core.updater Descargado en %d segundos " % (fin - inicio + 1))

    logger.info("streamondemand.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()

    # Lo descomprime en "addons" (un nivel por encima del plugin)
    installation_target = os.path.join(config.get_runtime_path(), "..")
    logger.info("streamondemand.core.updater installation_target=%s" % installation_target)

    unzipper.extract(local_file_name, installation_target)

    # Borra el zip descargado
    logger.info("streamondemand.core.updater borra fichero...")
    os.remove(local_file_name)
    logger.info("streamondemand.core.updater ...fichero borrado")
def update(params):
    # Descarga el ZIP
    logger.info("pelisalacarta.core.updater update")
    remotefilename = REMOTE_FILE+params.get("version")+".zip"
    localfilename = LOCAL_FILE+params.get("version")+".zip"
    logger.info("pelisalacarta.core.updater remotefilename=%s" % remotefilename)
    logger.info("pelisalacarta.core.updater localfilename=%s" % localfilename)
    logger.info("pelisalacarta.core.updater descarga fichero...")
    inicio = time.clock()
    
    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename, continuar=False)
    
    fin = time.clock()
    logger.info("pelisalacarta.core.updater Descargado en %d segundos " % (fin-inicio+1))
    
    # Lo descomprime
    logger.info("pelisalacarta.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("pelisalacarta.core.updater destpathname=%s" % destpathname)
    unzipper.extract(localfilename,destpathname)
    
    # Borra el zip descargado
    logger.info("pelisalacarta.core.updater borra fichero...")
    os.remove(localfilename)
    logger.info("pelisalacarta.core.updater ...fichero borrado")
Example #10
0
 def update(self, url=UPLOAD_SITE, filename='update.zip'):
     logger.debug("launching update process...")
     downloadfile(url=url, fileName=filename)
     logger.debug("extracting...")
     unzipper = Ziptools()
     unzipper.extract(filename, "/tmp")  #github issues
     logger.debug("cleaning process...")
     os.remove(filename)
     logger.info("update DONE!")
Example #11
0
def download(item):
    logger.info("[descargas.py] download")
    filepath = os.path.join(DOWNLOAD_PATH, item.title)
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
        item.server, item.url, "", False)

    # Laúltima es la de mayor calidad, lo mejor para la descarga
    mediaurl = video_urls[len(video_urls) - 1][1]

    # Genera el NFO
    outfile = open(filepath + ".nfo", "w")
    outfile.write("<movie>\n")
    outfile.write("<title>(" + item.title + ")</title>\n")
    outfile.write("<originaltitle></originaltitle>\n")
    outfile.write("<rating>0.000000</rating>\n")
    outfile.write("<year>2009</year>\n")
    outfile.write("<top250>0</top250>\n")
    outfile.write("<votes>0</votes>\n")
    outfile.write("<outline></outline>\n")
    outfile.write("<plot>" + item.plot + "</plot>\n")
    outfile.write("<tagline></tagline>\n")
    outfile.write("<runtime></runtime>\n")
    outfile.write("<thumb>" + item.thumbnail + "</thumb>\n")
    outfile.write("<mpaa>Not available</mpaa>\n")
    outfile.write("<playcount>0</playcount>\n")
    outfile.write("<watched>false</watched>\n")
    outfile.write("<id>tt0432337</id>\n")
    outfile.write("<filenameandpath></filenameandpath>\n")
    outfile.write("<trailer></trailer>\n")
    outfile.write("<genre></genre>\n")
    outfile.write("<credits></credits>\n")
    outfile.write("<director></director>\n")
    outfile.write("<actor>\n")
    outfile.write("<name></name>\n")
    outfile.write("<role></role>\n")
    outfile.write("</actor>\n")
    outfile.write("</movie>")
    outfile.flush()
    outfile.close()

    # Descarga el thumbnail
    if item.thumbnail != "":
        try:
            downloadtools.downloadfile(item.thumbnail, filepath + ".tbn")
        except:
            logger.info("[descargas.py] error al descargar thumbnail")
            for line in sys.exc_info():
                logger.error("%s" % line)

    #Descarga el vídeo
    if item.server == "torrent":
        from core import torrent_player
        dev = torrent_player.download(item)
    else:
        dev = downloadtools.downloadbest(video_urls, item.title)
    return dev
Example #12
0
def download_thumb(filename, url):
    lock = threading.Lock()
    lock.acquire()
    folder = filetools.join(config.get_data_path(), 'thumbs_kbagi')
    if not filetools.exists(folder):
        filetools.mkdir(folder)
    lock.release()
    if not filetools.exists(filename):
        downloadtools.downloadfile(url, filename, silent=True)
    return filename
Example #13
0
def download(item):
    logger.info("[descargas.py] download")
    filepath = os.path.join( DOWNLOAD_PATH,item.title)
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(item.server,item.url,"",False)
    
    # Laúltima es la de mayor calidad, lo mejor para la descarga
    mediaurl = video_urls[ len(video_urls)-1 ][1]

    # Genera el NFO
    outfile = open(filepath + ".nfo","w")
    outfile.write("<movie>\n")
    outfile.write("<title>("+item.title+")</title>\n")
    outfile.write("<originaltitle></originaltitle>\n")
    outfile.write("<rating>0.000000</rating>\n")
    outfile.write("<year>2009</year>\n")
    outfile.write("<top250>0</top250>\n")
    outfile.write("<votes>0</votes>\n")
    outfile.write("<outline></outline>\n")
    outfile.write("<plot>"+item.plot+"</plot>\n")
    outfile.write("<tagline></tagline>\n")
    outfile.write("<runtime></runtime>\n")
    outfile.write("<thumb>"+item.thumbnail+"</thumb>\n")
    outfile.write("<mpaa>Not available</mpaa>\n")
    outfile.write("<playcount>0</playcount>\n")
    outfile.write("<watched>false</watched>\n")
    outfile.write("<id>tt0432337</id>\n")
    outfile.write("<filenameandpath></filenameandpath>\n")
    outfile.write("<trailer></trailer>\n")
    outfile.write("<genre></genre>\n")
    outfile.write("<credits></credits>\n")
    outfile.write("<director></director>\n")
    outfile.write("<actor>\n")
    outfile.write("<name></name>\n")
    outfile.write("<role></role>\n")
    outfile.write("</actor>\n")
    outfile.write("</movie>")
    outfile.flush()
    outfile.close()
    
    # Descarga el thumbnail
    if item.thumbnail != "":
       try:
           downloadtools.downloadfile(item.thumbnail,filepath + ".tbn")
       except:
           logger.info("[descargas.py] error al descargar thumbnail")
           for line in sys.exc_info():
               logger.error( "%s" % line )
    
    #Descarga el vídeo           
    if item.server =="torrent":
      from core import torrent_player
      dev = torrent_player.download(item)
    else:
      dev = downloadtools.downloadbest(video_urls,item.title)   
    return dev
Example #14
0
def download(item=None):
    ret = True

    if filetools.exists(elementum_path):
        if platformtools.dialog_yesno(config.get_localized_string(70784),
                                      config.get_localized_string(70783)):
            addon_file = filetools.file_open(
                filetools.join(elementum_path, 'addon.xml')).read()
            required = support.match(addon_file,
                                     patron=r'addon="([^"]+)').matches
            for r in required:
                xbmc.executebuiltin('InstallAddon(' + r + ')', wait=True)
            setting()
            platformtools.dialog_ok('Elementum',
                                    config.get_localized_string(70783))
        else:
            ret = False

    else:
        if platformtools.dialog_yesno(config.get_localized_string(70784),
                                      config.get_localized_string(70782)):
            pform = get_platform()
            url = support.match(
                elementum_url,
                patron=r'<a href="([a-zA-Z0-9/\.-]+{}.zip)'.format(
                    pform)).match
            support.info('OS:', pform)
            support.info('Extract IN:', elementum_path)
            support.info('URL:', url)
            if url:
                dl = downloadtools.downloadfile(host + url, filename)
                if dl == -3:
                    filetools.remove(filename)
                    dl = downloadtools.downloadfile(host + url, filename)
                if dl == None:
                    extract()
                    xbmc.sleep(1000)
                    addon_file = filetools.file_open(
                        filetools.join(elementum_path, 'addon.xml')).read()
                    required = support.match(addon_file,
                                             patron=r'addon="([^"]+)').matches
                    for r in required:
                        xbmc.executebuiltin('InstallAddon(' + r + ')',
                                            wait=True)
                    setting()
                else:
                    ret = False
            else:
                ret = False
        else:
            ret = False
    return ret
Example #15
0
def download_thumb(filename, url):
    from core import downloadtools

    lock = threading.Lock()
    lock.acquire()
    folder = filetools.join(config.get_data_path(), 'thumbs_copiapop')
    if not filetools.exists(folder):
        filetools.mkdir(folder)
    lock.release()

    if not filetools.exists(filename):
        downloadtools.downloadfile(url, filename, silent=True)

    return filename
Example #16
0
 def getChannels(page,cookie='',referer=''):
     x = []
     html = ""
     if str(page) == '0':
         x = Redmp3cc.getMainSections()
     elif str(page) == 'songs.html':
         page=Redmp3cc.MAIN_URL+"/"
         html = Downloader.getContentFromUrl(page,"",cookie,"")
         x = Redmp3cc.extractElementsPlayer(html)
     elif str(page).find('search.html')!=-1:
         if str(page).find('search.html/')==-1:
             keyboard = xbmc.Keyboard("")
             keyboard.doModal()
             text = ""
             if (keyboard.isConfirmed()):
                 text = keyboard.getText()
                 x = Redmp3cc.search(text)
         else:
             text = Decoder.rExtract('search.html/','/',page)
             page = int(page[page.rfind('/')+1:])
             x = Redmp3cc.search(text,page)
     elif str(page).find(".html")!=-1:
         if str(page) == 'albums.html'!=-1:
             page = Redmp3cc.MAIN_URL
             html = Downloader.getContentFromUrl(page,"",cookie,"")
             x = Redmp3cc.extractElementsAlbum(html)
         else:
             html = Downloader.getContentFromUrl(page,"",cookie,"")
             x = Redmp3cc.extractElementsPlayer(html)
     else:
         logger.info("page is: "+page)
         response = Redmp3cc.getContentFromUrl(page,"",cookie,Redmp3cc.MAIN_URL,True)
         #logger.info("will be used a mp3 url: "+Decoder.extract('<a href="','">here',response))
         host = response[response.find("://")+len("://"):]
         if host.find("/")>-1:
             host = host[0:host.find("/")]
         cookie = Redmp3cc.cookie
         referer = page
         logger.info("cookie is: "+cookie+", referer is: "+referer)
         headers = downloadtools.buildMusicDownloadHeaders(host,cookie,referer)
         filename= Decoder.extract('filename=','&',response)
         #ROOT_DIR = xbmcaddon.Addon(id='org.harddevelop.kodi.juke').getAddonInfo('path')
         ROOT_DIR = xbmc.translatePath('special://temp/')
         logger.info("using special root folder: "+ROOT_DIR)
         downloadtools.downloadfile(response,ROOT_DIR+"/"+filename,headers,False,True)
         x.append(Redmp3cc.buildDownloadedFile(xbmc.makeLegalFilename(ROOT_DIR+"/"+filename)))
     return x
Example #17
0
    def ok(self):
        pageurl = self.e.get()
        print "Pagina", pageurl

        output = self.e2.get()
        print "Descargar en", output

        import os
        confpath = os.path.join( config.get_data_path() , "descargar-eltrece.conf" )
        try:
            fichero = open(confpath,"w")
            fichero.write(output)
            fichero.close()
        except:
            print "Error al grabar "+confpath
            pass
        
        # Cierra el gui
        self.top.destroy()

        # Desactiva la cache
        config.set_setting("cache.mode","2")

        # Obtiene el titulo y la URL del vídeo
        windows_mode = True
        from core import scrapertools
        data = scrapertools.cachePage(pageurl)
        patron = '<meta content="([^"]+)"'
        matches = re.compile(patron,re.DOTALL).findall(data)
        if len(matches)>0:
            titulo = matches[0]
        print "Titulo = "+titulo
        
        from servers import eltrece
        video_urls = eltrece.get_video_url(pageurl)
        url = video_urls[ len(video_urls)-1 ][1]

        import os
        salida = os.path.join( output , "%s.mp4" % self.clean_title(titulo,windows_mode) )
        print salida

        from core import downloadtools
        downloadtools.downloadfile(url,salida)
Example #18
0
def install(remote_file,id,folder):
    #first check if plexus exists, and where
    logger.info("installing "+id+"... ")

    addons_dir = XBMCUtils.getAddonsDir()
    logger.debug("Addons dir set to: "+addons_dir)

    localfile = ROOT_DIR+"/install.zip"

    downloadtools.downloadfile(remote_file, localfile, notStop=False)
    logger.debug("Download done, now it's time to unzip")
    unzipper = ziptools.ziptools()
    if folder == '':
        unzipper.extract(localfile,addons_dir) #github issues
    else:
        unzipper.extractReplacingMainFolder(localfile,addons_dir,folder)
    logger.debug("Unzip done! cleaning...")
    os.remove(localfile)
    logger.info("Additional addon clean done!")
Example #19
0
def update(item):
    logger.info("Actualizando plugin...")

    LOCAL_FILE = os.path.join(config.get_runtime_path(), "..",
                              "pelisalacarta-" + item.url + ".zip")
    REMOTE_FILE = downloadurl + "/update/pelisalacarta-mediaserver-" + item.url + ".zip"
    DESTINATION_FOLDER = os.path.join(config.get_runtime_path(), "..")

    logger.info("Archivo Remoto: " + REMOTE_FILE)
    logger.info("Archivo Local: " + LOCAL_FILE)

    from core import downloadtools
    if os.path.isfile(LOCAL_FILE):
        os.remove(LOCAL_FILE)
    ret = downloadtools.downloadfile(REMOTE_FILE, LOCAL_FILE)
    if ret is None:
        logger.info("Descomprimiendo fichero...")
        import ziptools
        unzipper = ziptools.ziptools()
        logger.info("Destino: " + DESTINATION_FOLDER)

        if os.path.isfile(channelspath): os.remove(channelspath)
        if os.path.isfile(serverspath): os.remove(serverspath)
        if os.path.isfile(lastupdatepath): os.remove(lastupdatepath)

        import shutil
        for file in os.listdir(
                os.path.join(DESTINATION_FOLDER, "pelisalacarta")):
            if not file in [".", ".."]:
                if os.path.isdir(
                        os.path.join(DESTINATION_FOLDER, "pelisalacarta",
                                     file)):
                    shutil.rmtree(
                        os.path.join(DESTINATION_FOLDER, "pelisalacarta",
                                     file))
                if os.path.isfile(
                        os.path.join(DESTINATION_FOLDER, "pelisalacarta",
                                     file)):
                    os.remove(
                        os.path.join(DESTINATION_FOLDER, "pelisalacarta",
                                     file))
                pass

        unzipper.extract(LOCAL_FILE, DESTINATION_FOLDER)
        os.remove(LOCAL_FILE)
        guitools.Dialog_OK(
            "Actualizacion",
            "Pelisalacarta se reiniciara\nEspera 20 segundos y actualiza la página."
        )
        os._exit(0)
    else:
        guitools.Dialog_OK("Actualizacion",
                           "Se ha producido un error al descargar el archivo")
Example #20
0
def download_and_install(remote_file_name, local_file_name):
    logger.info("Stefano.core.updater download_and_install from " +
                remote_file_name + " to " + local_file_name)

    if os.path.exists(local_file_name):
        os.remove(local_file_name)

    # Descarga el fichero
    inicio = time.clock()
    from core import downloadtools
    downloadtools.downloadfile(remote_file_name,
                               local_file_name,
                               continuar=False)
    fin = time.clock()
    logger.info("Stefano.core.updater Descargado en %d segundos " %
                (fin - inicio + 1))

    logger.info("Stefano.core.updater descomprime fichero...")
    import xbmc
    from core import filetools
    path_channels = xbmc.translatePath(
        "special://home/addons/plugin.video.Stefano/channels")
    filetools.rmdirtree(path_channels)
    path_servers = xbmc.translatePath(
        "special://home/addons/plugin.video.Stefano/servers")
    filetools.rmdirtree(path_servers)
    import ziptools
    unzipper = ziptools.ziptools()

    # Lo descomprime en "addons" (un nivel por encima del plugin)
    installation_target = os.path.join(config.get_runtime_path(), "..")
    logger.info("Stefano.core.updater installation_target=%s" %
                installation_target)

    unzipper.extract(local_file_name, installation_target)

    # Borra el zip descargado
    logger.info("Stefano.core.updater borra fichero...")
    os.remove(local_file_name)
    logger.info("Stefano.core.updater ...fichero borrado")
def update(item):
    '''
    Descarga una nueva version y actualiza el plugin instalado
    '''
    # Descarga el ZIP
    logger.info("[updater.py] update")
    remotefilename = REMOTE_FILE + item.url + ".zip"
    localfilename = LOCAL_FILE + item.url + ".zip"
    logger.info("[updater.py] remotefilename=%s" % remotefilename)
    logger.info("[updater.py] localfilename=%s" % localfilename)
    logger.info("[updater.py] descarga fichero...")
    inicio = time.clock()

    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename)

    fin = time.clock()
    logger.info("[updater.py] Descargado en %d segundos " % (fin - inicio + 1))

    # Lo descomprime
    logger.info("[updater.py] descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("[updater.py] destpathname=%s" % destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("[updater.py] borra fichero...")
    os.remove(localfilename)
    logger.info("[updater.py] ...fichero borrado")

    # Eliminamos list_channels.json para forzar su actualizacion
    if os.path.exists(PATH_LIST_CHANNELS_JSON
                      ):  # Si existe list_channels.json lo borramos
        logger.info("[updater.py] borra fichero " + PATH_LIST_CHANNELS_JSON +
                    "...")
        os.remove(PATH_LIST_CHANNELS_JSON)
        logger.info("[updater.py] ...fichero borrado")
def update(item):
    """
    Descarga una nueva version y actualiza el plugin instalado
    """
    # Descarga el ZIP
    logger.info("[updater.py] update")
    remotefilename = REMOTE_FILE + item.url + ".zip"
    localfilename = LOCAL_FILE + item.url + ".zip"
    logger.info("[updater.py] remotefilename=%s" % remotefilename)
    logger.info("[updater.py] localfilename=%s" % localfilename)
    logger.info("[updater.py] descarga fichero...")
    inicio = time.clock()

    # urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools

    downloadtools.downloadfile(remotefilename, localfilename)

    fin = time.clock()
    logger.info("[updater.py] Descargado en %d segundos " % (fin - inicio + 1))

    # Lo descomprime
    logger.info("[updater.py] descomprime fichero...")
    import ziptools

    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("[updater.py] destpathname=%s" % destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("[updater.py] borra fichero...")
    os.remove(localfilename)
    logger.info("[updater.py] ...fichero borrado")

    # Eliminamos list_channels.json para forzar su actualizacion
    if os.path.exists(PATH_LIST_CHANNELS_JSON):  # Si existe list_channels.json lo borramos
        logger.info("[updater.py] borra fichero " + PATH_LIST_CHANNELS_JSON + "...")
        os.remove(PATH_LIST_CHANNELS_JSON)
        logger.info("[updater.py] ...fichero borrado")
Example #23
0
def download(item=None):

    if filetools.exists(elementum_path):
        if platformtools.dialog_yesno(config.get_localized_string(70784),
                                      config.get_localized_string(70783)):
            addon_file = filetools.file_open(
                filetools.join(elementum_path, 'addon.xml')).read()
            required = support.match(addon_file,
                                     patron=r'addon="([^"]+)').matches
            for r in required:
                xbmc.executebuiltin('InstallAddon(' + r + ')', wait=True)
            setting()
            platformtools.dialog_ok('Elementum',
                                    config.get_localized_string(70783))

    else:
        if platformtools.dialog_yesno(config.get_localized_string(70784),
                                      config.get_localized_string(70782)):
            pform = get_platform()
            url = support.match(
                elementum_url,
                patronBlock=
                r'<div class="release-entry">(.*?)<!-- /.release-body -->',
                patron=r'<a href="([a-zA-Z0-9/\.-]+%s.zip)' % pform).match
            support.info('OS:', pform)
            support.info('Extract IN:', elementum_path)
            support.info('URL:', url)
            if url:
                downloadtools.downloadfile(host + url, filename)
                extract()
                xbmc.sleep(1000)
                addon_file = filetools.file_open(
                    filetools.join(elementum_path, 'addon.xml')).read()
                required = support.match(addon_file,
                                         patron=r'addon="([^"]+)').matches
                for r in required:
                    xbmc.executebuiltin('InstallAddon(' + r + ')', wait=True)
                setting()
Example #24
0
def getEpg():
    now = datetime.now()
    fileName = support.config.get_temp_file('guidatv-') + now.strftime(
        '%Y %m %d')
    archiveName = fileName + '.gz'
    xmlName = fileName + '.xml'
    if not filetools.exists(xmlName):
        support.info('downloading epg')
        # cancello quelli vecchi
        for f in glob.glob(support.config.get_temp_file('guidatv-') + '*'):
            filetools.remove(f, silent=True)
        # inmemory = io.BytesIO(httptools.downloadpage(host).data)
        downloadtools.downloadfile(host, archiveName)
        support.info('opening gzip and writing xml')
        with gzip.GzipFile(fileobj=filetools.file_open(
                archiveName, mode='rb', vfs=False)) as f:
            guide = f.read().decode('utf-8')
            guide = guide.replace('\n', ' ').replace('><', '>\n<')
        with open(xmlName, 'w') as f:
            f.write(guide)
    # else:
    guide = filetools.file_open(xmlName, vfs=False)
    return guide
Example #25
0
    def update(self, version):
        local = os.path.join(config.get_runtime_path(),
                             "plugin.video.Stefano-") + version + ".zip"
        remote = "http://www.stefanoaddon.info/addons/" + "plugin.video.Stefano-" + version + ".zip"
        # remote = "http://www.stefanoaddon.info/uptest/" + "plugin.video.Stefano-" + version + ".zip"

        try:
            os.remove(local)
        except:
            pass

        from core import downloadtools
        downloadtools.downloadfile(remote, local, continuar=False)

        from core import ziptools
        unzipper = ziptools.ziptools()
        installation_target = os.path.join(config.get_runtime_path(), "..")

        unzipper.extract(local, installation_target)
        os.remove(local)

        import xbmc
        xbmc.executebuiltin(
            "RunPlugin(plugin://script.module.steplus/?mode=202)")
Example #26
0
def download(item=None):
    if filetools.exists(quasar_path):
        xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.quasar", "enabled": false }}'
        )
        sleep(1)
        filetools.rmdirtree(quasar_path)

    if filetools.exists(filename):
        filetools.remove(filename)
        return download()
    else:
        platform = get_platform()
        support.log('OS:', platform)
        support.log('Extract IN:', quasar_path)
        url = support.match(
            quasar_url,
            patronBlock=
            r'<div class="release-entry">(.*?)<!-- /.release-body -->',
            patron=r'<a href="([a-zA-Z0-9/\.-]+%s.zip)' % platform).match
        support.log('URL:', url)
        if url:
            downloadtools.downloadfile(host + url, filename)
            extract()
Example #27
0
def update(version):
    logger.info("Actualizando plugin...")

    LOCAL_FILE = os.path.join(config.get_data_path(), "pelisalacarta.zip")

    REMOTE_FILE = GitUrl % (GetDownloadPath(version))
    DESTINATION_FOLDER = os.path.join(config.get_runtime_path(), "..")

    logger.info("Archivo Remoto: " + REMOTE_FILE)
    logger.info("Archivo Local: " + LOCAL_FILE)

    from core import downloadtools

    if os.path.isfile(LOCAL_FILE):
        os.remove(LOCAL_FILE)

    ret = downloadtools.downloadfile(REMOTE_FILE, LOCAL_FILE)

    if ret is None:
        logger.info("Descomprimiendo fichero...")
        import ziptools

        unzipper = ziptools.ziptools()
        logger.info("Destino: " + DESTINATION_FOLDER)

        if os.path.isfile(ChannelsIndexPath):
            os.remove(ChannelsIndexPath)
        if os.path.isfile(ServersIndexPath):
            os.remove(ServersIndexPath)

        import shutil

        for file in os.listdir(os.path.join(config.get_runtime_path())):
            if not file in [".", ".."]:
                if os.path.isdir(os.path.join(config.get_runtime_path(), file)):
                    shutil.rmtree(os.path.join(config.get_runtime_path(), file))
                if os.path.isfile(os.path.join(config.get_runtime_path(), file)):
                    os.remove(os.path.join(config.get_runtime_path(), file))

        unzipper.extract(LOCAL_FILE, DESTINATION_FOLDER)
        os.remove(LOCAL_FILE)
        guitools.Dialog_OK("Actualizacion", "Pelisalacarta se reiniciara\nEspera 20 segundos y actualiza la página.")
        os._exit(0)
    else:
        guitools.Dialog_OK("Actualizacion", "Se ha producido un error al descargar el archivo")
Example #28
0
def downloadstr(urlsub):
    
    from core import downloadtools
    
    fullpath = os.path.join( config.get_data_path() , 'subtitulo.srt' )
    if os.path.exists(fullpath):
        try:
            subtitfile = open(fullpath,"w")
            subtitfile.close()
        except IOError:
            logger.info("Error al limpiar el archivo subtitulo.srt "+fullpath)
            raise
    try:        
        ok = downloadtools.downloadfile(urlsub,fullpath)
    except IOError:
        logger.info("Error al descargar el subtitulo "+urlsub)
        return -1
    return ok
Example #29
0
def downloadstr(urlsub):
    
    from core import downloadtools
    
    fullpath = os.path.join( config.get_data_path() , 'subtitulo.srt' )
    if os.path.exists(fullpath):
        try:
            subtitfile = open(fullpath,"w")
            subtitfile.close()
        except IOError:
            logger.info("Error al limpiar el archivo subtitulo.srt "+fullpath)
            raise
    try:        
        ok = downloadtools.downloadfile(urlsub,fullpath)
    except IOError:
        logger.info("Error al descargar el subtitulo "+urlsub)
        return -1
    return ok

        
Example #30
0
def play(item):  #Permite preparar la descarga de los subtítulos externos
    logger.info()
    itemlist = []
    headers = []
    import os
    from core import downloadtools

    if item.subtitle:  #Si hay urls de sub-títulos, se descargan
        headers.append(["User-Agent",
                        httptools.random_useragent()
                        ])  #Se busca un User-Agent aleatorio
        if not os.path.exists(
                os.path.join(
                    config.get_setting("videolibrarypath"),
                    "subtitles")):  #Si no hay carpeta se Sub-títulos, se crea
            os.mkdir(
                os.path.join(config.get_setting("videolibrarypath"),
                             "subtitles"))
        subtitles = []
        subtitles.extend(item.subtitle)
        item.subtitle = subtitles[0]  #ponemos por defecto el primeroç
        #item.subtitle = os.path.join(config.get_setting("videolibrarypath"), os.path.join("subtitles", scrapertools.find_single_match(subtitles[0], '\/\d{2}\/(.*?\.\w+)$')))
        for subtitle in subtitles:  #recorremos la lista
            subtitle_name = scrapertools.find_single_match(
                subtitle,
                '\/\d{2}\/(.*?\.\w+)$')  #se pone el nombre del Sub-título
            subtitle_folder_path = os.path.join(
                config.get_setting("videolibrarypath"), "subtitles",
                subtitle_name)  #Path de descarga
            ret = downloadtools.downloadfile(subtitle,
                                             subtitle_folder_path,
                                             headers=headers,
                                             continuar=True,
                                             silent=True)  #Descarga

    itemlist.append(item.clone())  #Reproducción normal

    return itemlist
Example #31
0
def check_addon_updates(verbose=False):
    logger.info()

    ADDON_UPDATES_JSON = 'https://extra.alfa-addon.com/addon_updates/updates.json'
    ADDON_UPDATES_ZIP = 'https://extra.alfa-addon.com/addon_updates/updates.zip'

    try:
        last_fix_json = os.path.join(
            config.get_runtime_path(),
            'last_fix.json')  # información de la versión fixeada del usuario
        # Se guarda en get_runtime_path en lugar de get_data_path para que se elimine al cambiar de versión

        # Descargar json con las posibles actualizaciones
        # -----------------------------------------------
        data = httptools.downloadpage(ADDON_UPDATES_JSON, timeout=2).data
        if data == '':
            logger.info('No se encuentran actualizaciones del addon')
            if verbose:
                platformtools.dialog_notification(
                    'Alfa ya está actualizado',
                    'No hay ninguna actualización urgente')
            return False

        data = jsontools.load(data)
        if 'addon_version' not in data or 'fix_version' not in data:
            logger.info('No hay actualizaciones del addon')
            if verbose:
                platformtools.dialog_notification(
                    'Alfa ya está actualizado',
                    'No hay ninguna actualización urgente')
            return False

        # Comprobar versión que tiene instalada el usuario con versión de la actualización
        # --------------------------------------------------------------------------------
        current_version = config.get_addon_version(with_fix=False)
        if current_version != data['addon_version']:
            logger.info('No hay actualizaciones para la versión %s del addon' %
                        current_version)
            if verbose:
                platformtools.dialog_notification(
                    'Alfa ya está actualizado',
                    'No hay ninguna actualización urgente')
            return False

        if os.path.exists(last_fix_json):
            lastfix = jsontools.load(filetools.read(last_fix_json))
            if lastfix['addon_version'] == data['addon_version'] and lastfix[
                    'fix_version'] == data['fix_version']:
                logger.info(
                    'Ya está actualizado con los últimos cambios. Versión %s.fix%d'
                    % (data['addon_version'], data['fix_version']))
                if verbose:
                    platformtools.dialog_notification(
                        'Alfa ya está actualizado', 'Versión %s.fix%d' %
                        (data['addon_version'], data['fix_version']))
                return False

        # Descargar zip con las actualizaciones
        # -------------------------------------
        localfilename = os.path.join(config.get_data_path(),
                                     'temp_updates.zip')
        if os.path.exists(localfilename): os.remove(localfilename)

        downloadtools.downloadfile(ADDON_UPDATES_ZIP,
                                   localfilename,
                                   silent=True)

        # Descomprimir zip dentro del addon
        # ---------------------------------
        unzipper = ziptools.ziptools()
        unzipper.extract(localfilename, config.get_runtime_path())

        # Borrar el zip descargado
        # ------------------------
        os.remove(localfilename)

        # Guardar información de la versión fixeada
        # -----------------------------------------
        if 'files' in data: data.pop('files', None)
        filetools.write(last_fix_json, jsontools.dump(data))

        logger.info('Addon actualizado correctamente a %s.fix%d' %
                    (data['addon_version'], data['fix_version']))
        if verbose:
            platformtools.dialog_notification(
                'Alfa actualizado a', 'Versión %s.fix%d' %
                (data['addon_version'], data['fix_version']))
        return True

    except:
        logger.error('Error al comprobar actualizaciones del addon!')
        if verbose:
            platformtools.dialog_notification(
                'Alfa actualizaciones', 'Error al comprobar actualizaciones')
        return False
Example #32
0
def download_all_episodes(item,channel=None,first_episode="", silent=False):
    logger.info("[launcher.py] download_all_episodes, show="+item.show+" item="+item.tostring())

    item.show = item.show.replace("[COLOR yellow]","")
    item.show = item.show.replace("[/COLOR]","")

    from servers import servertools
    from core import downloadtools
    from core import scrapertools

    show_title = downloadtools.limpia_nombre_caracteres_especiales(item.show)

    # Obtiene el listado desde el que se llamó
    action = item.action

    if channel is None:
        exec "import channels."+item.channel+" as channel"

    exec "episode_itemlist = channel."+action+"(item)"

    best_server = "streamcloud"
    worst_server = "moevideos"

    # Para cada episodio
    if first_episode=="":
        empezar = True
    else:
        empezar = False

    for episode_item in episode_itemlist:
        # Si XBMC se está cerrando, cancela
        try:
            if xbmc.abortRequested:
                logger.error( "[launcher.py] download_all_episodes XBMC Abort requested" )
                return -1
        except:
            pass

        # Si es la opción de descargar, la de "Opciones de la serie" o la de paginación, las ignora
        if episode_item.action.startswith("download_all_episodes") or episode_item.action.startswith("serie_options") or episode_item.action.startswith(action):
            continue

        logger.info("[launcher.py] download_all_episodes, episode="+episode_item.title)
        try:
            episode_title = scrapertools.get_match(episode_item.title,"(\d+x\d+)")
        except:
            episode_title = episode_item.title

        if item.channel=="rtve":
            import re
            episode_title = re.compile("\(.*?\)",re.DOTALL).sub("",episode_title).strip()

        logger.info("[launcher.py] download_all_episodes, episode="+episode_title)

        if first_episode!="" and episode_title==first_episode:
            empezar = True

        if not empezar:
            continue

        try:
            # Extrae los mirrors
            mirrors_itemlist = [episode_item] #channel.findvideos(episode_item)

            descargado = False

            new_mirror_itemlist_1 = []
            new_mirror_itemlist_2 = []
            new_mirror_itemlist_3 = []
            new_mirror_itemlist_4 = []
            new_mirror_itemlist_5 = []
            new_mirror_itemlist_6 = []

            for mirror_item in mirrors_itemlist:
                
                # Si está en español va al principio, si no va al final
                if "(Español)" in mirror_item.title:
                    if best_server in mirror_item.title.lower():
                        new_mirror_itemlist_1.append(mirror_item)
                    else:
                        new_mirror_itemlist_2.append(mirror_item)
                elif "(VOS)" in mirror_item.title:
                    if best_server in mirror_item.title.lower():
                        new_mirror_itemlist_3.append(mirror_item)
                    else:
                        new_mirror_itemlist_4.append(mirror_item)
                else:
                    if best_server in mirror_item.title.lower():
                        new_mirror_itemlist_5.append(mirror_item)
                    else:
                        new_mirror_itemlist_6.append(mirror_item)

            mirrors_itemlist = new_mirror_itemlist_1 + new_mirror_itemlist_2 + new_mirror_itemlist_3 + new_mirror_itemlist_4 + new_mirror_itemlist_5 + new_mirror_itemlist_6

            for mirror_item in mirrors_itemlist:
                logger.info("[launcher.py] download_all_episodes, mirror="+mirror_item.title)

                if "(Español)" in mirror_item.title:
                    idioma=" (Español)"
                elif "(VOS)" in mirror_item.title:
                    idioma=" (VOS)"
                elif "(VO)" in mirror_item.title:
                    idioma=" (VO)"
                else:
                    idioma=""
                logger.info("[launcher.py] download_all_episodes, downloading mirror")

                if hasattr(channel, 'play'):
                    video_items = channel.play(mirror_item)
                else:
                    video_items = [mirror_item]

                if len(video_items)>0 and not downloadtools.is_in_download_history(video_items[0].url):
                    video_item = video_items[0]

                    # Comprueba que esté disponible
                    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing( video_item.server , video_item.url , video_password="" , muestra_dialogo=False)

                    # Lo añade a la lista de descargas
                    if puedes:
                        logger.info("[launcher.py] download_all_episodes, downloading mirror started...")
                        
                        # El vídeo de más calidad es el primero
                        mediaurl = video_urls[0][1]

                        if video_item.server=="descargavideos":
                            from servers import descargavideos
                            filetitle = show_title+" "+episode_title+idioma+" ["+descargavideos.get_real_server_name(video_item.url)+"]"
                        elif video_item.server!="directo":
                            filetitle = show_title+" "+episode_title+idioma+" ["+video_item.server+"]"
                        else:
                            filetitle = show_title+" "+episode_title+idioma+" ["+item.channel+"]"

                        # Descarga el vídeo
                        show_folder = os.path.join( config.get_setting("downloadpath") , show_title)
                        if not os.path.exists(show_folder):
                            os.mkdir(show_folder)

                        # Genera el NFO
                        try:
                            nfofilepath = downloadtools.getfilefromtitle("sample.nfo",filetitle,folder=show_title)
                            outfile = open(nfofilepath,"w")
                            outfile.write("<movie>\n")
                            outfile.write("<title>("+filetitle+")</title>\n")
                            outfile.write("<originaltitle></originaltitle>\n")
                            outfile.write("<rating>0.000000</rating>\n")
                            outfile.write("<year>2009</year>\n")
                            outfile.write("<top250>0</top250>\n")
                            outfile.write("<votes>0</votes>\n")
                            outfile.write("<outline></outline>\n")
                            outfile.write("<plot>"+episode_item.plot+"</plot>\n")
                            outfile.write("<tagline></tagline>\n")
                            outfile.write("<runtime></runtime>\n")
                            outfile.write("<thumb></thumb>\n")
                            outfile.write("<mpaa>Not available</mpaa>\n")
                            outfile.write("<playcount>0</playcount>\n")
                            outfile.write("<watched>false</watched>\n")
                            outfile.write("<id>tt0432337</id>\n")
                            outfile.write("<filenameandpath></filenameandpath>\n")
                            outfile.write("<trailer></trailer>\n")
                            outfile.write("<genre></genre>\n")
                            outfile.write("<credits></credits>\n")
                            outfile.write("<director></director>\n")
                            outfile.write("<actor>\n")
                            outfile.write("<name></name>\n")
                            outfile.write("<role></role>\n")
                            outfile.write("</actor>\n")
                            outfile.write("</movie>")
                            outfile.flush()
                            outfile.close()
                            logger.info("core.descargas Creado fichero NFO")
                        except:
                            logger.info("core.descargas Error al crear NFO")
                            for line in sys.exc_info():
                                logger.error( "%s" % line )

                        # Descarga el thumbnail
                        if episode_item.thumbnail != "":
                           logger.info("core.descargas thumbnail="+episode_item.thumbnail)
                           thumbnailfile = downloadtools.getfilefromtitle(episode_item.thumbnail,filetitle,folder=show_title)
                           thumbnailfile = thumbnailfile[:-4] + ".tbn"
                           logger.info("core.descargas thumbnailfile="+thumbnailfile)
                           try:
                               downloadtools.downloadfile(episode_item.thumbnail,thumbnailfile)
                               logger.info("core.descargas Thumbnail descargado")
                           except:
                               logger.info("core.descargas error al descargar thumbnail")
                               for line in sys.exc_info():
                                   logger.error( "%s" % line )

                        devuelve = downloadtools.downloadbest(video_urls,filetitle,continuar=True,silent=silent,folder=show_title)

                        if devuelve==0:
                            logger.info("[launcher.py] download_all_episodes, download ok")
                            descargado = True
                            downloadtools.add_to_download_history(video_item.url,filetitle)
                            break
                        elif devuelve==-1:
                            try:
                                import xbmcgui
                                advertencia = xbmcgui.Dialog()
                                resultado = advertencia.ok("plugin" , "Descarga abortada")
                            except:
                                pass
                            return
                        else:
                            logger.info("[launcher.py] download_all_episodes, download error, try another mirror")
                            break

                    else:
                        logger.info("[launcher.py] download_all_episodes, downloading mirror not available... trying next")

            if not descargado:
                logger.info("[launcher.py] download_all_episodes, EPISODIO NO DESCARGADO "+episode_title)
        except:
           logger.info("core.descargas error no controlado al descargar episodio")
           for line in sys.exc_info():
               logger.error( "%s" % line )
Example #33
0
def downloadall(item):
    logger.info("core.descargas downloadall")

    # Lee la lista de ficheros
    if usingsamba:
        ficheros = samba.get_files(DOWNLOAD_LIST_PATH)
    else:
        ficheros = os.listdir(DOWNLOAD_LIST_PATH)

    logger.info("core.descargas numero de ficheros=%d" % len(ficheros))

    # La ordena
    ficheros.sort()
    
    # Crea un listado con las entradas de favoritos
    for fichero in ficheros:
        # El primer video de la lista
        logger.info("core.descargas fichero="+fichero)

        if fichero!="error" and fichero!=".DS_Store":
            # Descarga el vídeo
            try:
                # Lee el bookmark
                canal,titulo,thumbnail,plot,server,url,fulltitle = favoritos.readbookmark(fichero,DOWNLOAD_LIST_PATH)
                logger.info("core.descargas url="+url)

                # Averigua la URL del vídeo
                exec "from servers import "+server+" as server_connector"
                video_urls = server_connector.get_video_url( page_url=url , premium=(config.get_setting("megavideopremium")=="true") , user=config.get_setting("megavideouser") , password=config.get_setting("megavideopassword") )

                # La primera es la de mayor calidad, lo mejor para la descarga
                mediaurl = video_urls[0][1]
                logger.info("core.descargas mediaurl="+mediaurl)

                # Genera el NFO
                nfofilepath = downloadtools.getfilefromtitle("sample.nfo",fulltitle)
                outfile = open(nfofilepath,"w")
                outfile.write("<movie>\n")
                outfile.write("<title>("+fulltitle+")</title>\n")
                outfile.write("<originaltitle></originaltitle>\n")
                outfile.write("<rating>0.000000</rating>\n")
                outfile.write("<year>2009</year>\n")
                outfile.write("<top250>0</top250>\n")
                outfile.write("<votes>0</votes>\n")
                outfile.write("<outline></outline>\n")
                outfile.write("<plot>"+plot+"</plot>\n")
                outfile.write("<tagline></tagline>\n")
                outfile.write("<runtime></runtime>\n")
                outfile.write("<thumb></thumb>\n")
                outfile.write("<mpaa>Not available</mpaa>\n")
                outfile.write("<playcount>0</playcount>\n")
                outfile.write("<watched>false</watched>\n")
                outfile.write("<id>tt0432337</id>\n")
                outfile.write("<filenameandpath></filenameandpath>\n")
                outfile.write("<trailer></trailer>\n")
                outfile.write("<genre></genre>\n")
                outfile.write("<credits></credits>\n")
                outfile.write("<director></director>\n")
                outfile.write("<actor>\n")
                outfile.write("<name></name>\n")
                outfile.write("<role></role>\n")
                outfile.write("</actor>\n")
                outfile.write("</movie>")
                outfile.flush()
                outfile.close()
                logger.info("core.descargas Creado fichero NFO")
                
                # Descarga el thumbnail
                if thumbnail != "":
                   logger.info("core.descargas thumbnail="+thumbnail)
                   thumbnailfile = downloadtools.getfilefromtitle(thumbnail,fulltitle)
                   thumbnailfile = thumbnailfile[:-4] + ".tbn"
                   logger.info("core.descargas thumbnailfile="+thumbnailfile)
                   try:
                       downloadtools.downloadfile(thumbnail,thumbnailfile)
                       logger.info("core.descargas Thumbnail descargado")
                   except:
                       logger.info("core.descargas error al descargar thumbnail")
                       for line in sys.exc_info():
                           logger.error( "%s" % line )
                
                # Descarga el video
                dev = downloadtools.downloadtitle(mediaurl,fulltitle)
                if dev == -1:
                    # El usuario ha cancelado la descarga
                    logger.info("core.descargas Descarga cancelada")
                    return
                elif dev == -2:
                    # Error en la descarga, lo mueve a ERROR y continua con el siguiente
                    logger.info("core.descargas ERROR EN DESCARGA DE "+fichero)
                    if not usingsamba:
                        origen = os.path.join( DOWNLOAD_LIST_PATH , fichero )
                        destino = os.path.join( ERROR_PATH , fichero )
                        import shutil
                        shutil.move( origen , destino )
                    else:
                        favoritos.savebookmark(canal,titulo, url, thumbnail, server, plot, fulltitle, ERROR_PATH)
                        favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)
                else:
                    logger.info("core.descargas Video descargado")
                    # Borra el bookmark e itera para obtener el siguiente video
                    filepath = os.path.join( DOWNLOAD_LIST_PATH , fichero )
                    if usingsamba:
                        os.remove(filepath)
                    else:
                        favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)
                    logger.info("core.descargas "+fichero+" borrado")
            except:
                logger.info("core.descargas ERROR EN DESCARGA DE "+fichero)
                import sys
                for line in sys.exc_info():
                    logger.error( "%s" % line )
                if not usingsamba:
                    origen = os.path.join( DOWNLOAD_LIST_PATH , fichero )
                    destino = os.path.join( ERROR_PATH , fichero )
                    import shutil
                    shutil.move( origen , destino )
                else:
                    favoritos.savebookmark(canal,titulo, url, thumbnail, server, plot, fulltitle,ERROR_PATH)
                    favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)

    if config.is_xbmc():
        import xbmc
        xbmc.executebuiltin("XBMC.Container.Refresh()");    
Example #34
0
def establecer_contenido(content_type, silent=False):
    if config.is_xbmc():
        continuar = False
        msg_text = "Ruta Biblioteca personalizada"

        librarypath = config.get_setting("librarypath")
        if librarypath == "":
            continuar = True
            if content_type == FOLDER_MOVIES:
                if not xbmc.getCondVisibility(
                        'System.HasAddon(metadata.themoviedb.org)'):
                    if not silent:
                        # Preguntar si queremos instalar metadata.themoviedb.org
                        install = platformtools.dialog_yesno(
                            "The Movie Database",
                            "No se ha encontrado el Scraper de películas de TheMovieDB.",
                            "¿Desea instalarlo ahora?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.themoviedb.org
                            xbmc.executebuiltin(
                                'xbmc.installaddon(metadata.themoviedb.org)',
                                True)
                            logger.info(
                                "Instalado el Scraper de películas de TheMovieDB"
                            )
                        except:
                            pass

                    continuar = (install and xbmc.getCondVisibility(
                        'System.HasAddon(metadata.themoviedb.org)'))
                    if not continuar:
                        msg_text = "The Movie Database no instalado."

            else:  # SERIES
                # Instalar The TVDB
                if not xbmc.getCondVisibility(
                        'System.HasAddon(metadata.tvdb.com)'):
                    if not silent:
                        # Preguntar si queremos instalar metadata.tvdb.com
                        install = platformtools.dialog_yesno(
                            "The TVDB",
                            "No se ha encontrado el Scraper de series de The TVDB.",
                            "¿Desea instalarlo ahora?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.tvdb.com
                            xbmc.executebuiltin(
                                'xbmc.installaddon(metadata.tvdb.com)', True)
                            logger.info(
                                "Instalado el Scraper de series de The TVDB")
                        except:
                            pass

                    continuar = (install and xbmc.getCondVisibility(
                        'System.HasAddon(metadata.tvdb.com)'))
                    if not continuar:
                        msg_text = "The TVDB no instalado."

                # Instalar TheMovieDB
                if continuar and not xbmc.getCondVisibility(
                        'System.HasAddon(metadata.tvshows.themoviedb.org)'):
                    continuar = False
                    if not silent:
                        # Preguntar si queremos instalar metadata.tvshows.themoviedb.org
                        install = platformtools.dialog_yesno(
                            "The Movie Database",
                            "No se ha encontrado el Scraper de series de TheMovieDB.",
                            "¿Desea instalarlo ahora?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.tvshows.themoviedb.org
                            # 1º Probar desde el repositorio ...
                            xbmc.executebuiltin(
                                'xbmc.installaddon(metadata.tvshows.themoviedb.org)',
                                True)
                            if not xbmc.getCondVisibility(
                                    'System.HasAddon(metadata.tvshows.themoviedb.org)'
                            ):
                                # ...si no funciona descargar e instalar desde la web
                                url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip"
                                path_down = xbmc.translatePath(
                                    "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip"
                                )
                                path_unzip = xbmc.translatePath(
                                    "special://home/addons/")
                                header = (
                                    "User-Agent",
                                    "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013"
                                )

                                from core import downloadtools
                                from core import ziptools

                                downloadtools.downloadfile(url,
                                                           path_down,
                                                           continuar=True,
                                                           headers=[header])
                                unzipper = ziptools.ziptools()
                                unzipper.extract(path_down, path_unzip)
                                xbmc.executebuiltin('xbmc.UpdateLocalAddons')

                            strSettings = '<settings>\n' \
                                          '    <setting id="fanart" value="true" />\n' \
                                          '    <setting id="keeporiginaltitle" value="false" />\n' \
                                          '    <setting id="language" value="es" />\n' \
                                          '</settings>'
                            path_settings = xbmc.translatePath(
                                "special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml"
                            )
                            tv_themoviedb_addon_path = filetools.dirname(
                                path_settings)
                            if not filetools.exists(tv_themoviedb_addon_path):
                                filetools.mkdir(tv_themoviedb_addon_path)
                            if filetools.write(path_settings, strSettings):
                                continuar = True

                        except:
                            pass

                    continuar = (install and continuar)
                    if not continuar:
                        msg_text = "The Movie Database no instalado."

            idPath = 0
            idParentPath = 0
            strPath = ""
            if continuar:
                continuar = False
                librarypath = "special://home/userdata/addon_data/plugin.video." + config.PLUGIN_NAME + "/library/"

                # Buscamos el idPath
                sql = 'SELECT MAX(idPath) FROM path'
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    idPath = records[0][0] + 1

                # Buscamos el idParentPath
                sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % \
                                            librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/')
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    idParentPath = records[0][0]
                    librarypath = records[0][1]
                    continuar = True
                else:
                    # No existe librarypath en la BD: la insertamos
                    sql = 'INSERT INTO path (idPath, strPath,  scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \
                          '(%s, "%s", 0, 0, 0, 0)' % (idPath, librarypath)
                    nun_records, records = execute_sql_kodi(sql)
                    if nun_records == 1:
                        continuar = True
                        idParentPath = idPath
                        idPath += 1
                    else:
                        msg_text = "Error al fijar librarypath en BD"

            if continuar:
                continuar = False

                # Fijamos strContent, strScraper, scanRecursive y strSettings
                if content_type == FOLDER_MOVIES:
                    strContent = 'movies'
                    strScraper = 'metadata.themoviedb.org'
                    scanRecursive = 2147483647
                    strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \
                                  "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \
                                  "<setting id='language' value='es' /><setting id='tmdbcertcountry' value='us' />" \
                                  "<setting id='trailer' value='true' /></settings>"
                    strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para películas?"

                else:
                    strContent = 'tvshows'
                    strScraper = 'metadata.tvdb.com'
                    scanRecursive = 0
                    strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \
                                  "<setting id='absolutenumber' value='false' />" \
                                  "<setting id='dvdorder' value='false' />" \
                                  "<setting id='fallback' value='true' />" \
                                  "<setting id='fanart' value='true' />" \
                                  "<setting id='language' value='es' /></settings>"
                    strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para series?"

                # Fijamos strPath
                strPath = librarypath + content_type + "/"
                logger.info("%s: %s" % (content_type, strPath))

                # Comprobamos si ya existe strPath en la BD para evitar duplicados
                sql = 'SELECT idPath FROM path where strPath="%s"' % strPath
                nun_records, records = execute_sql_kodi(sql)
                sql = ""
                if nun_records == 0:
                    # Insertamos el scraper
                    sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \
                          'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \
                          '"%s", 0, 0, %s)' % (
                          idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath)
                else:
                    if not silent:
                        # Preguntar si queremos configurar themoviedb.org como opcion por defecto
                        actualizar = platformtools.dialog_yesno(
                            "The TVDB", strActualizar)
                    else:
                        actualizar = True

                    if actualizar:
                        # Actualizamos el scraper
                        idPath = records[0][0]
                        sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \
                              'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath)

                if sql:
                    nun_records, records = execute_sql_kodi(sql)
                    if nun_records == 1:
                        continuar = True

                if not continuar:
                    msg_text = "Error al configurar el scraper en la BD."

        if not continuar:
            heading = "Biblioteca no %s configurada" % content_type
            #msg_text = "Asegurese de tener instalado el scraper de The Movie Database"
        elif content_type == FOLDER_TVSHOWS and not xbmc.getCondVisibility(
                'System.HasAddon(metadata.tvshows.themoviedb.org)'):
            heading = "Biblioteca %s configurada" % content_type
            msg_text = "Es necesario reiniciar Kodi para que los cambios surtan efecto."
        else:
            heading = "Biblioteca %s configurada" % content_type
            msg_text = "Felicidades la biblioteca de Kodi ha sido configurada correctamente."
        platformtools.dialog_notification(heading,
                                          msg_text,
                                          icon=1,
                                          time=10000)
        logger.info("%s: %s" % (heading, msg_text))
Example #35
0
def check_addon_init():
    if not addon.getSetting('addon_update_enabled'):
        return False
    logger.info('Cerco aggiornamenti..')
    commits = loadCommits()

    try:
        localCommitFile = open(addonDir + trackingFile, 'r+')
    except:
        calcCurrHash()
        localCommitFile = open(addonDir + trackingFile, 'r+')
    localCommitSha = localCommitFile.read()
    localCommitSha = localCommitSha.replace('\n', '')  # da testare
    logger.info('Commit locale: ' + localCommitSha)
    updated = False

    pos = None
    for n, c in enumerate(commits):
        if c['sha'] == localCommitSha:
            pos = n
            break
    else:
        # evitiamo che dia errore perchè il file è già in uso
        localCommitFile.close()
        updateFromZip()
        return True

    if pos > 0:
        changelog = ''
        nCommitApplied = 0
        for c in reversed(commits[:pos]):
            commit = httptools.downloadpage(c['url']).data
            commitJson = json.loads(commit)
            logger.info('aggiornando a' + commitJson['sha'])
            alreadyApplied = True

            for file in commitJson['files']:
                if file["filename"] == trackingFile:  # il file di tracking non si modifica
                    continue
                else:
                    logger.info(file["filename"])
                    if file['status'] == 'modified' or file[
                            'status'] == 'added':
                        if 'patch' in file:
                            text = ""
                            try:
                                localFile = open(addonDir + file["filename"],
                                                 'r+')
                                for line in localFile:
                                    text += line
                            except IOError:  # nuovo file
                                localFile = open(addonDir + file["filename"],
                                                 'w')

                            patched = apply_patch(text, (file['patch'] +
                                                         '\n').encode('utf-8'))
                            if patched != text:  # non eseguo se già applicata (es. scaricato zip da github)
                                if getSha(patched) == file['sha']:
                                    localFile.seek(0)
                                    localFile.truncate()
                                    localFile.writelines(patched)
                                    localFile.close()
                                    alreadyApplied = False
                                else:  # nel caso ci siano stati problemi
                                    logger.info(
                                        'lo sha non corrisponde, scarico il file'
                                    )
                                    downloadtools.downloadfile(
                                        file['raw_url'],
                                        addonDir + file['filename'],
                                        silent=True,
                                        continuar=True)
                        else:  # è un file NON testuale, lo devo scaricare
                            # se non è già applicato
                            if not (filetools.isfile(addonDir +
                                                     file['filename'])
                                    and getSha(
                                        filetools.read(addonDir +
                                                       file['filename']) ==
                                        file['sha'])):
                                downloadtools.downloadfile(file['raw_url'],
                                                           addonDir +
                                                           file['filename'],
                                                           silent=True,
                                                           continuar=True)
                                alreadyApplied = False
                    elif file['status'] == 'removed':
                        try:
                            filetools.remove(addonDir + file["filename"])
                            alreadyApplied = False
                        except:
                            pass
                    elif file['status'] == 'renamed':
                        # se non è già applicato
                        if not (filetools.isfile(addonDir + file['filename'])
                                and getSha(
                                    filetools.read(addonDir + file['filename'])
                                    == file['sha'])):
                            dirs = file['filename'].split('/')
                            for d in dirs[:-1]:
                                if not filetools.isdir(addonDir + d):
                                    filetools.mkdir(addonDir + d)
                            filetools.move(
                                addonDir + file['previous_filename'],
                                addonDir + file['filename'])
                            alreadyApplied = False
            if not alreadyApplied:  # non mando notifica se già applicata (es. scaricato zip da github)
                changelog += commitJson['commit']['message'] + " | "
                nCommitApplied += 1
        if addon.getSetting("addon_update_message"):
            time = nCommitApplied * 2000 if nCommitApplied < 10 else 20000
            platformtools.dialog_notification('Kodi on Demand', changelog,
                                              time)

        localCommitFile.seek(0)
        localCommitFile.truncate()
        localCommitFile.writelines(c['sha'])
        localCommitFile.close()

    else:
        logger.info('Nessun nuovo aggiornamento')

    return updated
Example #36
0
def play(
    item
):  #Permite preparar la descarga de los .torrents y subtítulos externos
    logger.info()
    itemlist = []
    headers = []
    import os
    from core import downloadtools
    from core import ziptools

    #buscamos la url del .torrent
    patron = '<tr><td align="(?:[^"]+)?"\s*class="(?:[^"]+)?"\s*width="(?:[^"]+)?">\s*Torrent:<\/td><td class="(?:[^"]+)?">\s*<img src="(?:[^"]+)?"\s*alt="(?:[^"]+)?"\s*border="(?:[^"]+)?"\s*\/>\s*<a onmouseover="(?:[^"]+)?"\s*onmouseout="(?:[^"]+)?" href="([^"]+)".*?<\/a>'
    try:
        data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "",
                      httptools.downloadpage(item.url, timeout=timeout).data)
        data = unicode(data, "utf-8", errors="replace").encode("utf-8")
    except:
        pass
    status, itemlist = check_blocked_IP(
        data, itemlist)  #Comprobamos si la IP ha sido bloqueada
    if status:
        return itemlist  #IP bloqueada
    if not scrapertools.find_single_match(data, patron):
        logger.error(
            'ERROR 02: PLAY: No hay enlaces o ha cambiado la estructura de la Web.  Verificar en la Web esto último y reportar el error con el log: PATRON: '
            + patron + ' / DATA: ' + data)
        itemlist.append(
            item.clone(
                action='',
                title=item.channel.capitalize() +
                ': ERROR 02: PLAY: No hay enlaces o ha cambiado la estructura de la Web.  Verificar en la Web esto último y reportar el error con el log'
            ))
        return itemlist
    item.url = urlparse.urljoin(host,
                                scrapertools.find_single_match(data, patron))

    #buscamos subtítulos en español
    patron = '<tr><td align="(?:[^"]+)?"\s*class="(?:[^"]+)?"\s*>\s*Subs.*?<\/td><td class="(?:[^"]+)?"\s*>(.*?)(?:<br\/>)?<\/td><\/tr>'
    data_subt = scrapertools.find_single_match(data, patron)
    if data_subt:
        patron = '<a href="([^"]+)"\s*onmouseover="return overlib\('
        patron += "'Download Spanish subtitles'"
        patron += '\)"\s*onmouseout="(?:[^"]+)?"\s*><img src="(?:[^"]+)?"\s*><\/a>'
        subt = scrapertools.find_single_match(data_subt, patron)
        if subt:
            item.subtitle = urlparse.urljoin(host, subt)

    if item.subtitle:  #Si hay urls de sub-títulos, se descargan
        headers.append(["User-Agent", httptools.get_user_agent()
                        ])  #Se busca el User-Agent por defecto
        videolibrary_path = config.get_videolibrary_path(
        )  #Calculamos el path absoluto a partir de la Videoteca
        if videolibrary_path.lower().startswith(
                "smb://"):  #Si es una conexión SMB, usamos userdata local
            videolibrary_path = config.get_data_path(
            )  #Calculamos el path absoluto a partir de Userdata
        videolibrary_path = os.path.join(videolibrary_path, "subtitles")
        #Primero se borra la carpeta de subtitulos para limpiar y luego se crea
        if os.path.exists(videolibrary_path):
            import shutil
            shutil.rmtree(videolibrary_path, ignore_errors=True)
            time.sleep(1)
        if not os.path.exists(videolibrary_path):
            os.mkdir(videolibrary_path)
        subtitle_name = 'Rarbg-ES_SUBT.zip'  #Nombre del archivo de sub-títulos
        subtitle_folder_path = os.path.join(videolibrary_path,
                                            subtitle_name)  #Path de descarga
        ret = downloadtools.downloadfile(item.subtitle,
                                         subtitle_folder_path,
                                         headers=headers,
                                         continuar=True,
                                         silent=True)

        if os.path.exists(subtitle_folder_path):
            # Descomprimir zip dentro del addon
            # ---------------------------------
            try:
                unzipper = ziptools.ziptools()
                unzipper.extract(subtitle_folder_path, videolibrary_path)
            except:
                import xbmc
                xbmc.executebuiltin('XBMC.Extract("%s", "%s")' %
                                    (subtitle_folder_path, videolibrary_path))
                time.sleep(1)

            # Borrar el zip descargado
            # ------------------------
            os.remove(subtitle_folder_path)

            #Tomo el primer archivo de subtítulos como valor por defecto
            for raiz, subcarpetas, ficheros in os.walk(videolibrary_path):
                for f in ficheros:
                    if f.endswith(".srt"):
                        #f_es = 'rarbg_subtitle.spa.srt'
                        f_es = scrapertools.find_single_match(
                            item.url,
                            '&f=(.*?).torrent$').replace('.', ' ').replace(
                                '-', ' ').lower() + '.spa.srt'
                        if not f_es:
                            f_es = item.infoLabels['originaltitle'] + '.spa.srt'
                            f_es = f_es.replace(':', '').lower()
                        os.rename(os.path.join(videolibrary_path, f),
                                  os.path.join(videolibrary_path, f_es))
                        item.subtitle = os.path.join(
                            videolibrary_path, f_es)  #Archivo de subtitulos
                        break
                break

    itemlist.append(item.clone())  #Reproducción normal

    return itemlist
def addchannel(item):
    from platformcode import platformtools

    import time, os

    logger.info("pelisalacarta.channels.configuracion addchannel")

    tecleado = platformtools.dialog_input("", "Introduzca la URL")
    if not tecleado:
        return
    logger.info("pelisalacarta.channels.configuracion url=%s" % tecleado)

    local_folder = config.get_runtime_path()
    if "canal" in item.title:
        local_folder = filetools.join(local_folder, "channels")
        folder_to_extract = "channels"
        info_accion = "canal"
    else:
        local_folder = filetools.join(local_folder, "servers")
        folder_to_extract = "servers"
        info_accion = "conector"

    # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github)
    try:
        extension = tecleado.rsplit(".", 1)[1]
    except:
        extension = ""

    files = []
    zip = False
    if extension == "py" or extension == "xml":
        filename = tecleado.rsplit("/", 1)[1]
        localfilename = filetools.join(local_folder, filename)
        files.append([tecleado, localfilename, filename])
    else:
        import re
        from core import scrapertools

        # Comprueba si la url apunta a una carpeta completa (channels o servers) de github
        if re.search(r"https://github.com/[^\s]+/" + folder_to_extract, tecleado):
            try:
                data = scrapertools.downloadpage(tecleado)
                matches = scrapertools.find_multiple_matches(
                    data, '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"'
                )
                for url, filename in matches:
                    url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/")
                    localfilename = filetools.join(local_folder, filename)
                    files.append([url, localfilename, filename])
            except:
                import traceback

                logger.info("Detalle del error: %s" % traceback.format_exc())
                platformtools.dialog_ok("Error", "La url no es correcta o no está disponible")
                return
        else:
            filename = "new%s.zip" % info_accion
            localfilename = filetools.join(config.get_data_path(), filename)
            files.append([tecleado, localfilename, filename])
            zip = True

    logger.info("pelisalacarta.channels.configuracion localfilename=%s" % localfilename)
    logger.info("pelisalacarta.channels.configuracion descarga fichero...")

    try:
        if len(files) > 1:
            lista_opciones = ["No", "Sí", "Sí (Sobrescribir todos)"]
            overwrite_all = False
        from core import downloadtools

        for url, localfilename, filename in files:
            result = downloadtools.downloadfile(url, localfilename, continuar=False)
            if result == -3:
                if len(files) == 1:
                    dyesno = platformtools.dialog_yesno(
                        "El archivo ya existe",
                        "Ya existe el %s %s." " ¿Desea sobrescribirlo?" % (info_accion, filename),
                    )
                else:
                    if not overwrite_all:
                        dyesno = platformtools.dialog_select(
                            "El archivo %s ya existe, ¿desea sobrescribirlo?" % filename, lista_opciones
                        )
                    else:
                        dyesno = 1
                # Diálogo cancelado
                if dyesno == -1:
                    return
                # Caso de carpeta github, opción sobrescribir todos
                elif dyesno == 2:
                    overwrite_all = True
                elif dyesno:
                    hora_folder = "Copia seguridad [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                    backup = filetools.join(config.get_data_path(), "backups", hora_folder, folder_to_extract)
                    if not filetools.exists(backup):
                        os.makedirs(backup)
                    import shutil

                    shutil.copy2(localfilename, filetools.join(backup, filename))
                    result = downloadtools.downloadfile(url, localfilename, continuar=True)
                else:
                    if len(files) == 1:
                        return
                    else:
                        continue
    except:
        import traceback

        logger.info("Detalle del error: %s" % traceback.format_exc())
        return

    if zip:
        try:
            # Lo descomprime
            logger.info("pelisalacarta.channels.configuracion descomprime fichero...")
            from core import ziptools

            unzipper = ziptools.ziptools()
            logger.info("pelisalacarta.channels.configuracion destpathname=%s" % local_folder)
            unzipper.extract(localfilename, local_folder, folder_to_extract, True, True)
        except:
            import traceback

            logger.info("Detalle del error: %s" % traceback.format_exc())
            # Borra el zip descargado
            filetools.remove(localfilename)
            platformtools.dialog_ok("Error", "Se ha producido un error extrayendo el archivo")
            return

        # Borra el zip descargado
        logger.info("pelisalacarta.channels.configuracion borra fichero...")
        filetools.remove(localfilename)
        logger.info("pelisalacarta.channels.configuracion ...fichero borrado")

    platformtools.dialog_ok("Éxito", "Actualización/Instalación realizada correctamente")
Example #38
0
def downloadall(item):
    logger.info("[descargas.py] downloadall")

    # Lee la lista de ficheros
    if usingsamba:
        ficheros = samba.get_files(DOWNLOAD_LIST_PATH)
    else:
        ficheros = os.listdir(DOWNLOAD_LIST_PATH)

    logger.info("[descargas.py] numero de ficheros=%d" % len(ficheros))

    # La ordena
    ficheros.sort()

    # Crea un listado con las entradas de favoritos
    for fichero in ficheros:
        # El primer video de la lista
        logger.info("[descargas.py] fichero=" + fichero)

        if fichero != "error" and fichero != ".DS_Store":
            # Descarga el vídeo
            try:
                # Lee el bookmark
                canal, titulo, thumbnail, plot, server, url, fulltitle = favoritos.readbookmark(
                    fichero, DOWNLOAD_LIST_PATH)
                logger.info("[descargas.py] url=" + url)

                # Averigua la URL del vídeo
                video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
                    server, url, "", False)

                # La última es la de mayor calidad, lo mejor para la descarga
                mediaurl = video_urls[len(video_urls) - 1][1]
                logger.info("[descargas.py] mediaurl=" + mediaurl)

                # Genera el NFO
                nfofilepath = downloadtools.getfilefromtitle(
                    "sample.nfo", fulltitle)
                outfile = open(nfofilepath, "w")
                outfile.write("<movie>\n")
                outfile.write("<title>(" + fulltitle + ")</title>\n")
                outfile.write("<originaltitle></originaltitle>\n")
                outfile.write("<rating>0.000000</rating>\n")
                outfile.write("<year>2009</year>\n")
                outfile.write("<top250>0</top250>\n")
                outfile.write("<votes>0</votes>\n")
                outfile.write("<outline></outline>\n")
                outfile.write("<plot>" + plot + "</plot>\n")
                outfile.write("<tagline></tagline>\n")
                outfile.write("<runtime></runtime>\n")
                outfile.write("<thumb></thumb>\n")
                outfile.write("<mpaa>Not available</mpaa>\n")
                outfile.write("<playcount>0</playcount>\n")
                outfile.write("<watched>false</watched>\n")
                outfile.write("<id>tt0432337</id>\n")
                outfile.write("<filenameandpath></filenameandpath>\n")
                outfile.write("<trailer></trailer>\n")
                outfile.write("<genre></genre>\n")
                outfile.write("<credits></credits>\n")
                outfile.write("<director></director>\n")
                outfile.write("<actor>\n")
                outfile.write("<name></name>\n")
                outfile.write("<role></role>\n")
                outfile.write("</actor>\n")
                outfile.write("</movie>")
                outfile.flush()
                outfile.close()
                logger.info("[descargas.py] Creado fichero NFO")

                # Descarga el thumbnail
                if thumbnail != "":
                    logger.info("[descargas.py] thumbnail=" + thumbnail)
                    thumbnailfile = downloadtools.getfilefromtitle(
                        thumbnail, fulltitle)
                    thumbnailfile = thumbnailfile[:-4] + ".tbn"
                    logger.info("[descargas.py] thumbnailfile=" +
                                thumbnailfile)
                    try:
                        downloadtools.downloadfile(thumbnail, thumbnailfile)
                        logger.info("[descargas.py] Thumbnail descargado")
                    except:
                        logger.info(
                            "[descargas.py] error al descargar thumbnail")
                        for line in sys.exc_info():
                            logger.error("%s" % line)

                # Descarga el video
                #dev = downloadtools.downloadtitle(mediaurl,fulltitle)
                dev = downloadtools.downloadbest(video_urls, fulltitle)
                if dev == -1:
                    # El usuario ha cancelado la descarga
                    logger.info("[descargas.py] Descarga cancelada")
                    return
                elif dev == -2:
                    # Error en la descarga, lo mueve a ERROR y continua con el siguiente
                    logger.info("[descargas.py] ERROR EN DESCARGA DE " +
                                fichero)
                    if not usingsamba:
                        origen = os.path.join(DOWNLOAD_LIST_PATH, fichero)
                        destino = os.path.join(ERROR_PATH, fichero)
                        import shutil
                        shutil.move(origen, destino)
                    else:
                        favoritos.savebookmark(canal, titulo, url, thumbnail,
                                               server, plot, fulltitle,
                                               ERROR_PATH)
                        favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)
                else:
                    logger.info("[descargas.py] Video descargado")
                    # Borra el bookmark e itera para obtener el siguiente video
                    filepath = os.path.join(DOWNLOAD_LIST_PATH, fichero)
                    if usingsamba:
                        os.remove(filepath)
                    else:
                        favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)
                    logger.info("[descargas.py] " + fichero + " borrado")
            except:
                logger.info("[descargas.py] ERROR EN DESCARGA DE " + fichero)
                import sys
                for line in sys.exc_info():
                    logger.error("%s" % line)
                if not usingsamba:
                    origen = os.path.join(DOWNLOAD_LIST_PATH, fichero)
                    destino = os.path.join(ERROR_PATH, fichero)
                    import shutil
                    shutil.move(origen, destino)
                else:
                    favoritos.savebookmark(canal, titulo, url, thumbnail,
                                           server, plot, fulltitle, ERROR_PATH)
                    favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)
Example #39
0
def addchannel(item):
    import os
    import time
    logger.info()

    tecleado = platformtools.dialog_input("", "Introduzca la URL")
    if not tecleado:
        return
    logger.info("url=%s" % tecleado)

    local_folder = config.get_runtime_path()
    if "canal" in item.title:
        local_folder = filetools.join(local_folder, 'channels')
        folder_to_extract = "channels"
        info_accion = "canal"
    else:
        local_folder = filetools.join(local_folder, 'servers')
        folder_to_extract = "servers"
        info_accion = "conector"

    # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github)
    try:
        extension = tecleado.rsplit(".", 1)[1]
    except:
        extension = ""

    files = []
    zip = False
    if extension == "py" or extension == "xml":
        filename = tecleado.rsplit("/", 1)[1]
        localfilename = filetools.join(local_folder, filename)
        files.append([tecleado, localfilename, filename])
    else:
        import re
        from core import scrapertools
        # Comprueba si la url apunta a una carpeta completa (channels o servers) de github
        if re.search(r'https://github.com/[^\s]+/'+folder_to_extract, tecleado):
            try:
                data = scrapertools.downloadpage(tecleado)
                matches = scrapertools.find_multiple_matches(data,
                                                             '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"')
                for url, filename in matches:
                    url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/")
                    localfilename = filetools.join(local_folder, filename)
                    files.append([url, localfilename, filename])
            except:
                import traceback
                logger.error("Detalle del error: %s" % traceback.format_exc())
                platformtools.dialog_ok("Error", "La url no es correcta o no está disponible")
                return
        else:
            filename = 'new%s.zip' % info_accion
            localfilename = filetools.join(config.get_data_path(), filename)
            files.append([tecleado, localfilename, filename])
            zip = True

    logger.info("localfilename=%s" % localfilename)
    logger.info("descarga fichero...")

    try:
        if len(files) > 1:
            lista_opciones = ["No", "Sí", "Sí (Sobrescribir todos)"]
            overwrite_all = False
        from core import downloadtools
        for url, localfilename, filename in files:
            result = downloadtools.downloadfile(url, localfilename, continuar=False, resumir=False)
            if result == -3:
                if len(files) == 1:
                    dyesno = platformtools.dialog_yesno("El archivo ya existe", "Ya existe el %s %s. "
                                                                                "¿Desea sobrescribirlo?" %
                                                        (info_accion, filename))
                else:
                    if not overwrite_all:
                        dyesno = platformtools.dialog_select("El archivo %s ya existe, ¿desea sobrescribirlo?"
                                                             % filename, lista_opciones)
                    else:
                        dyesno = 1
                # Diálogo cancelado
                if dyesno == -1:
                    return
                # Caso de carpeta github, opción sobrescribir todos
                elif dyesno == 2:
                    overwrite_all = True
                elif dyesno:
                    hora_folder = "Copia seguridad [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                    backup = filetools.join(config.get_data_path(), 'backups', hora_folder, folder_to_extract)
                    if not filetools.exists(backup):
                        os.makedirs(backup)
                    import shutil
                    shutil.copy2(localfilename, filetools.join(backup, filename))
                    downloadtools.downloadfile(url, localfilename, continuar=True, resumir=False)
                else:
                    if len(files) == 1:
                        return
                    else:
                        continue
    except:
        import traceback
        logger.error("Detalle del error: %s" % traceback.format_exc())
        return

    if zip:
        try:
            # Lo descomprime
            logger.info("descomprime fichero...")
            from core import ziptools
            unzipper = ziptools.ziptools()
            logger.info("destpathname=%s" % local_folder)
            unzipper.extract(localfilename, local_folder, folder_to_extract, True, True)
        except:
            import traceback
            logger.error("Detalle del error: %s" % traceback.format_exc())
            # Borra el zip descargado
            filetools.remove(localfilename)
            platformtools.dialog_ok("Error", "Se ha producido un error extrayendo el archivo")
            return

        # Borra el zip descargado
        logger.info("borra fichero...")
        filetools.remove(localfilename)
        logger.info("...fichero borrado")

    platformtools.dialog_ok("Éxito", "Actualización/Instalación realizada correctamente")
def addchannel(item):
    from platformcode import platformtools
    import os
    import time
    logger.info()
    
    tecleado = platformtools.dialog_input("", "Inserire l'URL")
    if not tecleado:
        return
    logger.info("url=%s" % tecleado)

    local_folder = config.get_runtime_path()
    if "canal" in item.title:
        local_folder = filetools.join(local_folder, 'channels')
        folder_to_extract = "channels"
        info_accion = "canal"
    else:
        local_folder = filetools.join(local_folder, 'servers')
        folder_to_extract = "servers"
        info_accion = "conector"

    # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github)
    try:
        extension = tecleado.rsplit(".", 1)[1]
    except:
        extension = ""

    files = []
    zip = False
    if extension == "py" or extension == "xml":
        filename = tecleado.rsplit("/", 1)[1]
        localfilename = filetools.join(local_folder, filename)
        files.append([tecleado, localfilename, filename])
    else:
        import re
        from core import scrapertools
        # Comprueba si la url apunta a una carpeta completa (channels o servers) de github
        if re.search(r'https://github.com/[^\s]+/'+folder_to_extract, tecleado):
            try:
                data = scrapertools.downloadpage(tecleado)
                matches = scrapertools.find_multiple_matches(data,
                                                             '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"')
                for url, filename in matches:
                    url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/")
                    localfilename = filetools.join(local_folder, filename)
                    files.append([url, localfilename, filename])
            except:
                import traceback
                logger.info("Detalle del error: %s" % traceback.format_exc())
                platformtools.dialog_ok("Errore", "L'URL non è corretto o non disponibile")
                return
        else:
            filename = 'new%s.zip' % info_accion
            localfilename = filetools.join(config.get_data_path(), filename)
            files.append([tecleado, localfilename, filename])
            zip = True

    logger.info("localfilename=%s" % localfilename)
    logger.info("descarga fichero...")
    
    try:
        if len(files) > 1:
            lista_opciones = ["No", "Si", "Si (Sovrascrivere tutto)"]
            overwrite_all = False
        from core import downloadtools
        for url, localfilename, filename in files:
            result = downloadtools.downloadfile(url, localfilename, continuar=False)
            if result == -3:
                if len(files) == 1:
                    dyesno = platformtools.dialog_yesno("Il file esiste già", "%s %s esiste già. "
                                                                                "Vuoi sovrascrivere?" %
                                                        (info_accion, filename))
                else:
                    if not overwrite_all:
                        dyesno = platformtools.dialog_select("Il file %s esiste già, vuoi sovrascrivere?"
                                                             % filename, lista_opciones)
                    else:
                        dyesno = 1
                # Diálogo cancelado
                if dyesno == -1:
                    return
                # Caso de carpeta github, opción sobrescribir todos
                elif dyesno == 2:
                    overwrite_all = True
                elif dyesno:
                    hora_folder = "Backup [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                    backup = filetools.join(config.get_data_path(), 'backups', hora_folder, folder_to_extract)
                    if not filetools.exists(backup):
                        os.makedirs(backup)
                    import shutil
                    shutil.copy2(localfilename, filetools.join(backup, filename))
                    downloadtools.downloadfile(url, localfilename, continuar=True)
                else:
                    if len(files) == 1:
                        return
                    else:
                        continue
    except:
        import traceback
        logger.info("Detalle del error: %s" % traceback.format_exc())
        return

    if zip:
        try:
            # Lo descomprime
            logger.info("descomprime fichero...")
            from core import ziptools
            unzipper = ziptools.ziptools()
            logger.info("destpathname=%s" % local_folder)
            unzipper.extract(localfilename, local_folder, folder_to_extract, True, True)
        except:
            import traceback
            logger.error("Detalle del error: %s" % traceback.format_exc())
            # Borra el zip descargado
            filetools.remove(localfilename)
            platformtools.dialog_ok("Errore", "C'è stato un errore nell'estrazione del file")
            return

        # Borra el zip descargado
        logger.info("borra fichero...")
        filetools.remove(localfilename)
        logger.info("...fichero borrado")

    platformtools.dialog_ok("Successo", "Aggiornamento/installazione eseguita correttamente")
Example #41
0
def check_addon_updates(verbose=False):
    logger.info()

    ADDON_UPDATES_JSON = 'https://extra.alfa-addon.com/addon_updates/updates.json'
    ADDON_UPDATES_ZIP = 'https://extra.alfa-addon.com/addon_updates/updates.zip'

    try:
        last_fix_json = os.path.join(
            config.get_runtime_path(),
            'last_fix.json')  # información de la versión fixeada del usuario
        # Se guarda en get_runtime_path en lugar de get_data_path para que se elimine al cambiar de versión

        # Descargar json con las posibles actualizaciones
        # -----------------------------------------------
        data = httptools.downloadpage(ADDON_UPDATES_JSON, timeout=2).data
        if data == '':
            logger.info('No se encuentran actualizaciones del addon')
            if verbose:
                platformtools.dialog_notification(
                    config.get_localized_string(70667),
                    config.get_localized_string(70668))
            return False

        data = jsontools.load(data)
        if 'addon_version' not in data or 'fix_version' not in data:
            logger.info('No hay actualizaciones del addon')
            if verbose:
                platformtools.dialog_notification(
                    config.get_localized_string(70667),
                    config.get_localized_string(70668))
            return False

        # Comprobar versión que tiene instalada el usuario con versión de la actualización
        # --------------------------------------------------------------------------------
        current_version = config.get_addon_version(with_fix=False)
        if current_version != data['addon_version']:
            logger.info('No hay actualizaciones para la versión %s del addon' %
                        current_version)
            if verbose:
                platformtools.dialog_notification(
                    config.get_localized_string(70667),
                    config.get_localized_string(70668))
            return False

        if os.path.exists(last_fix_json):
            try:
                lastfix = {}
                lastfix = jsontools.load(filetools.read(last_fix_json))
                if lastfix['addon_version'] == data[
                        'addon_version'] and lastfix['fix_version'] == data[
                            'fix_version']:
                    logger.info(
                        config.get_localized_string(70670) %
                        (data['addon_version'], data['fix_version']))
                    if verbose:
                        platformtools.dialog_notification(
                            config.get_localized_string(70667),
                            config.get_localized_string(70671) %
                            (data['addon_version'], data['fix_version']))
                    return False
            except:
                if lastfix:
                    logger.error('last_fix.json: ERROR en: ' + str(lastfix))
                else:
                    logger.error('last_fix.json: ERROR desconocido')
                lastfix = {}

        # Descargar zip con las actualizaciones
        # -------------------------------------
        localfilename = os.path.join(config.get_data_path(),
                                     'temp_updates.zip')
        if os.path.exists(localfilename): os.remove(localfilename)

        downloadtools.downloadfile(ADDON_UPDATES_ZIP,
                                   localfilename,
                                   silent=True)

        # Descomprimir zip dentro del addon
        # ---------------------------------
        try:
            unzipper = ziptools.ziptools()
            unzipper.extract(localfilename, config.get_runtime_path())
        except:
            import xbmc
            xbmc.executebuiltin('XBMC.Extract("%s", "%s")' %
                                (localfilename, config.get_runtime_path()))
            time.sleep(1)

        # Borrar el zip descargado
        # ------------------------
        os.remove(localfilename)

        # Guardar información de la versión fixeada
        # -----------------------------------------
        if 'files' in data: data.pop('files', None)
        filetools.write(last_fix_json, jsontools.dump(data))

        logger.info(
            config.get_localized_string(70672) %
            (data['addon_version'], data['fix_version']))
        if verbose:
            platformtools.dialog_notification(
                config.get_localized_string(70673),
                config.get_localized_string(70671) %
                (data['addon_version'], data['fix_version']))
        return True

    except:
        logger.error('Error al comprobar actualizaciones del addon!')
        logger.error(traceback.format_exc())
        if verbose:
            platformtools.dialog_notification(
                config.get_localized_string(70674),
                config.get_localized_string(70675))
        return False
Example #42
0
def set_content(content_type, silent=False):
    """
    Procedimiento para auto-configurar la biblioteca de kodi con los valores por defecto
    @type content_type: str ('CINE' o 'SERIES')
    @param content_type: tipo de contenido para configurar, series o peliculas
    """
    if config.is_xbmc():
        continuar = True
        msg_text = ""
        librarypath = config.get_setting("librarypath")

        if content_type == 'CINE':
            if not xbmc.getCondVisibility(
                    'System.HasAddon(metadata.themoviedb.org)'):
                if not silent:
                    # Preguntar si queremos instalar metadata.themoviedb.org
                    install = platformtools.dialog_yesno(
                        "The Movie Database", "TheMovieDB non presente.",
                        "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.themoviedb.org
                        xbmc.executebuiltin(
                            'xbmc.installaddon(metadata.themoviedb.org)', True)
                        logger.info(
                            "Instalado el Scraper de películas de TheMovieDB")
                    except:
                        pass

                continuar = (install and xbmc.getCondVisibility(
                    'System.HasAddon(metadata.themoviedb.org)'))
                if not continuar:
                    msg_text = "The Movie Database no instalado."

        else:  # SERIES
            # Instalar The TVDB
            if not xbmc.getCondVisibility(
                    'System.HasAddon(metadata.tvdb.com)'):
                if not silent:
                    # Preguntar si queremos instalar metadata.tvdb.com
                    install = platformtools.dialog_yesno(
                        "The TVDB", "The TVDB non presente.",
                        "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.tvdb.com
                        xbmc.executebuiltin(
                            'xbmc.installaddon(metadata.tvdb.com)', True)
                        logger.info(
                            "Instalado el Scraper de series de The TVDB")
                    except:
                        pass

                continuar = (install and xbmc.getCondVisibility(
                    'System.HasAddon(metadata.tvdb.com)'))
                if not continuar:
                    msg_text = "The TVDB no instalado."

            # Instalar TheMovieDB
            if continuar and not xbmc.getCondVisibility(
                    'System.HasAddon(metadata.tvshows.themoviedb.org)'):
                continuar = False
                if not silent:
                    # Preguntar si queremos instalar metadata.tvshows.themoviedb.org
                    install = platformtools.dialog_yesno(
                        "The Movie Database", "TheMovieDB non presente.",
                        "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.tvshows.themoviedb.org
                        # 1º Probar desde el repositorio ...
                        xbmc.executebuiltin(
                            'xbmc.installaddon(metadata.tvshows.themoviedb.org)',
                            True)
                        if not xbmc.getCondVisibility(
                                'System.HasAddon(metadata.tvshows.themoviedb.org)'
                        ):
                            # ...si no funciona descargar e instalar desde la web
                            url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip"
                            path_down = xbmc.translatePath(
                                "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip"
                            )
                            path_unzip = xbmc.translatePath(
                                "special://home/addons/")
                            header = (
                                "User-Agent",
                                "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013"
                            )

                            from core import downloadtools
                            from core import ziptools

                            downloadtools.downloadfile(url,
                                                       path_down,
                                                       continuar=True,
                                                       headers=[header])
                            unzipper = ziptools.ziptools()
                            unzipper.extract(path_down, path_unzip)
                            xbmc.executebuiltin('UpdateLocalAddons')

                        strSettings = '<settings>\n' \
                                      '    <setting id="fanart" value="true" />\n' \
                                      '    <setting id="keeporiginaltitle" value="false" />\n' \
                                      '    <setting id="language" value="it" />\n' \
                                      '</settings>'
                        path_settings = xbmc.translatePath(
                            "special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml"
                        )
                        tv_themoviedb_addon_path = filetools.dirname(
                            path_settings)
                        if not filetools.exists(tv_themoviedb_addon_path):
                            filetools.mkdir(tv_themoviedb_addon_path)
                        if filetools.write(path_settings, strSettings):
                            continuar = True

                    except:
                        pass

                continuar = (install and continuar)
                if not continuar:
                    msg_text = "The Movie Database non installato."

        idPath = 0
        idParentPath = 0
        strPath = ""
        if continuar:
            continuar = False

            # Buscamos el idPath
            sql = 'SELECT MAX(idPath) FROM path'
            nun_records, records = execute_sql_kodi(sql)
            if nun_records == 1:
                idPath = records[0][0] + 1

            sql_librarypath = librarypath
            if sql_librarypath.startswith("special://"):
                sql_librarypath = sql_librarypath.replace(
                    '/profile/', '/%/').replace('/home/userdata/', '/%/')
                sep = '/'
            elif sql_librarypath.startswith("smb://"):
                sep = '/'
            else:
                sep = os.sep

            if not sql_librarypath.endswith(sep):
                sql_librarypath += sep

            # Buscamos el idParentPath
            sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_librarypath
            nun_records, records = execute_sql_kodi(sql)
            if nun_records == 1:
                idParentPath = records[0][0]
                librarypath = records[0][1][:-1]
                continuar = True
            else:
                # No existe librarypath en la BD: la insertamos
                sql_librarypath = librarypath
                if not sql_librarypath.endswith(sep):
                    sql_librarypath += sep

                sql = 'INSERT INTO path (idPath, strPath,  scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \
                      '(%s, "%s", 0, 0, 0, 0)' % (idPath, sql_librarypath)
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    continuar = True
                    idParentPath = idPath
                    idPath += 1
                else:
                    msg_text = "Omesso di impostare LibraryPath in BD"

        if continuar:
            continuar = False

            # Fijamos strContent, strScraper, scanRecursive y strSettings
            if content_type == 'CINE':
                strContent = 'movies'
                strScraper = 'metadata.themoviedb.org'
                scanRecursive = 2147483647
                strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \
                              "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \
                              "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \
                              "<setting id='trailer' value='true' /></settings>"
                strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per i film ?"
                if not librarypath.endswith(sep):
                    librarypath += sep
                strPath = librarypath + config.get_setting(
                    "folder_movies") + sep
            else:
                strContent = 'tvshows'
                strScraper = 'metadata.tvdb.com'
                scanRecursive = 0
                strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \
                              "<setting id='absolutenumber' value='false' />" \
                              "<setting id='dvdorder' value='false' />" \
                              "<setting id='fallback' value='true' />" \
                              "<setting id='fanart' value='true' />" \
                              "<setting id='language' value='it' /></settings>"
                strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per le serie ?"
                if not librarypath.endswith(sep):
                    librarypath += sep
                strPath = librarypath + config.get_setting(
                    "folder_tvshows") + sep

            logger.info("%s: %s" % (content_type, strPath))
            # Comprobamos si ya existe strPath en la BD para evitar duplicados
            sql = 'SELECT idPath FROM path where strPath="%s"' % strPath
            nun_records, records = execute_sql_kodi(sql)
            sql = ""
            if nun_records == 0:
                # Insertamos el scraper
                sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \
                      'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \
                      '"%s", 0, 0, %s)' % (
                      idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath)
            else:
                if not silent:
                    # Preguntar si queremos configurar themoviedb.org como opcion por defecto
                    actualizar = platformtools.dialog_yesno(
                        "The TVDB", strActualizar)
                else:
                    actualizar = True

                if actualizar:
                    # Actualizamos el scraper
                    idPath = records[0][0]
                    sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \
                          'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath)

            if sql:
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    continuar = True

            if not continuar:
                msg_text = "Omesso impostare LibraryPath in BD"

        if not continuar:
            heading = "Biblioteca %s no configurada" % content_type
        elif content_type == 'SERIES' and not xbmc.getCondVisibility(
                'System.HasAddon(metadata.tvshows.themoviedb.org)'):
            heading = "Biblioteca %s configurata" % content_type
            msg_text = "Riavviare Kodi per attuare le modifiche."
        else:
            heading = "Biblioteca %s configurata" % content_type
            msg_text = "Libreria di Kodi configurata correttamente."
        platformtools.dialog_notification(heading,
                                          msg_text,
                                          icon=1,
                                          time=10000)
        logger.info("%s: %s" % (heading, msg_text))
def establecer_contenido(content_type, silent=False):
    if config.is_xbmc():
        continuar = False
        msg_text = "Cartella Libreria personalizzata"

        librarypath = config.get_setting("librarypath")
        if librarypath == "":
            continuar = True
            if content_type == FOLDER_MOVIES:
                if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'):
                    if not silent:
                        # Preguntar si queremos instalar metadata.themoviedb.org
                        install = platformtools.dialog_yesno("The Movie Database",
                                                             "TheMovieDB. non presente.",
                                                             "Installare adesso?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.themoviedb.org
                            xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True)
                            logger.info("Instalado el Scraper de películas de TheMovieDB")
                        except:
                            pass

                    continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'))
                    if not continuar:
                        msg_text = "The Movie Database non installato."

            else: # SERIES
                # Instalar The TVDB
                if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'):
                    if not silent:
                        # Preguntar si queremos instalar metadata.tvdb.com
                        install = platformtools.dialog_yesno("The TVDB",
                                                             "The TVDB non presente.",
                                                             "Installare adesso?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.tvdb.com
                            xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True)
                            logger.info("Instalado el Scraper de series de The TVDB")
                        except:
                            pass

                    continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'))

                    if not continuar:
                        msg_text = "The TVDB non installato."

                # Instalar TheMovieDB
                if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                    continuar = False
                    if not silent:
                        # Preguntar si queremos instalar metadata.tvshows.themoviedb.org
                        install = platformtools.dialog_yesno("The Movie Database",
                                                             "TheMovieDB non presente.",
                                                             "Installare adesso?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.tvshows.themoviedb.org
                            # 1º Probar desde el repositorio ...
                            xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True)
                            if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                                    # ...si no funciona descargar e instalar desde la web
                                    url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip"
                                    path_down = xbmc.translatePath(
                                        "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip")
                                    path_unzip = xbmc.translatePath("special://home/addons/")
                                    header = ("User-Agent",
                                              "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013")

                                    from core import downloadtools
                                    from core import ziptools

                                    downloadtools.downloadfile(url, path_down, continuar=True, headers=[header])
                                    unzipper = ziptools.ziptools()
                                    unzipper.extract(path_down, path_unzip)
                                    xbmc.executebuiltin('xbmc.UpdateLocalAddons')

                            strSettings = '<settings>\n' \
                                          '    <setting id="fanart" value="true" />\n' \
                                          '    <setting id="keeporiginaltitle" value="false" />\n' \
                                          '    <setting id="language" value="it" />\n' \
                                          '</settings>'
                            path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml")
                            tv_themoviedb_addon_path = filetools.dirname(path_settings)
                            if not filetools.exists(tv_themoviedb_addon_path):
                                filetools.mkdir(tv_themoviedb_addon_path)
                            if filetools.write(path_settings,strSettings):
                                continuar = True
                        except:
                            pass

                    continuar = (install and continuar)
                    if not continuar:
                        msg_text = "The Movie Database non installato."

            idPath = 0
            idParentPath = 0
            strPath = ""
            if continuar:
                continuar = False
                librarypath = "special://home/userdata/addon_data/plugin.video." + config.PLUGIN_NAME + "/library/"

                # Buscamos el idPath
                sql = 'SELECT MAX(idPath) FROM path'
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    idPath = records[0][0] + 1


                # Buscamos el idParentPath
                sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % \
                                            librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/')
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    idParentPath = records[0][0]
                    librarypath = records[0][1]
                    continuar = True
                else:
                    # No existe librarypath en la BD: la insertamos
                    sql = 'INSERT INTO path (idPath, strPath,  scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \
                          '(%s, "%s", 0, 0, 0, 0)' % (idPath, librarypath)
                    nun_records, records = execute_sql_kodi(sql)
                    if nun_records == 1:
                        continuar = True
                        idParentPath = idPath
                        idPath += 1
                    else:
                        msg_text = "Impossibile impostare librarypath in BD"

            if continuar:
                continuar = False

                # Fijamos strContent, strScraper, scanRecursive y strSettings
                if content_type == FOLDER_MOVIES:
                    strContent = 'movies'
                    strScraper = 'metadata.themoviedb.org'
                    scanRecursive = 2147483647
                    strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \
                                  "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \
                                  "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \
                                  "<setting id='trailer' value='true' /></settings>"
                    strActualizar = "Configurare lo scraper per i film in italiano?"

                else:
                    strContent = 'tvshows'
                    strScraper = 'metadata.tvdb.com'
                    scanRecursive = 0
                    strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \
                                  "<setting id='absolutenumber' value='false' />" \
                                  "<setting id='dvdorder' value='false' />" \
                                  "<setting id='fallback' value='true' />" \
                                  "<setting id='fanart' value='true' />" \
                                  "<setting id='language' value='it' /></settings>"
                    strActualizar = "Configurare lo scraper per le serie in italiano?"

                # Fijamos strPath
                strPath = librarypath + content_type + "/"
                logger.info("%s: %s" % (content_type, strPath))

                # Comprobamos si ya existe strPath en la BD para evitar duplicados
                sql = 'SELECT idPath FROM path where strPath="%s"' % strPath
                nun_records, records = execute_sql_kodi(sql)
                sql = ""
                if nun_records == 0:
                    # Insertamos el scraper
                    sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \
                          'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \
                          '"%s", 0, 0, %s)' % (
                          idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath)
                else:
                    if not silent:
                        # Preguntar si queremos configurar themoviedb.org como opcion por defecto
                        actualizar = platformtools.dialog_yesno("The TVDB", strActualizar)
                    else:
                        actualizar = True

                    if actualizar:
                        # Actualizamos el scraper
                        idPath = records[0][0]
                        sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \
                              'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath)

                if sql:
                    nun_records, records = execute_sql_kodi(sql)
                    if nun_records == 1:
                        continuar = True

                if not continuar:
                    msg_text = "Error al configurar el scraper en la BD."

        if not continuar:
            heading = "Libreria non %s configurata" % content_type
            #msg_text = "Assicurarsi di aver installato l'add-on The Movie Database"
        elif content_type == FOLDER_TVSHOWS and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
            heading = "Libreria %s configurata" % content_type
            msg_text = "Kodi deve essere riavviato affinché le modifiche abbiano effetto."
        else:
            heading = "Libreria %s configurata" % content_type
            msg_text = "Complimenti la libreria di Kodi è stata configurata correttamente."
        platformtools.dialog_notification(heading, msg_text, icon=1, time=10000)
        logger.info("%s: %s" % (heading,msg_text))
def strm_detail(item):
    logger.info("[cuevana.py] strm_detail")
    code =""
    if (item.url.startswith("http://www.cuevana.tv/list_search_info.php")):
        data = scrapertools.cachePage(item.url)
        patron = "window.location\='/series/([0-9]+)/"
        matches = re.compile(patron,re.DOTALL).findall(data)
        if len(matches)>0:
            code = matches[0]
        logger.info("code="+code)
        url = "http://www.cuevana.tv/player/source?id=%s&subs=,ES&onstart=yes&tipo=s&sub_pre=ES" % matches[0]
        serieOpelicula = True
    else:
        logger.info("url1="+item.url)
        patron = "http://www.cuevana.tv/peliculas/([0-9]+)/"
        matches = re.compile(patron,re.DOTALL).findall(item.url)
        if len(matches)>0:
            code = matches[0]
        logger.info("code="+code)
        url = "http://www.cuevana.tv/player/source?id=%s&subs=,ES&onstart=yes&sub_pre=ES#" % code
        serieOpelicula = False
    
    logger.info("url2="+url)
    data = scrapertools.cachePage(url)

    # goSource('ee5533f50eab1ef355661eef3b9b90ec','megaupload')
    patron = "goSource\('([^']+)','megaupload'\)"
    matches = re.compile(patron,re.DOTALL).findall(data)
    if len(matches)>0:
        data = scrapertools.cachePagePost("http://www.cuevana.tv/player/source_get","key=%s&host=megaupload&vars=&id=2933&subs=,ES&tipo=&amp;sub_pre=ES" % matches[0])
    logger.info("data="+data)

    # Subtitulos
    if serieOpelicula:
        suburl = "http://www.cuevana.tv/files/s/sub/"+code+"_ES.srt"
    else:
        suburl = "http://www.cuevana.tv/files/sub/"+code+"_ES.srt"
    logger.info("suburl="+suburl)
    
    # Elimina el archivo subtitulo.srt de alguna reproduccion anterior
    ficherosubtitulo = os.path.join( config.get_data_path(), 'subtitulo.srt' )
    if os.path.exists(ficherosubtitulo):
        try:
          os.remove(ficherosubtitulo)
        except IOError:
          xbmc.output("Error al eliminar el archivo subtitulo.srt "+ficherosubtitulo)
          raise

    from core import downloadtools
    downloadtools.downloadfile(suburl, ficherosubtitulo )
    config.set_setting("subtitulo","true")

    listavideos = servertools.findvideos(data)
    
    for video in listavideos:
        server = video[2]
        if server == "Megaupload":
          scrapedtitle = item.title + " [" + server + "]"
          scrapedurl = video[1]
          thumbnail = urllib.unquote_plus( item.thumbnail )
          plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" )
          # xbmctools.playvideo("cuevana","megaupload","G0NMCIXJ","Series","24","","",strmfile=True)
          xbmctools.playvideo(CHANNELNAME,server,scrapedurl,"Series",scrapedtitle,item.thumbnail,item.plot,strmfile=True,subtitle=suburl)
          exit
    logger.info("[cuevana.py] strm_detail fin")
    return
def run():
    import sys
    logger.info("[tvalacarta.py] run")
    
    # Verifica si el path de usuario del plugin está creado
    if not os.path.exists(config.get_data_path()):
        logger.debug("[tvalacarta.py] Path de usuario no existe, se crea: "+config.get_data_path())
        os.mkdir(config.get_data_path())

    # Imprime en el log los parámetros de entrada
    logger.info("[tvalacarta.py] sys.argv=%s" % str(sys.argv))
    
    # Crea el diccionario de parametros
    params = dict()
    if len(sys.argv)>=2 and len(sys.argv[2])>0:
        params = dict(part.split('=') for part in sys.argv[ 2 ][ 1: ].split('&'))
    logger.info("[tvalacarta.py] params=%s" % str(params))
    
    # Extrae la url de la página
    if (params.has_key("url")):
        url = urllib.unquote_plus( params.get("url") )
    else:
        url=''

    # Extrae la accion
    if (params.has_key("action")):
        action = params.get("action")
    else:
        action = "selectchannel"

    # Extrae el server
    if (params.has_key("server")):
        server = params.get("server")
    else:
        server = ""

    # Extrae la categoria
    if (params.has_key("category")):
        category = urllib.unquote_plus( params.get("category") )
    else:
        if params.has_key("channel"):
            category = params.get("channel")
        else:
            category = ""


    try:
        # Accion por defecto - elegir canal
        if ( action=="selectchannel" ):
            
            if config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("tvalacarta",config.get_localized_string(30064))
                except:
                    pass

            import channelselector as plugin
            plugin.mainlist(params, url, category)

        # Actualizar version
        elif ( action=="update" ):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info("[pelisalacarta.py] Actualizacion automática desactivada")

            import channelselector as plugin
            plugin.listchannels(params, url, category)

        elif (action=="channeltypes"):
            import channelselector as plugin
            plugin.channeltypes(params,url,category)

        elif (action=="listchannels"):
            import channelselector as plugin
            plugin.listchannels(params,url,category)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(params.get("channel"))

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin",params.get("channel"),config.get_localized_string(30063))
                except:
                    pass

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en pelisalacarta
            regular_channel_path = os.path.join( config.get_runtime_path(), PLUGIN_NAME , 'channels' , params.get("channel")+".py" )
            core_channel_path = os.path.join( config.get_runtime_path(), 'core' , params.get("channel")+".py" )

            if params.get("channel")=="buscador":
                import pelisalacarta.buscador as channel
            elif os.path.exists( regular_channel_path ):
                exec "import pelisalacarta.channels."+params.get("channel")+" as channel"
            elif os.path.exists( core_channel_path ):
                exec "from core import "+params.get("channel")+" as channel"

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos 
            if category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            print "generico=" , generico 
            
            if not generico:
                exec "channel."+action+"(params, url, category)"
            else:
                if params.has_key("title"):
                    title = urllib.unquote_plus( params.get("title") )
                else:
                    title = ""
                if params.has_key("thumbnail"):
                    thumbnail = urllib.unquote_plus( params.get("thumbnail") )
                else:
                    thumbnail = ""
                if params.has_key("plot"):
                    plot = urllib.unquote_plus( params.get("plot") )
                else:
                    plot = ""
                if params.has_key("server"):
                    server = urllib.unquote_plus( params.get("server") )
                else:
                    server = "directo"
                if params.has_key("extradata"):
                    extra = urllib.unquote_plus( params.get("extradata") )
                else:
                    extra = ""
                if params.has_key("subtitle"):
                    subtitle = urllib.unquote_plus( params.get("subtitle") )
                else:
                    subtitle = ""
            
                from core.item import Item
                item = Item(channel=params.get("channel"), title=title , url=url, thumbnail=thumbnail , plot=plot , server=server, category=category, extra=extra, subtitle=subtitle)

                if item.subtitle!="":
                    logger.info("Descargando subtítulos de "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("Sin subtitulos")

                from core import xbmctools
                if action=="play":
                    # Si el canal tiene una acción "play" tiene prioridad
                    try:
                        itemlist = channel.play(item)
                        if len(itemlist)>0:
                            item = itemlist[0]
                    except:
                        import sys
                        for line in sys.exc_info():
                            logger.error( "%s" % line )
                   
                    xbmctools.playvideo(params.get("channel"),item.server,item.url,item.category,item.title,item.thumbnail,item.plot,subtitle=item.subtitle)
                else:
                    if action!="findvideos":
                        exec "itemlist = channel."+action+"(item)"
                    else:
                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        try:
                            exec "itemlist = channel."+action+"(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        except:
                            itemlist = findvideos(item)

                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError,e:
        import sys
        for line in sys.exc_info():
            logger.error( "%s" % line )
        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %d , Razon: %s" %(e.reason[0],e.reason[1]))
            texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web"
            ok = ventana_error.ok ("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado     
        elif hasattr(e,'code'):
            logger.info("codigo de error HTTP : %d" %e.code)
            texto = (config.get_localized_string(30051) % e.code) # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok ("plugin", texto)    
Example #46
0
def check_addon_updates(verbose=False):
    logger.info()

    # Forzamos la actualización de los repos para facilitar la actualización del addon Alfa
    xbmc.executebuiltin('UpdateAddonRepos')
    
    ADDON_UPDATES_JSON = 'https://extra.alfa-addon.com/addon_updates/updates.json'
    ADDON_UPDATES_ZIP = 'https://extra.alfa-addon.com/addon_updates/updates.zip'

    try:
        get_ua_list()
    except:
        pass

    try:
        last_fix_json = os.path.join(config.get_runtime_path(), 'last_fix.json')   # información de la versión fixeada del usuario
        # Se guarda en get_runtime_path en lugar de get_data_path para que se elimine al cambiar de versión

        try:
            localfilename = os.path.join(config.get_data_path(), 'temp_updates.zip')
            if os.path.exists(localfilename): os.remove(localfilename)
        except:
            pass
        
        # Descargar json con las posibles actualizaciones
        # -----------------------------------------------
        data = httptools.downloadpage(ADDON_UPDATES_JSON, timeout=5).data
        if data == '': 
            logger.info('No se encuentran actualizaciones del addon')
            if verbose:
                dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente')
            check_update_to_others(verbose=verbose)                             # Comprueba las actualuzaciones de otros productos
            return False

        data = jsontools.load(data)
        if 'addon_version' not in data or 'fix_version' not in data: 
            logger.info('No hay actualizaciones del addon')
            if verbose:
                dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente')
            check_update_to_others(verbose=verbose)                             # Comprueba las actualuzaciones de otros productos
            return False

        # Comprobar versión que tiene instalada el usuario con versión de la actualización
        # --------------------------------------------------------------------------------
        current_version = config.get_addon_version(with_fix=False, from_xml=True)
        if current_version != data['addon_version']:
            logger.info('No hay actualizaciones para la versión %s del addon' % current_version)
            if verbose:
                dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente')
            check_update_to_others(verbose=verbose)                             # Comprueba las actualuzaciones de otros productos
            return False

        if os.path.exists(last_fix_json):
            try:
                lastfix =  {} 
                lastfix = jsontools.load(open(last_fix_json, "r").read())
                if lastfix['addon_version'] == data['addon_version'] and lastfix['fix_version'] == data['fix_version']:
                    logger.info('Ya está actualizado con los últimos cambios. Versión %s.fix%d' % (data['addon_version'], data['fix_version']))
                    if verbose:
                        dialog_notification('Alfa ya está actualizado', 'Versión %s.fix%d' % (data['addon_version'], data['fix_version']))
                    check_update_to_others(verbose=verbose)                     # Comprueba las actualuzaciones de otros productos
                    return False
            except:
                if lastfix:
                    logger.error('last_fix.json: ERROR en: ' + str(lastfix))
                else:
                    logger.error('last_fix.json: ERROR desconocido')
                lastfix =  {}

        # Descargar zip con las actualizaciones
        # -------------------------------------

        downloadtools.downloadfile(ADDON_UPDATES_ZIP, localfilename, silent=True)
        
        # Descomprimir zip dentro del addon
        # ---------------------------------
        try:
            unzipper = ziptools.ziptools()
            unzipper.extract(localfilename, config.get_runtime_path())
        except:
            xbmc.executebuiltin('Extract("%s", "%s")' % (localfilename, config.get_runtime_path()))
            time.sleep(1)
        
        # Borrar el zip descargado
        # ------------------------
        try:
            os.remove(localfilename)
        except:
            pass
        
        # Si es PY3 se actualizan los módulos marshal
        if PY3:
            from platformcode.custom_code import marshal_check
            marshal_check()
        
        # Guardar información de la versión fixeada
        # -----------------------------------------
        if 'files' in data: data.pop('files', None)
            
        open(last_fix_json, "w").write(jsontools.dump(data))
        
        logger.info('Addon actualizado correctamente a %s.fix%d' % (data['addon_version'], data['fix_version']))
        if verbose:
            dialog_notification('Alfa actualizado a', 'Versión %s.fix%d' % (data['addon_version'], data['fix_version']))
        
        check_update_to_others(verbose=verbose)                                 # Comprueba las actualuzaciones de otros productos
        return True

    except:
        logger.error('Error al comprobar actualizaciones del addon!')
        logger.error(traceback.format_exc())
        if verbose:
            dialog_notification('Alfa actualizaciones', 'Error al comprobar actualizaciones')
        check_update_to_others(verbose=verbose)                                 # Comprueba las actualuzaciones de otros productos
        return False
Example #47
0
def download_all_episodes(item, channel, first_episode="", silent=False):
    logger.info("[launcher.py] download_all_episodes, show=" + item.show +
                " item=" + item.tostring())
    show_title = item.show

    # Obtiene el listado desde el que se llamó
    action = item.action

    exec "episode_itemlist = channel." + action + "(item)"
    from servers import servertools
    from core import downloadtools
    from core import scrapertools

    best_server = "streamcloud"
    worst_server = "moevideos"

    # Para cada episodio
    if first_episode == "":
        empezar = True
    else:
        empezar = False

    for episode_item in episode_itemlist:
        # Si XBMC se está cerrando, cancela
        try:
            if xbmc.abortRequested:
                logger.error(
                    "[launcher.py] download_all_episodes XBMC Abort requested")
                return -1
        except:
            pass

        # Si es la opción de descargar, la de "Opciones de la serie" o la de paginación, las ignora
        if episode_item.action.startswith(
                "download_all_episodes") or episode_item.action.startswith(
                    "serie_options") or episode_item.action.startswith(action):
            continue

        logger.info("[launcher.py] download_all_episodes, episode=" +
                    episode_item.title)
        try:
            episode_title = scrapertools.get_match(episode_item.title,
                                                   "(\d+x\d+)")
        except:
            episode_title = episode_item.title

        if item.channel == "rtve":
            episode_title = re.compile("\(.*?\)",
                                       re.DOTALL).sub("",
                                                      episode_title).strip()

        logger.info("[launcher.py] download_all_episodes, episode=" +
                    episode_title)

        if first_episode != "" and episode_title == first_episode:
            empezar = True

        if not empezar:
            continue

        # Extrae los mirrors
        mirrors_itemlist = [episode_item]  #channel.findvideos(episode_item)

        descargado = False

        new_mirror_itemlist_1 = []
        new_mirror_itemlist_2 = []
        new_mirror_itemlist_3 = []
        new_mirror_itemlist_4 = []
        new_mirror_itemlist_5 = []
        new_mirror_itemlist_6 = []

        for mirror_item in mirrors_itemlist:

            # Si está en español va al principio, si no va al final
            if "(Español)" in mirror_item.title:
                if best_server in mirror_item.title.lower():
                    new_mirror_itemlist_1.append(mirror_item)
                else:
                    new_mirror_itemlist_2.append(mirror_item)
            elif "(VOS)" in mirror_item.title:
                if best_server in mirror_item.title.lower():
                    new_mirror_itemlist_3.append(mirror_item)
                else:
                    new_mirror_itemlist_4.append(mirror_item)
            else:
                if best_server in mirror_item.title.lower():
                    new_mirror_itemlist_5.append(mirror_item)
                else:
                    new_mirror_itemlist_6.append(mirror_item)

        mirrors_itemlist = new_mirror_itemlist_1 + new_mirror_itemlist_2 + new_mirror_itemlist_3 + new_mirror_itemlist_4 + new_mirror_itemlist_5 + new_mirror_itemlist_6

        for mirror_item in mirrors_itemlist:
            logger.info("[launcher.py] download_all_episodes, mirror=" +
                        mirror_item.title)

            if "(Español)" in mirror_item.title:
                idioma = " (Español)"
            elif "(VOS)" in mirror_item.title:
                idioma = " (VOS)"
            elif "(VO)" in mirror_item.title:
                idioma = " (VO)"
            else:
                idioma = ""
            logger.info(
                "[launcher.py] download_all_episodes, downloading mirror")

            if hasattr(channel, 'play'):
                video_items = channel.play(mirror_item)
            else:
                video_items = [mirror_item]

            if len(video_items) > 0:
                video_item = video_items[0]

                # Comprueba que esté disponible
                video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
                    video_item.server,
                    video_item.url,
                    video_password="",
                    muestra_dialogo=False)

                # Lo añade a la lista de descargas
                if puedes:
                    logger.info(
                        "[launcher.py] download_all_episodes, downloading mirror started..."
                    )
                    # El vídeo de más calidad es el último
                    mediaurl = video_urls[len(video_urls) - 1][1]

                    if video_item.server != "directo":
                        filetitle = show_title + " " + episode_title + idioma + " [" + video_item.server + "]"
                    else:
                        filetitle = show_title + " " + episode_title + idioma + " [" + item.channel + "]"

                    # Genera el NFO
                    nfofilepath = downloadtools.getfilefromtitle(
                        "sample.nfo", filetitle)
                    outfile = open(nfofilepath, "w")
                    outfile.write("<movie>\n")
                    outfile.write("<title>(" + filetitle + ")</title>\n")
                    outfile.write("<originaltitle></originaltitle>\n")
                    outfile.write("<rating>0.000000</rating>\n")
                    outfile.write("<year>2009</year>\n")
                    outfile.write("<top250>0</top250>\n")
                    outfile.write("<votes>0</votes>\n")
                    outfile.write("<outline></outline>\n")
                    outfile.write("<plot>" + episode_item.plot + "</plot>\n")
                    outfile.write("<tagline></tagline>\n")
                    outfile.write("<runtime></runtime>\n")
                    outfile.write("<thumb></thumb>\n")
                    outfile.write("<mpaa>Not available</mpaa>\n")
                    outfile.write("<playcount>0</playcount>\n")
                    outfile.write("<watched>false</watched>\n")
                    outfile.write("<id>tt0432337</id>\n")
                    outfile.write("<filenameandpath></filenameandpath>\n")
                    outfile.write("<trailer></trailer>\n")
                    outfile.write("<genre></genre>\n")
                    outfile.write("<credits></credits>\n")
                    outfile.write("<director></director>\n")
                    outfile.write("<actor>\n")
                    outfile.write("<name></name>\n")
                    outfile.write("<role></role>\n")
                    outfile.write("</actor>\n")
                    outfile.write("</movie>")
                    outfile.flush()
                    outfile.close()
                    logger.info("core.descargas Creado fichero NFO")

                    # Descarga el thumbnail
                    if episode_item.thumbnail != "":
                        logger.info("core.descargas thumbnail=" +
                                    episode_item.thumbnail)
                        thumbnailfile = downloadtools.getfilefromtitle(
                            episode_item.thumbnail, filetitle)
                        thumbnailfile = thumbnailfile[:-4] + ".tbn"
                        logger.info("core.descargas thumbnailfile=" +
                                    thumbnailfile)
                        try:
                            downloadtools.downloadfile(episode_item.thumbnail,
                                                       thumbnailfile)
                            logger.info("core.descargas Thumbnail descargado")
                        except:
                            logger.info(
                                "core.descargas error al descargar thumbnail")
                            for line in sys.exc_info():
                                logger.error("%s" % line)

                    # Descarga el vídeo
                    devuelve = downloadtools.downloadbest(video_urls,
                                                          filetitle,
                                                          continuar=False,
                                                          silent=silent)

                    if devuelve == 0:
                        logger.info(
                            "[launcher.py] download_all_episodes, download ok")
                        descargado = True
                        break
                    elif devuelve == -1:
                        try:
                            import xbmcgui
                            advertencia = xbmcgui.Dialog()
                            resultado = advertencia.ok("plugin",
                                                       "Descarga abortada")
                        except:
                            pass
                        return
                    else:
                        logger.info(
                            "[launcher.py] download_all_episodes, download error, try another mirror"
                        )
                        break

                else:
                    logger.info(
                        "[launcher.py] download_all_episodes, downloading mirror not available... trying next"
                    )

        if not descargado:
            logger.info(
                "[launcher.py] download_all_episodes, EPISODIO NO DESCARGADO "
                + episode_title)
Example #48
0
def downloadall(item):
    logger.info("[descargas.py] downloadall")

    # Lee la lista de ficheros
    if usingsamba:
        ficheros = samba.get_files(DOWNLOAD_LIST_PATH)
    else:
        ficheros = os.listdir(DOWNLOAD_LIST_PATH)

    logger.info("[descargas.py] numero de ficheros=%d" % len(ficheros))

    # La ordena
    ficheros.sort()
    
    # Crea un listado con las entradas de favoritos
    for fichero in ficheros:
        # El primer video de la lista
        logger.info("[descargas.py] fichero="+fichero)

        if fichero != "error" and fichero != ".DS_Store":
            # Descarga el vídeo
            try:
                # Lee el bookmark
                canal, titulo, thumbnail, plot, server, url, fulltitle = \
                    favoritos.readbookmark(fichero, DOWNLOAD_LIST_PATH)
                logger.info("[descargas.py] url="+url)

                # Averigua la URL del vídeo
                video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(server, url, "", False)

                # La última es la de mayor calidad, lo mejor para la descarga
                mediaurl = video_urls[len(video_urls)-1][1]
                logger.info("[descargas.py] mediaurl="+mediaurl)

                # Genera el NFO
                nfofilepath = downloadtools.getfilefromtitle("sample.nfo", fulltitle)
                outfile = open(nfofilepath, "w")
                outfile.write("<movie>\n")
                outfile.write("<title>("+fulltitle+")</title>\n")
                outfile.write("<originaltitle></originaltitle>\n")
                outfile.write("<rating>0.000000</rating>\n")
                outfile.write("<year>2009</year>\n")
                outfile.write("<top250>0</top250>\n")
                outfile.write("<votes>0</votes>\n")
                outfile.write("<outline></outline>\n")
                outfile.write("<plot>"+plot+"</plot>\n")
                outfile.write("<tagline></tagline>\n")
                outfile.write("<runtime></runtime>\n")
                outfile.write("<thumb></thumb>\n")
                outfile.write("<mpaa>Not available</mpaa>\n")
                outfile.write("<playcount>0</playcount>\n")
                outfile.write("<watched>false</watched>\n")
                outfile.write("<id>tt0432337</id>\n")
                outfile.write("<filenameandpath></filenameandpath>\n")
                outfile.write("<trailer></trailer>\n")
                outfile.write("<genre></genre>\n")
                outfile.write("<credits></credits>\n")
                outfile.write("<director></director>\n")
                outfile.write("<actor>\n")
                outfile.write("<name></name>\n")
                outfile.write("<role></role>\n")
                outfile.write("</actor>\n")
                outfile.write("</movie>")
                outfile.flush()
                outfile.close()
                logger.info("[descargas.py] Creado fichero NFO")
                
                # Descarga el thumbnail
                if thumbnail != "":
                    logger.info("[descargas.py] thumbnail="+thumbnail)
                    thumbnailfile = downloadtools.getfilefromtitle(thumbnail, fulltitle)
                    thumbnailfile = thumbnailfile[:-4] + ".tbn"
                    logger.info("[descargas.py] thumbnailfile="+thumbnailfile)
                    try:
                        downloadtools.downloadfile(thumbnail, thumbnailfile)
                        logger.info("[descargas.py] Thumbnail descargado")
                    except:
                        logger.info("[descargas.py] error al descargar thumbnail")
                        for line in sys.exc_info():
                            logger.error("%s" % line)
                
                # Descarga el video
                dev = downloadtools.downloadbest(video_urls, fulltitle)
                if dev == -1:
                    # El usuario ha cancelado la descarga
                    logger.info("[descargas.py] Descarga cancelada")
                    return
                elif dev == -2:
                    # Error en la descarga, lo mueve a ERROR y continua con el siguiente
                    logger.info("[descargas.py] ERROR EN DESCARGA DE "+fichero)
                    if not usingsamba:
                        origen = os.path.join(DOWNLOAD_LIST_PATH, fichero)
                        destino = os.path.join(ERROR_PATH, fichero)
                        import shutil
                        shutil.move(origen, destino)
                    else:
                        favoritos.savebookmark(canal, titulo, url, thumbnail, server, plot, fulltitle, ERROR_PATH)
                        favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)
                else:
                    logger.info("[descargas.py] Video descargado")
                    # Borra el bookmark e itera para obtener el siguiente video
                    filepath = os.path.join(DOWNLOAD_LIST_PATH, fichero)
                    if usingsamba:
                        os.remove(filepath)
                    else:
                        favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)
                    logger.info("[descargas.py] "+fichero+" borrado")
            except:
                logger.info("[descargas.py] ERROR EN DESCARGA DE "+fichero)
                import sys
                for line in sys.exc_info():
                    logger.error("%s" % line)
                if not usingsamba:
                    origen = os.path.join(DOWNLOAD_LIST_PATH, fichero)
                    destino = os.path.join(ERROR_PATH, fichero)
                    import shutil
                    shutil.move(origen, destino)
                else:
                    favoritos.savebookmark(canal, titulo, url, thumbnail, server, plot, fulltitle, ERROR_PATH)
                    favoritos.deletebookmark(fichero, DOWNLOAD_LIST_PATH)
def set_content(content_type, silent=False):
    """
    Procedimiento para auto-configurar la biblioteca de kodi con los valores por defecto
    @type content_type: str ('CINE' o 'SERIES')
    @param content_type: tipo de contenido para configurar, series o peliculas
    """
    if config.is_xbmc():
        continuar = True
        msg_text = ""
        librarypath = config.get_setting("librarypath")

        if content_type == 'CINE':
            if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'):
                if not silent:
                    # Preguntar si queremos instalar metadata.themoviedb.org
                    install = platformtools.dialog_yesno("The Movie Database",
                                                         "TheMovieDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.themoviedb.org
                        xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True)
                        logger.info("Instalado el Scraper de películas de TheMovieDB")
                    except:
                        pass

                continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'))
                if not continuar:
                    msg_text = "The Movie Database no instalado."

        else: # SERIES
            # Instalar The TVDB
            if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'):
                if not silent:
                    # Preguntar si queremos instalar metadata.tvdb.com
                    install = platformtools.dialog_yesno("The TVDB",
                                                         "The TVDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.tvdb.com
                        xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True)
                        logger.info("Instalado el Scraper de series de The TVDB")
                    except:
                        pass

                continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'))
                if not continuar:
                    msg_text = "The TVDB no instalado."

            # Instalar TheMovieDB
            if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                continuar = False
                if not silent:
                    # Preguntar si queremos instalar metadata.tvshows.themoviedb.org
                    install = platformtools.dialog_yesno("The Movie Database",
                                                         "TheMovieDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.tvshows.themoviedb.org
                        # 1º Probar desde el repositorio ...
                        xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True)
                        if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                                # ...si no funciona descargar e instalar desde la web
                                url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip"
                                path_down = xbmc.translatePath(
                                    "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip")
                                path_unzip = xbmc.translatePath("special://home/addons/")
                                header = ("User-Agent",
                                          "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013")

                                from core import downloadtools
                                from core import ziptools

                                downloadtools.downloadfile(url, path_down, continuar=True, headers=[header])
                                unzipper = ziptools.ziptools()
                                unzipper.extract(path_down, path_unzip)
                                xbmc.executebuiltin('UpdateLocalAddons')

                        strSettings = '<settings>\n' \
                                      '    <setting id="fanart" value="true" />\n' \
                                      '    <setting id="keeporiginaltitle" value="false" />\n' \
                                      '    <setting id="language" value="it" />\n' \
                                      '</settings>'
                        path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml")
                        tv_themoviedb_addon_path = filetools.dirname(path_settings)
                        if not filetools.exists(tv_themoviedb_addon_path):
                            filetools.mkdir(tv_themoviedb_addon_path)
                        if filetools.write(path_settings,strSettings):
                            continuar = True

                    except:
                        pass

                continuar = (install and continuar)
                if not continuar:
                    msg_text = "The Movie Database non installato."

        idPath = 0
        idParentPath = 0
        strPath = ""
        if continuar:
            continuar = False

            # Buscamos el idPath
            sql = 'SELECT MAX(idPath) FROM path'
            nun_records, records = execute_sql_kodi(sql)
            if nun_records == 1:
                idPath = records[0][0] + 1

            sql_librarypath = librarypath
            if sql_librarypath.startswith("special://"):
                sql_librarypath = sql_librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/')
                sep = '/'
            elif sql_librarypath.startswith("smb://"):
                sep = '/'
            else:
                sep = os.sep

            if not sql_librarypath.endswith(sep):
                sql_librarypath += sep

            # Buscamos el idParentPath
            sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_librarypath
            nun_records, records = execute_sql_kodi(sql)
            if nun_records == 1:
                idParentPath = records[0][0]
                librarypath = records[0][1][:-1]
                continuar = True
            else:
                # No existe librarypath en la BD: la insertamos
                sql_librarypath = librarypath
                if not sql_librarypath.endswith(sep):
                    sql_librarypath += sep

                sql = 'INSERT INTO path (idPath, strPath,  scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \
                      '(%s, "%s", 0, 0, 0, 0)' % (idPath, sql_librarypath)
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    continuar = True
                    idParentPath = idPath
                    idPath += 1
                else:
                    msg_text = "Omesso di impostare LibraryPath in BD"

        if continuar:
            continuar = False

            # Fijamos strContent, strScraper, scanRecursive y strSettings
            if content_type == 'CINE':
                strContent = 'movies'
                strScraper = 'metadata.themoviedb.org'
                scanRecursive = 2147483647
                strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \
                              "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \
                              "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \
                              "<setting id='trailer' value='true' /></settings>"
                strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per i film ?"
                if not librarypath.endswith(sep):
                    librarypath += sep
                strPath = librarypath + config.get_setting("folder_movies") + sep
            else:
                strContent = 'tvshows'
                strScraper = 'metadata.tvdb.com'
                scanRecursive = 0
                strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \
                              "<setting id='absolutenumber' value='false' />" \
                              "<setting id='dvdorder' value='false' />" \
                              "<setting id='fallback' value='true' />" \
                              "<setting id='fanart' value='true' />" \
                              "<setting id='language' value='it' /></settings>"
                strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per le serie ?"
                if not librarypath.endswith(sep):
                    librarypath += sep
                strPath = librarypath + config.get_setting("folder_tvshows") + sep

            logger.info("%s: %s" % (content_type, strPath))
            # Comprobamos si ya existe strPath en la BD para evitar duplicados
            sql = 'SELECT idPath FROM path where strPath="%s"' % strPath
            nun_records, records = execute_sql_kodi(sql)
            sql = ""
            if nun_records == 0:
                # Insertamos el scraper
                sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \
                      'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \
                      '"%s", 0, 0, %s)' % (
                      idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath)
            else:
                if not silent:
                    # Preguntar si queremos configurar themoviedb.org como opcion por defecto
                    actualizar = platformtools.dialog_yesno("The TVDB", strActualizar)
                else:
                    actualizar = True

                if actualizar:
                    # Actualizamos el scraper
                    idPath = records[0][0]
                    sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \
                          'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath)

            if sql:
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    continuar = True

            if not continuar:
                msg_text = "Omesso impostare LibraryPath in BD"


        if not continuar:
            heading = "Biblioteca %s no configurada" % content_type
        elif content_type == 'SERIES' and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
            heading = "Biblioteca %s configurata" % content_type
            msg_text = "Riavviare Kodi per attuare le modifiche."
        else:
            heading = "Biblioteca %s configurata" % content_type
            msg_text = "Libreria di Kodi configurata correttamente."
        platformtools.dialog_notification(heading, msg_text, icon=1, time=10000)
        logger.info("%s: %s" % (heading,msg_text))