Ejemplo n.º 1
0
    def get(self, itemid):
        # try:
        item_key = ndb.Key(urlsafe=itemid)
        item = item_key.get()
        if item is not None:
            exec "from tvalacarta.channels import "+item.channel+" as channelmodule"
            if item.action == "play":
                if hasattr(channelmodule, 'play'):
                    playitem = channelmodule.play(item)[0]
                else:
                    from servers import servertools
                    url = servertools.resolve_video_urls_for_playing(item.channel,item.url,item.password)
                    playitem = Item(url=url[0][0][1])
                template_values = {'item':playitem}
                template = JINJA_ENVIRONMENT.get_template('play.html')
                self.response.write(template.render(template_values))
            else:
                items = []
                method = getattr(channelmodule, item.action)
                items = method(item)

                if len(items) > 0:
                    ndb.put_multi(items)
                    template_values = {'items':items}
                    template = JINJA_ENVIRONMENT.get_template('item.html')
                    self.response.write(template.render(template_values))
                else:
                    self.response.write("webapp2.RequestHandler")
        else:
            self.redirect("/")
Ejemplo n.º 2
0
def download_url(url, titulo, server):

    url = url.replace("\\", "")

    print "Analizando enlace " + url

    # Averigua el servidor
    if server == "":
        itemlist = servertools.find_video_items(data=url)
        if len(itemlist) == 0:
            print "No se puede identificar el enlace"
            return

        item = itemlist[0]
        print "Es un enlace en " + item.server
    else:
        item = Item()
        item.server = server

    # Obtiene las URL de descarga
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
        item.server, url)
    if len(video_urls) == 0:
        print "No se ha encontrado nada para descargar"
        return

    # Descarga el de mejor calidad, como hace pelisalacarta
    print "Descargando..."
    print video_urls
    devuelve = downloadtools.downloadbest(video_urls, titulo, continuar=True)
Ejemplo n.º 3
0
def test_download_url():

    url = "https://mega.co.nz/#!AxRliabL!LZzZjm3f7Qi1t_pQ37MxZVh1TLsO215Y8Er6m9hOQ0I"
    titulo = "escuela_de_bomberos(thor).rar"

    print "Analizando enlace "+url

    # Averigua el servidor
    itemlist = servertools.find_video_items(data=url)
    if len(url)==0:
        print "No se puede identificar el enlace"
        return

    item = itemlist[0]
    print "Es un enlace en "+item.server

    # Obtiene las URL de descarga
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(item.server,url)
    if len(video_urls)==0:
        print "No se ha encontrado nada para descargar"
        return

    # Descarga el de mejor calidad, como hace pelisalacarta
    print video_urls
    devuelve = downloadtools.downloadbest(video_urls,titulo,continuar=False)
Ejemplo n.º 4
0
def download_url(url,titulo,server):

    url = url.replace("\\","")

    print "Analizando enlace "+url

    # Averigua el servidor
    if server=="":
        itemlist = servertools.find_video_items(data=url)
        if len(itemlist)==0:
            print "No se puede identificar el enlace"
            return

        item = itemlist[0]
        print "Es un enlace en "+item.server
    else:
        item = Item()
        item.server = server

    # Obtiene las URL de descarga
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(item.server,url)
    if len(video_urls)==0:
        print "No se ha encontrado nada para descargar"
        return

    # Descarga el de mejor calidad, como hace pelisalacarta
    print "Descargando..."
    print video_urls
    devuelve = downloadtools.downloadbest(video_urls,titulo,continuar=True)
Ejemplo n.º 5
0
def test_download_url():

    url = "https://mega.co.nz/#!AxRliabL!LZzZjm3f7Qi1t_pQ37MxZVh1TLsO215Y8Er6m9hOQ0I"
    titulo = "escuela_de_bomberos(thor).rar"

    print "Analizando enlace " + url

    # Averigua el servidor
    itemlist = servertools.find_video_items(data=url)
    if len(url) == 0:
        print "No se puede identificar el enlace"
        return

    item = itemlist[0]
    print "Es un enlace en " + item.server

    # Obtiene las URL de descarga
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
        item.server, url)
    if len(video_urls) == 0:
        print "No se ha encontrado nada para descargar"
        return

    # Descarga el de mejor calidad, como hace pelisalacarta
    print video_urls
    devuelve = downloadtools.downloadbest(video_urls, titulo, continuar=False)
Ejemplo n.º 6
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
Ejemplo n.º 7
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
Ejemplo n.º 8
0
def menu_video(item):
    itemlist = []
    logger.info("menu_video url="+item.url+", server="+item.server+", fulltitle="+item.fulltitle)

    from servers import servertools
    video_urls,puede,motivo = servertools.resolve_video_urls_for_playing( item.server , item.url , video_password="" , muestra_dialogo=False)

    if puede:
        for video_url in video_urls:
            itemlist.append( Item(channel=item.channel, title="Ver "+video_url[0], url=video_url[1], action="play_video") )
        
        refered_item_encoded = urllib.quote(item.title.replace("|","-"))+"|"+urllib.quote(item.server)+"|"+urllib.quote(item.url)+"|"+urllib.quote(item.extra)
        
        itemlist.append( Item(channel=item.channel, title="Descargar",action="descargar",url=refered_item_encoded,fulltitle=urllib.quote(item.fulltitle) ) )
        
        if item.channel!="favoritos":
            itemlist.append( Item(channel=item.channel, title="Añadir a favoritos",action="add_to_favorites",url=refered_item_encoded,fulltitle=urllib.quote(item.fulltitle) ) )
        else:
            itemlist.append( Item(channel=item.channel, title="Quitar de favoritos",action="remove_from_favorites",url=refered_item_encoded,fulltitle=urllib.quote(item.fulltitle) ) )
        
        if item.channel!="descargas":
            itemlist.append( Item(channel=item.channel, title="Añadir a la lista de descargas",action="add_to_downloads",url=refered_item_encoded,fulltitle=urllib.quote(item.fulltitle) ) )
        else:
            if item.category=="errores":
                itemlist.append( Item(channel=item.channel, title="Quitar definitivamente de la lista de descargas",action="remove_from_error_downloads",url=refered_item_encoded ) )
                itemlist.append( Item(channel=item.channel, title="Pasar de nuevo a la lista de descargas",action="add_again_to_downloads",url=refered_item_encoded ) )
            else:
                itemlist.append( Item(channel=item.channel, title="Quitar de la lista de descargas",action="remove_from_downloads",url=refered_item_encoded ) )
    
        itemlist.append( Item(channel=item.channel, title="Enviar a jdownloader",action="send_to_jdownloader",url=refered_item_encoded ) )
        itemlist.append( Item(channel=item.channel, title="Buscar trailer",action="search_trailer",url=refered_item_encoded ) )
        if item.category=="wiideoteca":
            itemlist.append( Item(channel=item.channel, title="Marcar como Ultimo Episodio Visto",action="UltimoVisto",url=item.extra,fulltitle=item.fulltitle ) )

    # Si no puedes ver el vídeo te informa
    else:
        itemlist.append( Item(title="No puedes ver ese vídeo porque...") )
        if item.server!="":
            if "<br/>" in motivo:
                itemlist.append( Item(title=motivo.split("<br/>")[0]) )
                itemlist.append( Item(title=motivo.split("<br/>")[1]) )
                itemlist.append( Item(title=item.url) )
            else:
                itemlist.append( Item(title=motivo) )
                itemlist.append( Item(title=item.url) )
        else:
            itemlist.append( Item(title="El servidor donde está alojado no está") )
            itemlist.append( Item(title="soportado en pelisalacarta todavía") )
            itemlist.append( Item(title=item.url) )

    return itemlist
Ejemplo n.º 9
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)
Ejemplo n.º 10
0
def download_all_episodes(item):
    from servers import servertools
    from core import downloadtools
    from core import scrapertools

    # Esto es poco elegante...
    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if item.extra: action = item.extra
    if item.refered_action: action = item.refered_action
    if "###" in action:
        item.extra = action.split("###")[1]
        action = action.split("###")[0]

    #Importamos el canal
    channel = ImportarCanal(item.channel)

    #Ejecutamos la funcion
    exec "itemlist = channel." + action + "(item)"

    #Quitamos estos dos elementos de la lista (si los hay)
    for episodio in itemlist:
        if episodio.action == "add_serie_to_library" or episodio.action == "download_all_episodes":
            itemlist.remove(episodio)

    #Abrimos el dialogo
    pDialog = guitools.Dialog_Progress('pelisalacarta',
                                       'Descargando ' + item.show)

    for x, episodio in enumerate(itemlist):

        #Si se presiona cancelar, se cancela
        if pDialog.iscanceled():
            return
        #Extraemos la Temporada y el Episodio
        episodio.title = scrapertools.get_season_and_episode(episodio.title)

        #Actualizamos el progreso
        pDialog.Actualizar(((x) * 100) / len(itemlist),
                           'Descargando ' + item.show,
                           'Descargando episodio: ' + episodio.title)

        # Extrae los mirrors
        if hasattr(channel, 'findvideos'):
            mirrors_itemlist = channel.findvideos(episodio)
        else:
            mirrors_itemlist = findvideos(episodio, episodio.channel)

        descargado = False

        #Descarga el primer mirror que funcione
        for mirror_item in mirrors_itemlist:

            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 descarga
                if puedes:

                    # El vídeo de más calidad es el último
                    devuelve = downloadtools.downloadbest(
                        video_urls,
                        item.show + " " + episodio.title + " [" +
                        video_item.server + "]",
                        continuar=False)
                    if devuelve == 0:
                        logger.info(
                            "[launcher.py] download_all_episodes - Archivo Descargado"
                        )
                        descargado = True
                        break
                    elif devuelve == -1:
                        pDialog.Cerrar()
                        logger.info(
                            "[launcher.py] download_all_episodes - Descarga abortada"
                        )
                        guitools.Dialog_OK("pelisalacarta",
                                           "La descarga ha sido cancelada")
                        return
                    else:
                        continue
    pDialog.Cerrar()
Ejemplo n.º 11
0
def MenuVideo(item):
    if item.server == "": item.server = "directo"
    default_action = config.get_setting("default_action")
    itemlist = []

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    from servers import servertools
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
        item.server, item.url, item.password, True)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            itemlist.append(
                Item(title=config.get_localized_string(30151) + " " +
                     video_url[0],
                     url=video_url,
                     action="play_video"))

        if item.server == "local":
            itemlist.append(
                Item(title=config.get_localized_string(30164),
                     url=video_urls,
                     action="delete"))

        if not item.server == "local":
            itemlist.append(
                Item(title=config.get_localized_string(30153),
                     url=video_urls,
                     action="download"))  #"Descargar"

        if item.channel == "favoritos":
            itemlist.append(
                Item(title=config.get_localized_string(30154),
                     url=video_urls,
                     action="remove_from_favorites"))  #"Quitar de favoritos"

        if not item.channel == "favoritos":
            itemlist.append(
                Item(title=config.get_localized_string(30155),
                     url=video_urls,
                     action="add_to_favorites"))  #"Añadir a favoritos"

        if not item.channel == "library":
            itemlist.append(
                Item(title=config.get_localized_string(30161),
                     url=video_urls,
                     action="add_to_library"))  #"Añadir a Biblioteca"

        if item.channel == "library":
            itemlist.append(
                Item(title="Quitar de la Biblioteca",
                     url=video_urls,
                     action="remove_from_library"))  #"Añadir a Biblioteca"

        if not item.channel == "descargas":
            itemlist.append(
                Item(
                    title=config.get_localized_string(30157),
                    url=video_urls,
                    action="add_to_downloads"))  #"Añadir a lista de descargas"

        if item.channel == "descargas" and item.category == "errores":
            itemlist.append(
                Item(title=config.get_localized_string(30159),
                     url=video_urls,
                     action="remove_from_error_downloads")
            )  #"Borrar descarga definitivamente"
            itemlist.append(
                Item(title=config.get_localized_string(30160),
                     url=video_urls,
                     action="add_again_to_downloads")
            )  #"Pasar de nuevo a lista de descargas"

        if item.channel == "descargas" and item.category == "pendientes":
            itemlist.append(
                Item(title=config.get_localized_string(30156),
                     url=video_urls,
                     action="remove_from_downloads")
            )  #"Quitar de lista de descargas"

        if config.get_setting("jdownloader_enabled") == "true":
            itemlist.append(
                Item(title=config.get_localized_string(30158),
                     url=video_urls,
                     action="send_to_jdownloader"))  #"Enviar a JDownloader"

        if config.get_setting("pyload_enabled") == "true":
            itemlist.append(
                Item(title=config.get_localized_string(30158).replace(
                    "jDownloader", "pyLoad"),
                     url=video_urls,
                     action="send_to_pyLoad"))  #"Enviar a pyLoad"

        if not item.channel in ["trailertools", "ecarteleratrailers"]:
            itemlist.append(
                Item(title=config.get_localized_string(30162),
                     url=video_urls,
                     action="search_trailer"))  # "Buscar Trailer"

    else:
        if item.server != "":
            guitools.Dialog_OK("No puedes ver ese vídeo porque...",
                               motivo.replace("<br/>", "\n") + "\n" + item.url)

        else:
            guitools.Dialog_OK(
                "No puedes ver ese vídeo porque...",
                "El servidor donde está alojado no está\nsoportado en pelisalacarta todavía\n"
                + url)

            if item.channel == "favoritos":
                itemlist.append(
                    Item(title=config.get_localized_string(30154),
                         url=video_urls,
                         action="remove_from_favorites")
                )  #"Quitar de favoritos"
            if item.channel == "library":
                itemlist.append(
                    Item(title="Quitar de la Biblioteca",
                         url=video_urls,
                         action="remove_from_library"))  #"Añadir a Biblioteca"

            if item.channel == "descargas" and item.category == "errores":
                itemlist.append(
                    Item(title=config.get_localized_string(30159),
                         url=video_urls,
                         action="remove_from_error_downloads")
                )  #"Borrar descarga definitivamente"
            if item.channel == "descargas" and not item.category == "errores":
                itemlist.append(
                    Item(title=config.get_localized_string(30156),
                         url=video_urls,
                         action="remove_from_downloads")
                )  #"Quitar de lista de descargas"

    return itemlist
Ejemplo n.º 12
0
def play_video(item,desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False):
    logger.info('tvalacarta.platformcode.xbmctools add_new_video item='+item.tostring())
    
    if item.url.startswith("http://"):
        item.url = item.url.replace(" ","%20")

    try:
        item.server = item.server.lower()
    except:
        item.server = ""

    if item.server=="":
        item.server="directo"

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action="+default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode")=="0" and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(item.server , item.url , item.video_password , item.muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            opciones.append(config.get_localized_string(30151) + " " + video_url[0])

        if item.server=="local":
            opciones.append(config.get_localized_string(30164))
        else:
            opcion = config.get_localized_string(30153)
            opciones.append(opcion) # "Descargar"
    
            if item.channel=="favoritos": 
                opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"
            else:
                opciones.append(config.get_localized_string(30155)) # "Añadir a favoritos"
        
            #if not strmfile:
            #    opciones.append(config.get_localized_string(30161)) # "Añadir a Biblioteca"
        
            if item.channel!="descargas":
                opciones.append(config.get_localized_string(30157)) # "Añadir a lista de descargas"
            else:
                if item.category=="errores":
                    opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
                    opciones.append(config.get_localized_string(30160)) # "Pasar de nuevo a lista de descargas"
                else:
                    opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"

            #opciones.append(config.get_localized_string(30158)) # "Enviar a JDownloader"

        if default_action=="3":
            seleccion = len(opciones)-1
    
    # Si no puedes ver el vídeo te informa
    else:
        alert_no_puedes_ver_video(item.server,"",motivo)

        if item.channel=="favoritos": 
            opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"

        if item.channel=="descargas":
            if item.category=="errores":
                opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
        
        if len(opciones)==0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action=="0":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163), opciones) # "Elige una opción"
        #dia.close()
    elif default_action=="1":
        seleccion = len(video_urls)-1
    elif default_action=="2":
        seleccion = 0
    elif default_action=="3":
        seleccion = seleccion
    else:
        seleccion=0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC 
    if seleccion==-1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem( item.title, iconImage="DefaultVideo.png", thumbnailImage=item.thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),False,listitem)
        return

    if opciones[seleccion]==config.get_localized_string(30158): # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools
        data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+item.url+ " " +item.thumbnail)
        return

    elif opciones[seleccion]==config.get_localized_string(30164): # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os

        os.remove( item.url )

        if os.path.exists(item.url[:-4]+".tbn"):
            os.remove( item.url[:-4]+".tbn" )

        if os.path.exists(item.url[:-4]+".nfo"):
            os.remove( item.url[:-4]+".nfo" )

        xbmc.executebuiltin( "Container.Refresh" )
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion])>2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0

        if len(video_urls[seleccion])>3:
            use_download_and_play = (video_urls[seleccion][3]=="download_and_play")
        else:
            use_download_and_play = False

        view = True

    # Descargar
    elif opciones[seleccion]==config.get_localized_string(30153): # "Descargar"
        
        # El vídeo de más calidad es el primero
        mediaurl = video_urls[0][1]
        
        from core import downloadtools
        keyboard = xbmc.Keyboard(item.fulltitle)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            title = keyboard.getText()
            downloadtools.downloadtitle(mediaurl,title)
        return

    elif opciones[seleccion]==config.get_localized_string(30154): #"Quitar de favoritos"
        from channels import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30102) , item.title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30159): #"Borrar descarga definitivamente"
        from channels import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30106)) # 'Se ha quitado de la lista'
        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30160): #"Pasar de nuevo a lista de descargas":
        from channels import descargas
        descargas.mover_descarga_error_a_pendiente(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30107)) # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30155): #"Añadir a favoritos":
        from channels import favoritos
        from core import downloadtools

        keyboard = xbmc.Keyboard(item.fulltitle)
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=title,url=item.url,thumbnail=item.thumbnail,server=item.server,plot=item.plot,fulltitle=item.title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion]==config.get_localized_string(30156): #"Quitar de lista de descargas":
        from channels import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus( item.extra )))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30106)) # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30157): #"Añadir a lista de descargas":

        from channels import descargas
        from core import downloadtools

        if item.show<>"":
            filename = item.show+" - "+item.title
        elif item.show_title<>"":
            filename = item.show_title+" - "+item.title
        else:
            filename = item.title

        keyboard = xbmc.Keyboard(filename)
        keyboard.doModal()
        if keyboard.isConfirmed():
            filename = keyboard.getText()
            descargas.savebookmark(titulo=filename,url=item.url,thumbnail=item.thumbnail,server=item.server,plot=item.plot,fulltitle=filename)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30101) , filename , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30161): #"Añadir a Biblioteca":  # Library
        from platformcode.xbmc import library
        titulo = item.fulltitle
        if item.fulltitle=="":
            titulo = item.title
        library.savelibrary(titulo , item.url , item.thumbnail , item.server , item.plot , canal=item.channel , category=item.category , Serie=item.Serie)
        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.fulltitle , config.get_localized_string(30135)) # 'se ha añadido a la lista de descargas'
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time>0:
    
        continuar = handle_wait(wait_time,server,"Cargando vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        xlistitem = getLibraryInfo(mediaurl)
    else:
        try:
            xlistitem = xbmcgui.ListItem( item.title, iconImage="DefaultVideo.png", thumbnailImage=item.thumbnail, path=mediaurl)
        except:
            xlistitem = xbmcgui.ListItem( item.title, iconImage="DefaultVideo.png", thumbnailImage=item.thumbnail)
        xlistitem.setInfo( "video", { "Title": item.title, "Plot" : item.plot , "Studio" : item.channel , "Genre" : item.category } )

    # Lanza el reproductor
    if strmfile: #Si es un fichero strm no hace falta el play
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,xlistitem)
        #if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        #    logger.info("tvalacarta.platformcode.xbmctools Con subtitulos")
        #    setSubtitles()
    else:
        if use_download_and_play or config.get_setting("player_mode")=="3":
            import download_and_play

            # El canal exige usar download_and_play, pero el usuario no lo ha elegido -> le quitamos los diálogos
            if use_download_and_play and config.get_setting("player_mode")!="3":
                download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") , show_dialog=False )
            else:
                download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") )
            return

        elif config.get_setting("player_mode")=="0":
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()
            playlist.add( mediaurl, xlistitem )

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info("tvalacarta.platformcode.xbmctools playersettings="+playersettings)
        
            if config.get_system_platform() == "xbox":
                player_type = xbmc.PLAYER_CORE_AUTO
                if playersettings == "0":
                    player_type = xbmc.PLAYER_CORE_AUTO
                    logger.info("tvalacarta.platformcode.xbmctools PLAYER_CORE_AUTO")
                elif playersettings == "1":
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.info("tvalacarta.platformcode.xbmctools PLAYER_CORE_MPLAYER")
                elif playersettings == "2":
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.info("tvalacarta.platformcode.xbmctools PLAYER_CORE_DVDPLAYER")
                xbmcPlayer = xbmc.Player( player_type )
            else:
                xbmcPlayer = xbmc.Player()
        
            xbmcPlayer.play(playlist)

        elif config.get_setting("player_mode")=="1":
            #xlistitem.setProperty('IsPlayable', 'true')
            #xlistitem.setProperty('path', mediaurl)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=mediaurl))
        
        elif config.get_setting("player_mode")=="2":
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )

    if (config.get_setting("subtitulo") == "true") and view:
        from core import subtitletools
        wait2second()
        subtitletools.set_Subtitle()
        if subtitle!="":
            xbmc.Player().setSubtitles(subtitle)
Ejemplo n.º 13
0
def play_video(item,desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False):
    from servers import servertools
    import sys
    import xbmcgui,xbmc
    
    logger.info("[xbmctools.py] play_video")
    logger.info(item.tostring())

    try:
        item.server = item.server.lower()
    except:
        item.server = ""

    if item.server=="":
        item.server="directo"

    try:
        from core import descargas
        download_enable=True
    except:
        download_enable=False

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action="+default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode")=="0" and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(item.server,item.url,item.password,muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        
        for video_url in video_urls:
            opciones.append(config.get_localized_string(30151) + " " + video_url[0])

        if item.server=="local":
            opciones.append(config.get_localized_string(30164))
        else:
            if download_enable:
                opcion = config.get_localized_string(30153)
                opciones.append(opcion) # "Descargar"
    
            if item.channel=="favoritos": 
                opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"
            else:
                opciones.append(config.get_localized_string(30155)) # "Añadir a favoritos"
        
            if not strmfile:
                opciones.append(config.get_localized_string(30161)) # "Añadir a Biblioteca"
        
            if download_enable:
                if item.channel!="descargas":
                    opciones.append(config.get_localized_string(30157)) # "Añadir a lista de descargas"
                else:
                    if item.category=="errores":
                        opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
                        opciones.append(config.get_localized_string(30160)) # "Pasar de nuevo a lista de descargas"
                    else:
                        opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
    
            if config.get_setting("jdownloader_enabled")=="true":
                opciones.append(config.get_localized_string(30158)) # "Enviar a JDownloader"
            if config.get_setting("pyload_enabled")=="true":
                opciones.append(config.get_localized_string(30158).replace("jDownloader","pyLoad")) # "Enviar a pyLoad"

        if default_action=="3":
            seleccion = len(opciones)-1
    
        # Busqueda de trailers en youtube    
        if not item.channel in ["Trailer","ecarteleratrailers"]:
            opciones.append(config.get_localized_string(30162)) # "Buscar Trailer"

    # Si no puedes ver el vídeo te informa
    else:
        import xbmcgui
        if item.server!="":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok( "No puedes ver ese vídeo porque...",motivo.split("<br/>")[0],motivo.split("<br/>")[1],item.url)
            else:
                resultado = advertencia.ok( "No puedes ver ese vídeo porque...",motivo,item.url)
        else:
            resultado = advertencia.ok( "No puedes ver ese vídeo porque...","El servidor donde está alojado no está","soportado en pelisalacarta todavía",item.url)

        if item.channel=="favoritos": 
            opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"

        if item.channel=="descargas":
            if item.category=="errores":
                opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
        
        if len(opciones)==0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action=="0": # and server!="torrent":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163), opciones) # "Elige una opción"
        #dia.close()
        '''
        elif default_action=="0" and server=="torrent":
            advertencia = xbmcgui.Dialog()
            logger.info("video_urls[0]="+str(video_urls[0][1]))
            if puedes and ('"status":"COMPLETED"' in video_urls[0][1] or '"percent_done":100' in video_urls[0][1]):
                listo  = "y está listo para ver"
            else:
                listo = "y se está descargando"
            resultado = advertencia.ok( "Torrent" , "El torrent ha sido añadido a la lista" , listo )
            seleccion=-1
        '''
    elif default_action=="1":
        seleccion = 0
    elif default_action=="2":
        seleccion = len(video_urls)-1
    elif default_action=="3":
        seleccion = seleccion
    else:
        seleccion=0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC 
    if seleccion==-1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem( item.title, iconImage="DefaultVideo.png", thumbnailImage=item.thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),False,listitem)    # JUR Added
        #if config.get_setting("subtitulo") == "true":
        #    config.set_setting("subtitulo", "false")
        return

    if opciones[seleccion]==config.get_localized_string(30158): # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools
        
        if item.subtitle!="":
            data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+item.url+ " " +item.thumbnail + " " + item.subtitle)
        else:
            data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+item.url+ " " +item.thumbnail)

        return

    if opciones[seleccion]==config.get_localized_string(30158).replace("jDownloader","pyLoad"): # "Enviar a pyLoad"
        logger.info("Enviando a pyload...")

        if item.show!="":
            package_name = item.show
        else:
            package_name = "pelisalacarta"

        from core import pyload_client
        pyload_client.download(url=item.url,package_name=package_name)
        return

    elif opciones[seleccion]==config.get_localized_string(30164): # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os
        os.remove( item.url )
        xbmc.executebuiltin( "Container.Refresh" )
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion])>3:
            wait_time = video_urls[seleccion][2]
            item.subtitle = video_urls[seleccion][3]
        elif len(video_urls[seleccion])>2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0
        view = True

    # Descargar
    elif opciones[seleccion]==config.get_localized_string(30153): # "Descargar"

        download_title = item.fulltitle
        if item.hasContentDetails=="true":
            download_title = item.contentTitle

        import xbmc
        # El vídeo de más calidad es el último
        mediaurl = video_urls[len(video_urls)-1][1]

        from core import downloadtools
        keyboard = xbmc.Keyboard(download_title)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            download_title = keyboard.getText()
            devuelve = downloadtools.downloadbest(video_urls,download_title)
            
            if devuelve==0:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Descargado con éxito")
            elif devuelve==-1:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Descarga abortada")
            else:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Error en la descarga")
        return

    elif opciones[seleccion]==config.get_localized_string(30154): #"Quitar de favoritos"
        from core import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30102) , item.title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30159): #"Borrar descarga definitivamente"
        from core import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30106)) # 'Se ha quitado de la lista'
        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30160): #"Pasar de nuevo a lista de descargas":
        from core import descargas
        descargas.mover_descarga_error_a_pendiente(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30107)) # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30155): #"Añadir a favoritos":
        from core import favoritos
        from core import downloadtools

        download_title = item.fulltitle
        download_thumbnail = item.thumbnail
        download_plot = item.plot

        if item.hasContentDetails=="true":
            download_title = item.contentTitle
            download_thumbnail = item.contentThumbnail
            download_plot = item.contentPlot

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(download_title)+" ["+item.channel+"]")
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=download_title,url=item.url,thumbnail=download_thumbnail,server=item.server,plot=download_plot,fulltitle=item.title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30102) , item.title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion]==config.get_localized_string(30156): #"Quitar de lista de descargas":
        from core import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus( item.extra )))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30106)) # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30157): #"Añadir a lista de descargas":
        from core import descargas
        from core import downloadtools

        download_title = item.fulltitle
        download_thumbnail = item.thumbnail
        download_plot = item.plot

        if item.hasContentDetails=="true":
            download_title = item.contentTitle
            download_thumbnail = item.contentThumbnail
            download_plot = item.contentPlot

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(download_title))
        keyboard.doModal()
        if keyboard.isConfirmed():
            download_title = keyboard.getText()

            descargas.savebookmark(titulo=download_title,url=item.url,thumbnail=download_thumbnail,server=item.server,plot=download_plot,fulltitle=download_title)

            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30101) , download_title , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30161): #"Añadir a Biblioteca":  # Library
        from platformcode import library
        
        titulo = item.fulltitle
        if item.fulltitle=="":
            titulo = item.title
        
        library.savelibrary(titulo,item.url,item.thumbnail,item.server,item.plot,canal=item.channel,category=item.category,Serie=item.show)

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , titulo , config.get_localized_string(30135)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30162): #"Buscar Trailer":
        config.set_setting("subtitulo", "false")
        import sys
        xbmc.executebuiltin("Container.Update(%s?%s)" % ( sys.argv[ 0 ] , item.clone(channel="trailertools", action="buscartrailer").tourl()))
        return

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("[xbmctools.py] mediaurl="+mediaurl)
    if mediaurl=="":
        logger.info("b1")
        if server == "unknown":
            alertUnsopportedServer()
        else:
            alertnodisponibleserver(item.server)
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time>0:
        logger.info("b2")
        continuar = handle_wait(wait_time,server,"Cargando vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        logger.info("b3")
        xlistitem = getLibraryInfo(mediaurl)
    else:
        logger.info("b4")

        play_title = item.fulltitle
        play_thumbnail = item.thumbnail
        play_plot = item.plot

        if item.hasContentDetails=="true":
            play_title = item.contentTitle
            play_thumbnail = item.contentThumbnail
            play_plot = item.contentPlot

        try:
            xlistitem = xbmcgui.ListItem( play_title, iconImage="DefaultVideo.png", thumbnailImage=play_thumbnail, path=mediaurl)
            logger.info("b4.1")
        except:
            xlistitem = xbmcgui.ListItem( play_title, iconImage="DefaultVideo.png", thumbnailImage=play_thumbnail)
            logger.info("b4.2")      
        
        xlistitem.setInfo( "video", { "Title": play_title, "Plot" : play_plot , "Studio" : item.channel , "Genre" : item.category } )
        
        #set_infoLabels(listitem,plot) # Modificacion introducida por super_berny para añadir infoLabels al ListItem
    
    # Lanza el reproductor
        # Lanza el reproductor
    if strmfile:           # and item.server != "torrent": #Si es un fichero strm no hace falta el play
        logger.info("b6")
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    else:
        logger.info("b7")
        logger.info("player_mode="+config.get_setting("player_mode"))
        logger.info("mediaurl="+mediaurl)
        if config.get_setting("player_mode")=="3" or "megacrypter.com" in mediaurl:
            logger.info("b11")
            import download_and_play
            download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") )
            return

        elif config.get_setting("player_mode")=="0" or (config.get_setting("player_mode")=="3" and mediaurl.startswith("rtmp")):
            logger.info("b8")
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()
            playlist.add( mediaurl, xlistitem )

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info("[xbmctools.py] playersettings="+playersettings)
        
            if config.get_system_platform()=="xbox":
                player_type = xbmc.PLAYER_CORE_AUTO
                if playersettings == "0":
                    player_type = xbmc.PLAYER_CORE_AUTO
                    logger.info("[xbmctools.py] PLAYER_CORE_AUTO")
                elif playersettings == "1":
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.info("[xbmctools.py] PLAYER_CORE_MPLAYER")
                elif playersettings == "2":
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.info("[xbmctools.py] PLAYER_CORE_DVDPLAYER")
            
                xbmcPlayer = xbmc.Player( player_type )
            else:
                xbmcPlayer = xbmc.Player()
    
            xbmcPlayer.play(playlist)
            
            if item.channel=="cuevana" and item.subtitle!="":
                logger.info("subtitulo="+subtitle)
                if item.subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
                    logger.info("[xbmctools.py] Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode")=="1":
            logger.info("b9")
            logger.info("mediaurl :"+ mediaurl)
            logger.info("Tras setResolvedUrl")
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=mediaurl))
        
        elif config.get_setting("player_mode")=="2":
            logger.info("b10")
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )
      
    if item.subtitle!="" and view:
        logger.info("b11")
        logger.info("Subtítulos externos: "+item.subtitle)
        xbmc.Player().setSubtitles(item.subtitle)
def play_video(channel="",server="",url="",category="",title="", thumbnail="",plot="",extra="",desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False,Serie="",subtitle="", video_password="",fulltitle=""):
    from servers import servertools
    import sys
    import xbmcgui
    
    if url.startswith("http://"):
        url = url.replace(" ","%20")
    
    try:
        logger.info("[xbmctools.py] play_video(channel=%s, server=%s, url=%s, category=%s, title=%s, thumbnail=%s, plot=%s, desdefavoritos=%s, desdedescargados=%s, desderrordescargas=%s, strmfile=%s, Serie=%s, subtitle=%s" % (channel,server,url,category,title,thumbnail,plot,desdefavoritos,desdedescargados,desderrordescargas,strmfile,Serie,subtitle))
    except:
        pass

    try:
        server = server.lower()
    except:
        server = ""

    if server=="":
        server="directo"

    try:
        from core import descargas
        download_enable=True
    except:
        download_enable=False

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action="+default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode")=="0" and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(server,url,video_password,muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            opciones.append(config.get_localized_string(30151) + " " + video_url[0])

        if server=="local":
            opciones.append(config.get_localized_string(30164))
        else:
            if download_enable:
                opcion = config.get_localized_string(30153)
                opciones.append(opcion) # "Descargar"
    
            if channel=="favoritos": 
                opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"
            else:
                opciones.append(config.get_localized_string(30155)) # "Añadir a favoritos"
        
            if not strmfile:
                opciones.append(config.get_localized_string(30161)) # "Añadir a Biblioteca"
        
            if download_enable:
                if channel!="descargas":
                    opciones.append(config.get_localized_string(30157)) # "Añadir a lista de descargas"
                else:
                    if category=="errores":
                        opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
                        opciones.append(config.get_localized_string(30160)) # "Pasar de nuevo a lista de descargas"
                    else:
                        opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
    
            opciones.append(config.get_localized_string(30158)) # "Enviar a JDownloader"

        if default_action=="3":
            seleccion = len(opciones)-1
    
        # Busqueda de trailers en youtube    
        if not channel in ["Trailer","ecarteleratrailers"]:
            opciones.append(config.get_localized_string(30162)) # "Buscar Trailer"

    # Si no puedes ver el vídeo te informa
    else:
        import xbmcgui
        if server!="":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok( "No puedes ver ese vídeo porque...",motivo.split("<br/>")[0],motivo.split("<br/>")[1],url)
            else:
                resultado = advertencia.ok( "No puedes ver ese vídeo porque...",motivo,url)
        else:
            resultado = advertencia.ok( "No puedes ver ese vídeo porque...","El servidor donde está alojado no está","soportado en pelisalacarta todavía",url)

        if channel=="favoritos": 
            opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"

        if channel=="descargas":
            if category=="errores":
                opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
        
        if len(opciones)==0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action=="0":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163), opciones) # "Elige una opción"
        #dia.close()
    elif default_action=="1":
        seleccion = 0
    elif default_action=="2":
        seleccion = len(video_urls)-1
    elif default_action=="3":
        seleccion = seleccion
    else:
        seleccion=0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC 
    if seleccion==-1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),False,listitem)    # JUR Added
        #if config.get_setting("subtitulo") == "true":
        #    config.set_setting("subtitulo", "false")
        return

    if opciones[seleccion]==config.get_localized_string(30158): # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools
        data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+url+ " " +thumbnail)
        return

    elif opciones[seleccion]==config.get_localized_string(30164): # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os
        os.remove( url )
        xbmc.executebuiltin( "Container.Refresh" )
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion])>2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0

        if len(video_urls[seleccion])>3:
            use_download_and_play = (video_urls[seleccion][3]=="download_and_play")
        else:
            use_download_and_play = False

        view = True

    # Descargar
    elif opciones[seleccion]==config.get_localized_string(30153): # "Descargar"
        
        # El vídeo de más calidad es el último
        mediaurl = video_urls[len(video_urls)-1][1]
        
        # Si no quiere usar filenium para descargas, coge el anterior
        if config.get_setting("filenium_for_download")=="false" and video_urls[len(video_urls)-1][0]=="[filenium]":
            mediaurl = video_urls[len(video_urls)-2][1]

        from core import downloadtools
        keyboard = xbmc.Keyboard(fulltitle)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            title = keyboard.getText()
            downloadtools.downloadtitle(mediaurl,title)
        return

    elif opciones[seleccion]==config.get_localized_string(30154): #"Quitar de favoritos"
        from core import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30159): #"Borrar descarga definitivamente"
        from core import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de la lista'
        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30160): #"Pasar de nuevo a lista de descargas":
        from core import descargas
        descargas.mover_descarga_error_a_pendiente(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30107)) # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30155): #"Añadir a favoritos":
        from core import favoritos
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle)+" ["+channel+"]")
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion]==config.get_localized_string(30156): #"Quitar de lista de descargas":
        from core import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus( extra )))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30157): #"Añadir a lista de descargas":
        from core import descargas
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle))
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            descargas.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30161): #"Añadir a Biblioteca":  # Library
        from platformcode.xbmc import library
        titulo = fulltitle
        if fulltitle=="":
            titulo = title
        library.savelibrary(titulo,url,thumbnail,server,plot,canal=channel,category=category,Serie=Serie)
        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , fulltitle , config.get_localized_string(30135)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30162): #"Buscar Trailer":
        config.set_setting("subtitulo", "false")
        import sys
        xbmc.executebuiltin("Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s&server=%s)" % ( sys.argv[ 0 ] , "trailertools" , "buscartrailer" , urllib.quote_plus( category ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" ) , server ))
        return

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("[xbmctools.py] mediaurl="+mediaurl)
    if mediaurl=="":
        logger.info("b1")
        if server == "unknown":
            alertUnsopportedServer()
        else:
            alertnodisponibleserver(server)
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time>0:
        logger.info("b2")
        continuar = handle_wait(wait_time,server,"Cargando vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        logger.info("b3")
        xlistitem = getLibraryInfo(mediaurl)
    else:
        logger.info("b4")
        try:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail, path=mediaurl)
        except:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        xlistitem.setInfo( "video", { "Title": title, "Plot" : plot , "Studio" : channel , "Genre" : category } )

    # Descarga el subtitulo
    if channel=="cuevana" and subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        logger.info("b5")
        try:
            import os
            ficherosubtitulo = os.path.join( config.get_data_path(), 'subtitulo.srt' )
            if os.path.exists(ficherosubtitulo):
                try:
                  os.remove(ficherosubtitulo)
                except IOError:
                  logger.info("Error al eliminar el archivo subtitulo.srt "+ficherosubtitulo)
                  raise
        
            from core import scrapertools
            data = scrapertools.cache_page(subtitle)
            #print data
            fichero = open(ficherosubtitulo,"w")
            fichero.write(data)
            fichero.close()
            #from core import downloadtools
            #downloadtools.downloadfile(subtitle, ficherosubtitulo )
        except:
            logger.info("Error al descargar el subtítulo")

    # Lanza el reproductor
    if strmfile: #Si es un fichero strm no hace falta el play
        logger.info("b6")
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,xlistitem)
        #if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        #    logger.info("[xbmctools.py] Con subtitulos")
        #    setSubtitles()
    else:
        logger.info("b7")
        if use_download_and_play or config.get_setting("player_mode")=="3":
            logger.info("b11")
            import download_and_play

            # El canal exige usar download_and_play, pero el usuario no lo ha elegido -> le quitamos los diálogos
            if use_download_and_play and config.get_setting("player_mode")!="3":
                download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") , show_dialog=False )
            else:
                download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") )
            return

        elif config.get_setting("player_mode")=="0":
            logger.info("b8")
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()
            playlist.add( mediaurl, xlistitem )

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info("[xbmctools.py] playersettings="+playersettings)
        
            player_type = xbmc.PLAYER_CORE_AUTO
            if playersettings == "0":
                player_type = xbmc.PLAYER_CORE_AUTO
                logger.info("[xbmctools.py] PLAYER_CORE_AUTO")
            elif playersettings == "1":
                player_type = xbmc.PLAYER_CORE_MPLAYER
                logger.info("[xbmctools.py] PLAYER_CORE_MPLAYER")
            elif playersettings == "2":
                player_type = xbmc.PLAYER_CORE_DVDPLAYER
                logger.info("[xbmctools.py] PLAYER_CORE_DVDPLAYER")
        
            xbmcPlayer = xbmc.Player( player_type )
            xbmcPlayer.play(playlist)
            
            if channel=="cuevana" and subtitle!="":
                logger.info("subtitulo="+subtitle)
                if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
                    logger.info("[xbmctools.py] Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode")=="1":
            logger.info("b9")
            #xlistitem.setProperty('IsPlayable', 'true')
            #xlistitem.setProperty('path', mediaurl)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=mediaurl))
        
        elif config.get_setting("player_mode")=="2":
            logger.info("b10")
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )

    if (config.get_setting("subtitulo") == "true") and view:
        logger.info("b11")
        from core import subtitletools
        wait2second()
        subtitletools.set_Subtitle()
        if subtitle!="":
            xbmc.Player().setSubtitles(subtitle)
Ejemplo n.º 15
0
def run():
    logger.info("streamondemand.platformcode.launcher run")

    # Extract item from sys.argv
    if sys.argv[2]:
        try:
            item = Item().fromurl(sys.argv[2])
            params = ""

        #Esto es para mantener la compatiblidad con el formato anterior...
        #Contretamente para que funcionen los STRM hasta que no se actualicen al nuevo formato
        except:
            params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password, hasContentDetails, contentTitle, contentThumbnail, contentPlot = extract_parameters(
            )
            item = Item(fanart=fanart,
                        channel=channel_name,
                        title=title,
                        fulltitle=fulltitle,
                        url=url,
                        thumbnail=thumbnail,
                        plot=plot,
                        action=action,
                        server=server,
                        extra=extra,
                        subtitle=subtitle,
                        viewmode=viewmode,
                        category=category,
                        show=show,
                        password=password,
                        hasContentDetails=hasContentDetails,
                        contentTitle=contentTitle,
                        contentThumbnail=contentThumbnail,
                        contentPlot=contentPlot)
    else:
        item = Item(action="selectchannel")
        params = ""

    logger.info(item.tostring())

    if config.get_setting('filter_servers') == 'true':
        server_white_list, server_black_list = set_server_list()

    try:
        # Default action: open channel and launch mainlist function
        if (item.action == "selectchannel"):
            import channelselector
            itemlist = channelselector.mainlist(params, item.url,
                                                item.category)
            from platformcode import xbmctools
            xbmctools.renderItems(itemlist, item)

        # Actualizar version
        elif (item.action == "update"):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info(
                    "streamondemand.platformcode.launcher Actualizacion automática desactivada"
                )

            #import channelselector as plugin
            #plugin.listchannels(params, url, category)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        elif (item.action == "channeltypes"):
            import channelselector
            itemlist = channelselector.channeltypes(params, item.url,
                                                    item.category)
            from platformcode import xbmctools
            xbmctools.renderItems(itemlist, item)

        elif (item.action == "listchannels"):
            import channelselector
            itemlist = channelselector.listchannels(params, item.url,
                                                    item.category)
            from platformcode import xbmctools
            xbmctools.renderItems(itemlist, item)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:

            if item.action == "mainlist":
                # Parental control
                can_open_channel = False

                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(item.channel) and config.get_setting(
                        "adult_pin") != "":

                    import xbmc
                    keyboard = xbmc.Keyboard("", "PIN para canales de adultos",
                                             True)
                    keyboard.doModal()

                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        if tecleado == config.get_setting("adult_pin"):
                            can_open_channel = True

                # All the other cases can open the channel
                else:
                    can_open_channel = True

                if not can_open_channel:
                    return

            if item.action == "mainlist" and config.get_setting(
                    "updatechannels") == "true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(item.channel)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin", channel_name,
                                       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 streamondemand
            regular_channel_path = os.path.join(config.get_runtime_path(),
                                                'channels',
                                                item.channel + ".py")
            core_channel_path = os.path.join(config.get_runtime_path(), 'core',
                                             item.channel + ".py")
            logger.info(
                "streamondemand.platformcode.launcher regular_channel_path=%s"
                % regular_channel_path)
            logger.info(
                "streamondemand.platformcode.launcher core_channel_path=%s" %
                core_channel_path)

            if item.channel == "personal" or item.channel == "personal2" or item.channel == "personal3" or item.channel == "personal4" or item.channel == "personal5":
                import channels.personal as channel
            elif os.path.exists(regular_channel_path):
                exec "import channels." + item.channel + " as channel"
            elif os.path.exists(core_channel_path):
                exec "from core import " + item.channel + " as channel"

            logger.info(
                "streamondemand.platformcode.launcher running channel %s %s" %
                (channel.__name__, channel.__file__))

            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 item.category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info(
                    "streamondemand.platformcode.launcher xbmc native channel")
                if (item.action == "strm"):
                    from platformcode import xbmctools
                    xbmctools.playstrm(params, item.url, item.category)
                else:
                    exec "channel." + item.action + "(params, item.url, item.category)"
            else:
                logger.info(
                    "streamondemand.platformcode.launcher multiplatform channel"
                )
                '''
                if item.subtitle!="":
                    logger.info("streamondemand.platformcode.launcher Downloading subtitle file "+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("streamondemand.platformcode.launcher No subtitle")
                '''
                from platformcode import xbmctools

                if item.action == "play":
                    logger.info("streamondemand.platformcode.launcher play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info(
                            "streamondemand.platformcode.launcher executing channel 'play' method"
                        )
                        itemlist = channel.play(item)
                        if len(itemlist) > 0:
                            item = itemlist[0]
                            xbmctools.play_video(item)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok("plugin",
                                                  "Niente da riprodurre")
                    else:
                        logger.info(
                            "streamondemand.platformcode.launcher no channel 'play' method, executing core method"
                        )
                        xbmctools.play_video(item)

                elif item.action == "strm_detail" or item.action == "play_from_library":
                    logger.info(
                        "streamondemand.platformcode.launcher play_from_library"
                    )

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")

                    logger.info("item.server=#" + item.server + "#")
                    # Ejecuta find_videos, del canal o común
                    if item.server != "":
                        try:
                            from servers import servertools
                            videourls = servertools.resolve_video_urls_for_playing(
                                server=item.server,
                                url=item.url,
                                video_password=item.video_password)
                            return videourls
                        except:
                            itemlist = []
                            pass
                    else:
                        try:
                            itemlist = channel.findvideos(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(
                                    itemlist, server_white_list,
                                    server_black_list)
                        except:
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(
                                    itemlist, server_white_list,
                                    server_black_list)

                    if len(itemlist) > 0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)

                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)

                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(
                            config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]

                        if seleccion == -1:
                            return
                    else:
                        elegido = item

                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" %
                                (item.title, item.subtitle))

                    from platformcode import xbmctools
                    logger.info("subtitle=" + item.subtitle)
                    xbmctools.play_video(item, strmfile=True)

                elif item.action == "add_pelicula_to_library":
                    logger.info(
                        "streamondemand.platformcode.launcher add_pelicula_to_library"
                    )
                    from platformcode import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary(titulo=item.fulltitle,
                                        url=item.url,
                                        thumbnail=item.thumbnail,
                                        server=item.server,
                                        plot=item.plot,
                                        canal=item.channel,
                                        category="Cine",
                                        Serie=item.show.strip(),
                                        verbose=False,
                                        accion="play_from_library",
                                        pedirnombre=False,
                                        subtitle=item.subtitle)

                elif item.action == "add_serie_to_library":
                    logger.info(
                        "streamondemand.platformcode.launcher add_serie_to_library, show=#"
                        + item.show + "#")
                    from platformcode import library
                    import xbmcgui

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

                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

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

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('streamondemand',
                                         'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info("[launcher.py] Total Episodios:" +
                                str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i * 100 / totalepisodes,
                                       'Añadiendo episodio...', item.title)
                        logger.info(
                            "streamondemand.platformcode.launcher add_serie_to_library, title="
                            + item.title)
                        if (pDialog.iscanceled()):
                            return

                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                                nuevos = nuevos + library.savelibrary(
                                    titulo=item.title,
                                    url=item.url,
                                    thumbnail=item.thumbnail,
                                    server=item.server,
                                    plot=item.plot,
                                    canal=item.channel,
                                    category="Series",
                                    Serie=item.show.strip(),
                                    verbose=False,
                                    accion="play_from_library",
                                    pedirnombre=False,
                                    subtitle=item.subtitle,
                                    extra=item.extra)
                        except IOError:

                            for line in sys.exc_info():
                                logger.error("%s" % line)
                            logger.info(
                                "streamondemand.platformcode.launcher Error al grabar el archivo "
                                + item.title)
                            errores = errores + 1

                    pDialog.close()

                    # Actualizacion de la biblioteca
                    itemlist = []
                    if errores > 0:
                        itemlist.append(
                            Item(
                                title=
                                "ERRORE, la serie NON si è aggiunta alla biblioteca o l'ha fatto in modo incompleto"
                            ))
                        logger.info("[launcher.py] No se pudo añadir " +
                                    str(errores) + " episodios")
                    else:
                        itemlist.append(
                            Item(title=
                                 "La serie è stata aggiunta alla biblioteca"))
                        logger.info("[launcher.py] Ningún error al añadir " +
                                    str(errores) + " episodios")

                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, item)

                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join(
                        config.get_library_path(), "series.xml")
                    if not os.path.exists(nombre_fichero_config_canal):
                        nombre_fichero_config_canal = os.path.join(
                            config.get_data_path(), "series.xml")

                    logger.info("nombre_fichero_config_canal=" +
                                nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open(nombre_fichero_config_canal, "w")
                    else:
                        f = open(nombre_fichero_config_canal, "r")
                        contenido = f.read()
                        f.close()
                        f = open(nombre_fichero_config_canal, "w")
                        f.write(contenido)
                    from platformcode import library
                    f.write(
                        library.title_to_folder_name(item.show) + "," +
                        item.url + "," + item.channel + "," + item.extra +
                        "\n")
                    f.close()

                elif item.action == "download_all_episodes":
                    download_all_episodes(item, channel)

                elif item.action == "search":
                    logger.info("streamondemand.platformcode.launcher search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, item)

                else:
                    logger.info(
                        "streamondemand.platformcode.launcher executing channel '"
                        + item.action + "' method")
                    if item.action != "findvideos":
                        exec "itemlist = channel." + item.action + "(item)"

                        #for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, 'findvideos'):
                            exec "itemlist = channel." + item.action + "(item)"

                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(
                                    itemlist, server_white_list,
                                    server_black_list)

                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info(
                                "streamondemand.platformcode.launcher no channel 'findvideos' method, executing core method"
                            )
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(
                                    itemlist, server_white_list,
                                    server_black_list)

                        from platformcode import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin

                    handle = sys.argv[1]
                    xbmcplugin.setContent(int(handle), "movies")

                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        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)
Ejemplo n.º 16
0
def download_all_episodes(item,channel,first_episode="", silent=False):
    logger.info("[launcher.py] download_all_episodes, show="+item.show)
    show_title = item.show

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

    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if "###" in item.extra:
        action = item.extra.split("###")[0]
        item.extra = item.extra.split("###")[1]

    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

        if episode_item.action=="download_all_episodes":
            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
        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":
                        devuelve = downloadtools.downloadbest(video_urls,show_title+" "+episode_title+idioma+" ["+video_item.server+"]",continuar=False,silent=silent)
                    else:
                        devuelve = downloadtools.downloadbest(video_urls,show_title+" "+episode_title+idioma+" ["+item.channel+"]",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)
Ejemplo n.º 17
0
def playvideo(sender,itemtext):
    Log("[__init__.py] playvideo")
    item = Item()
    item.deserialize(itemtext)

    dir = MediaContainer(viewGroup="InfoList")

    if item.action=="play":
        try:
            Log("[__init__.py] playvideo ejecutando metodo play del canal #"+item.channel+"#")
            exec "from pelisalacarta.channels import "+item.channel
            exec "itemlist = "+item.channel+"."+item.action+"(item)"
            item = itemlist[0]
            item.title = encodingsafe(item.title)
            item.plot = encodingsafe(item.plot)
        except:
            Log("[__init__.py] playvideo error al ejecutar metodo play del canal")
            import sys
            for line in sys.exc_info():
                Log( "%s" % line )

    from core import config

    Log("[__init__.py] playvideo url="+item.url+", server="+item.server)

    video_urls = []
    video_password=""
    url = item.url
    server = item.server
    

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    from servers import servertools
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(server,url,video_password,False)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            if len(video_url)>2:
                wait_time=video_url[2]
                dir.Append(Function( VideoItem(playvideonormal, title="Ver el vídeo "+video_url[0]+" (Espera %d segundos)" % wait_time, subtitle="", summary="", thumb = ""), mediaurl=video_url[1] ))
            else:
                wait_time=0
                dir.Append(Function( VideoItem(playvideonormal, title="Ver el vídeo "+video_url[0], subtitle="", summary="", thumb = ""), mediaurl=video_url[1] ))

    # Si no puedes ver el vídeo te informa
    else:
        if server!="":
            if "<br/>" in motivo:
                dir.Append(Function( VideoItem(playvideonormal, title="No puedes ver este vídeo", subtitle="", summary="No puedes ver ese vídeo porque...\n"+motivo.split("<br/>")[0]+"\n"+motivo.split("<br/>")[1]+"\n"+url, thumb = ""), mediaurl="" ))
            else:
                dir.Append(Function( VideoItem(playvideonormal, title="No puedes ver este vídeo", subtitle="", summary="No puedes ver ese vídeo porque...\n"+motivo , thumb = ""), mediaurl="" ))
        else:
            dir.Append(Function( VideoItem(playvideonormal, title="No puedes ver este vídeo", subtitle="", summary="No puedes ver ese vídeo porque...\n"+"El servidor donde está alojado no está"+"\nsoportado en pelisalacarta todavía" , thumb = ""), mediaurl="" ))
    
    '''
    try:
        Log("megavideo="+config.get_setting("megavideopremium"))
        # Extrae todos los enlaces posibles
        exec "from servers import "+server+" as server_connector"
        if server=="megavideo" or server=="megaupload":
            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"), video_password=video_password )
        elif server=="fileserve":
            video_urls = server_connector.get_video_url( page_url=url , premium=(config.get_setting("fileservepremium")=="true") , user=config.get_setting("fileserveuser") , password=config.get_setting("fileservepassword"), video_password=video_password )
        else:
            video_urls = server_connector.get_video_url( page_url=url , video_password=video_password )
    except:
        import sys
        for line in sys.exc_info():
            Log( "%s" % line )

    if config.get_setting("fileniumpremium")=="true" and item.server not in ["downupload","vk","fourshared","directo","adnstream","facebook","megalive","tutv","stagevu"]:
        exec "from servers import filenium as gen_conector"
        video_gen = gen_conector.get_video_url( page_url=url , premium=(config.get_setting("fileniumpremium")=="true") , user=config.get_setting("fileniumuser") , password=config.get_setting("fileniumpassword"), video_password=video_password )
        Log("[xbmctools.py] filenium url="+video_gen)
        video_urls.append( [ "[filenium]", video_gen ] )
    '''
    
    return dir
def download_all_episodes(item,channel,first_episode="",preferred_server="vidspot",filter_language=""):
    logger.info("streamondemand.platformcode.launcher download_all_episodes, show="+item.show)
    show_title = item.show

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

    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if "###" in item.extra:
        action = item.extra.split("###")[0]
        item.extra = item.extra.split("###")[1]

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

    # Ordena los episodios para que funcione el filtro de first_episode
    episode_itemlist = sorted(episode_itemlist, key=lambda Item: Item.title) 

    from servers import servertools
    from core import downloadtools

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

    for episode_item in episode_itemlist:
        if episode_item.action == "add_serie_to_library" or episode_item.action == "download_all_episodes":
            continue

        try:
            logger.info("streamondemand.platformcode.launcher download_all_episodes, episode="+episode_item.title)
            #episode_title = scrapertools.get_match(episode_item.title,"(\d+x\d+)")
            episode_title = episode_item.title
            episode_title = re.sub(r"\[COLOR [^]]*\]", "", episode_title)
            episode_title = re.sub(r"\[/COLOR\]", "", episode_title)
            logger.info("streamondemand.platformcode.launcher download_all_episodes, episode="+episode_title)
        except:
            import traceback
            logger.info(traceback.format_exc())
            continue

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

        if episodio_ya_descargado(show_title,episode_title):
            continue

        if not empezar:
            continue

        # Extrae los mirrors
        try:
            #mirrors_itemlist = channel.findvideos(episode_item)
            exec "mirrors_itemlist = channel."+episode_item.action+"(episode_item)"
        except:
            mirrors_itemlist = servertools.find_video_items(episode_item)
        print mirrors_itemlist

        descargado = False

        for mirror_item in mirrors_itemlist:
            logger.info("streamondemand.platformcode.launcher download_all_episodes, mirror="+mirror_item.title)

            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("streamondemand.platformcode.launcher download_all_episodes, downloading mirror started...")
                    # El vídeo de más calidad es el último
                    devuelve = downloadtools.downloadbest(video_urls,show_title+" "+episode_title+" ["+video_item.server+"]",continuar=False)

                    if devuelve==0:
                        logger.info("streamondemand.platformcode.launcher download_all_episodes, download ok")
                        descargado = True
                        break
                    elif devuelve==-1:
                        try:
                            import xbmcgui
                            advertencia = xbmcgui.Dialog()
                            resultado = advertencia.ok("plugin" , "Download interrotto")
                        except:
                            pass
                        return
                    else:
                        logger.info("streamondemand.platformcode.launcher download_all_episodes, download error, try another mirror")
                        continue

                else:
                    logger.info("streamondemand.platformcode.launcher download_all_episodes, downloading mirror not available... trying next")

        if not descargado:
            logger.info("streamondemand.platformcode.launcher download_all_episodes, EPISODIO NO DESCARGADO "+episode_title)
Ejemplo n.º 19
0
def download_all_episodes(item,channel,first_episode="",preferred_server="vidspot",filter_language=""):
    logger.info("pelisalacarta.platformcode.launcher download_all_episodes, show="+item.show)
    show_title = item.show

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

    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if "###" in item.extra:
        action = item.extra.split("###")[0]
        item.extra = item.extra.split("###")[1]

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

    # Ordena los episodios para que funcione el filtro de first_episode
    episode_itemlist = sorted(episode_itemlist, key=lambda Item: Item.title) 

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

    best_server = preferred_server
    worst_server = "moevideos"

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

    for episode_item in episode_itemlist:
        try:
            logger.info("pelisalacarta.platformcode.launcher download_all_episodes, episode="+episode_item.title)
            episode_title = scrapertools.get_match(episode_item.title,"(\d+x\d+)")
            logger.info("pelisalacarta.platformcode.launcher download_all_episodes, episode="+episode_title)
        except:
            import traceback
            logger.info(traceback.format_exc())
            continue

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

        if episodio_ya_descargado(show_title,episode_title):
            continue

        if not empezar:
            continue

        # Extrae los mirrors
        try:
            mirrors_itemlist = channel.findvideos(episode_item)
        except:
            mirrors_itemlist = servertools.find_video_items(episode_item)
        print mirrors_itemlist

        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 "(Latino)" 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)
            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("pelisalacarta.platformcode.launcher download_all_episodes, mirror="+mirror_item.title)

            if "(Español)" in mirror_item.title:
                idioma="(Español)"
                codigo_idioma="es"
            elif "(Latino)" in mirror_item.title:
                idioma="(Latino)"
                codigo_idioma="lat"
            elif "(VOS)" in mirror_item.title:
                idioma="(VOS)"
                codigo_idioma="vos"
            elif "(VO)" in mirror_item.title:
                idioma="(VO)"
                codigo_idioma="vo"
            else:
                idioma="(Desconocido)"
                codigo_idioma="desconocido"

            logger.info("pelisalacarta.platformcode.launcher filter_language=#"+filter_language+"#, codigo_idioma=#"+codigo_idioma+"#")
            if filter_language=="" or (filter_language!="" and filter_language==codigo_idioma):
                logger.info("pelisalacarta.platformcode.launcher download_all_episodes, downloading mirror")
            else:
                logger.info("pelisalacarta.platformcode.launcher language "+codigo_idioma+" filtered, skipping")
                continue

            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("pelisalacarta.platformcode.launcher download_all_episodes, downloading mirror started...")
                    # El vídeo de más calidad es el último
                    mediaurl = video_urls[len(video_urls)-1][1]
                    devuelve = downloadtools.downloadbest(video_urls,show_title+" "+episode_title+" "+idioma+" ["+video_item.server+"]",continuar=False)

                    if devuelve==0:
                        logger.info("pelisalacarta.platformcode.launcher 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("pelisalacarta.platformcode.launcher download_all_episodes, download error, try another mirror")
                        continue

                else:
                    logger.info("pelisalacarta.platformcode.launcher download_all_episodes, downloading mirror not available... trying next")

        if not descargado:
            logger.info("pelisalacarta.platformcode.launcher download_all_episodes, EPISODIO NO DESCARGADO "+episode_title)
Ejemplo n.º 20
0
def run():
    logger.info("pelisalacarta.platformcode.launcher run")

    # Extract parameters from sys.argv
    params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password, hasContentDetails, contentTitle, contentThumbnail, contentPlot = extract_parameters()
    logger.info("pelisalacarta.platformcode.launcher fanart=%s, channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s, hasContentDetails=%s contentTitle=%s contentThumbnail=%s contentPlot=%s" % (fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password,hasContentDetails, contentTitle, contentThumbnail, contentPlot))

    if config.get_setting('filter_servers') == 'true':
        server_white_list, server_black_list = set_server_list() 

    try:
        # Default action: open channel and launch mainlist function
        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.platformcode.launcher Actualizacion automática desactivada")

            #import channelselector as plugin
            #plugin.listchannels(params, url, category)
            if config.get_system_platform()!="xbox":
                import xbmc
                xbmc.executebuiltin( "Container.Refresh" )

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

        elif (action=="categories"):
            import channelselector as plugin
            plugin.categories(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":
                # Parental control
                can_open_channel = False

                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(channel_name) and config.get_setting("adult_pin")!="":
                    
                    import xbmc
                    keyboard = xbmc.Keyboard("","PIN para canales de adultos",True)
                    keyboard.doModal()

                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        if tecleado==config.get_setting("adult_pin"):
                            can_open_channel = True

                # All the other cases can open the channel
                else:
                    can_open_channel = True

                if not can_open_channel:
                    return

            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin",channel_name,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() , 'channels' , channel_name+".py" )
            core_channel_path = os.path.join( config.get_runtime_path(), 'core' , channel_name+".py" )
            logger.info("pelisalacarta.platformcode.launcher regular_channel_path=%s" % regular_channel_path)
            logger.info("pelisalacarta.platformcode.launcher core_channel_path=%s" % core_channel_path)

            if channel_name=="personal" or channel_name=="personal2" or channel_name=="personal3" or channel_name=="personal4" or channel_name=="personal5":
                import channels.personal as channel
            elif os.path.exists( regular_channel_path ):
                exec "import channels."+channel_name+" as channel"
            elif os.path.exists( core_channel_path ):
                exec "from core import "+channel_name+" as channel"

            logger.info("pelisalacarta.platformcode.launcher running channel %s %s" % (channel.__name__ , channel.__file__))

            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

            if not generico:
                logger.info("pelisalacarta.platformcode.launcher xbmc native channel")
                if (action=="strm"):
                    from platformcode import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel."+action+"(params, url, category)"
            else:            
                logger.info("pelisalacarta.platformcode.launcher multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name, title=title , fulltitle=fulltitle, url=url, thumbnail=thumbnail , plot=plot , server=server, category=category, extra=extra, subtitle=subtitle, viewmode=viewmode, show=show, password=password, fanart=fanart, hasContentDetails=hasContentDetails, contentTitle=contentTitle, contentThumbnail=contentThumbnail, contentPlot=contentPlot)
                
                '''
                if item.subtitle!="":
                    logger.info("pelisalacarta.platformcode.launcher Downloading subtitle file "+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("pelisalacarta.platformcode.launcher No subtitle")
                '''
                from platformcode import xbmctools

                if action=="play":
                    logger.info("pelisalacarta.platformcode.launcher play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method")
                        itemlist = channel.play(item)
                        if len(itemlist)>0:
                            item = itemlist[0]
                            xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                    else:
                        logger.info("pelisalacarta.platformcode.launcher no channel 'play' method, executing core method")
                        xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot)

                elif action=="strm_detail" or action=="play_from_library":
                    logger.info("pelisalacarta.platformcode.launcher play_from_library")

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")                    

                    logger.info("item.server=#"+item.server+"#")
                    # Ejecuta find_videos, del canal o común
                    if item.server != "":
                        try:
                            from servers import servertools
                            videourls = servertools.resolve_video_urls_for_playing(server=item.server, url=item.url, video_password=item.video_password)
                            return videourls
                        except:
                            itemlist = []
                            pass						
                    else:
                        try:
                            itemlist = channel.findvideos(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(itemlist, server_white_list, server_black_list) 
                        except:
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(itemlist, server_white_list, server_black_list)

                    if len(itemlist)>0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)
    
                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)
                    
                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]
    
                        if seleccion==-1:
                            return
                    else:
                        elegido = item
                
                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" % (item.title,item.subtitle))
                    
                    from platformcode import xbmctools
                    logger.info("subtitle="+item.subtitle)
                    xbmctools.play_video(strmfile=True, channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=fulltitle)

                elif action=="add_pelicula_to_library":
                    logger.info("pelisalacarta.platformcode.launcher add_pelicula_to_library")
                    from platformcode import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary( titulo=item.fulltitle , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Cine" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )

                elif action=="add_serie_to_library":
                    logger.info("pelisalacarta.platformcode.launcher add_serie_to_library, show=#"+item.show+"#")
                    from platformcode import library
                    import xbmcgui
                
                    # Obtiene el listado desde el que se llamó
                    action = item.extra
                    
                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

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

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info ("[launcher.py] Total Episodios:"+str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
                        logger.info("pelisalacarta.platformcode.launcher add_serie_to_library, title="+item.title)
                        if (pDialog.iscanceled()):
                            return
                
                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                                nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle, extra=item.extra )
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error( "%s" % line )
                            logger.info("pelisalacarta.platformcode.launcherError al grabar el archivo "+item.title)
                            errores = errores + 1
                        
                    pDialog.close()
                    
                    # Actualizacion de la biblioteca
                    itemlist=[]
                    if errores > 0:
                        itemlist.append(Item(title="ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta"))
                        logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios")
                    else:
                        itemlist.append(Item(title="La serie se ha añadido a la biblioteca"))
                        logger.info ("[launcher.py] Ningún error al añadir "+str(errores)+" episodios")
                    
                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)
                    
                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
                    if not os.path.exists(nombre_fichero_config_canal):
                        nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

                    logger.info("nombre_fichero_config_canal="+nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open( nombre_fichero_config_canal , "w" )
                    else:
                        f = open( nombre_fichero_config_canal , "r" )
                        contenido = f.read()
                        f.close()
                        f = open( nombre_fichero_config_canal , "w" )
                        f.write(contenido)
                    from platformcode import library
                    f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
                    f.close();

                elif action=="download_all_episodes":
                    download_all_episodes(item,channel)

                elif action=="search":
                    logger.info("pelisalacarta.platformcode.launcher search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info("pelisalacarta.platformcode.launcher executing channel '"+action+"' method")
                    if action!="findvideos":
                        exec "itemlist = channel."+action+"(item)"
                            
                        #for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, 'findvideos'):
                            exec "itemlist = channel."+action+"(item)"

                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(itemlist, server_white_list, server_black_list) 

                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, executing core method")
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(itemlist, server_white_list, server_black_list)

                        from platformcode import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys
                    handle = sys.argv[1]
                    xbmcplugin.setContent(int( handle ),"movies")
                    
                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError,e:
        import traceback,sys
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        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)    
Ejemplo n.º 21
0
def playvideo(sender, itemtext):
    Log("[__init__.py] playvideo")
    item = Item()
    item.deserialize(itemtext)

    dir = MediaContainer(viewGroup="InfoList")

    if item.action == "play":
        try:
            Log("[__init__.py] playvideo ejecutando metodo play del canal #" +
                item.channel + "#")
            exec "from pelisalacarta.channels import " + item.channel
            exec "itemlist = " + item.channel + "." + item.action + "(item)"
            item = itemlist[0]
            item.title = encodingsafe(item.title)
            item.plot = encodingsafe(item.plot)
        except:
            Log("[__init__.py] playvideo error al ejecutar metodo play del canal"
                )
            import sys
            for line in sys.exc_info():
                Log("%s" % line)

    from core import config

    Log("[__init__.py] playvideo url=" + item.url + ", server=" + item.server)

    video_urls = []
    video_password = ""
    url = item.url
    server = item.server

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    from servers import servertools
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
        server, url, video_password, False)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            if len(video_url) > 2:
                wait_time = video_url[2]
                dir.Append(
                    Function(VideoItem(playvideonormal,
                                       title="Ver el vídeo " + video_url[0] +
                                       " (Espera %d segundos)" % wait_time,
                                       subtitle="",
                                       summary="",
                                       thumb=""),
                             mediaurl=video_url[1]))
            else:
                wait_time = 0
                dir.Append(
                    Function(VideoItem(playvideonormal,
                                       title="Ver el vídeo " + video_url[0],
                                       subtitle="",
                                       summary="",
                                       thumb=""),
                             mediaurl=video_url[1]))

    # Si no puedes ver el vídeo te informa
    else:
        if server != "":
            if "<br/>" in motivo:
                dir.Append(
                    Function(VideoItem(
                        playvideonormal,
                        title="No puedes ver este vídeo",
                        subtitle="",
                        summary="No puedes ver ese vídeo porque...\n" +
                        motivo.split("<br/>")[0] + "\n" +
                        motivo.split("<br/>")[1] + "\n" + url,
                        thumb=""),
                             mediaurl=""))
            else:
                dir.Append(
                    Function(VideoItem(
                        playvideonormal,
                        title="No puedes ver este vídeo",
                        subtitle="",
                        summary="No puedes ver ese vídeo porque...\n" + motivo,
                        thumb=""),
                             mediaurl=""))
        else:
            dir.Append(
                Function(
                    VideoItem(playvideonormal,
                              title="No puedes ver este vídeo",
                              subtitle="",
                              summary="No puedes ver ese vídeo porque...\n" +
                              "El servidor donde está alojado no está" +
                              "\nsoportado en pelisalacarta todavía",
                              thumb=""),
                    mediaurl=""))
    '''
    try:
        Log("megavideo="+config.get_setting("megavideopremium"))
        # Extrae todos los enlaces posibles
        exec "from servers import "+server+" as server_connector"
        if server=="megavideo" or server=="megaupload":
            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"), video_password=video_password )
        elif server=="fileserve":
            video_urls = server_connector.get_video_url( page_url=url , premium=(config.get_setting("fileservepremium")=="true") , user=config.get_setting("fileserveuser") , password=config.get_setting("fileservepassword"), video_password=video_password )
        else:
            video_urls = server_connector.get_video_url( page_url=url , video_password=video_password )
    except:
        import sys
        for line in sys.exc_info():
            Log( "%s" % line )

    if config.get_setting("fileniumpremium")=="true" and item.server not in ["downupload","vk","fourshared","directo","adnstream","facebook","megalive","tutv","stagevu"]:
        exec "from servers import filenium as gen_conector"
        video_gen = gen_conector.get_video_url( page_url=url , premium=(config.get_setting("fileniumpremium")=="true") , user=config.get_setting("fileniumuser") , password=config.get_setting("fileniumpassword"), video_password=video_password )
        Log("[xbmctools.py] filenium url="+video_gen)
        video_urls.append( [ "[filenium]", video_gen ] )
    '''

    return dir
Ejemplo n.º 22
0
def play_video(channel="",server="",url="",category="",title="", thumbnail="",plot="",extra="",desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False,Serie="",subtitle="", video_password="",fulltitle=""):
    from servers import servertools
    import sys
    import xbmcgui,xbmc
    try:
        logger.info("[xbmctools.py] play_video(channel=%s, server=%s, url=%s, category=%s, title=%s, thumbnail=%s, plot=%s, desdefavoritos=%s, desdedescargados=%s, desderrordescargas=%s, strmfile=%s, Serie=%s, subtitle=%s" % (channel,server,url,category,title,thumbnail,plot,desdefavoritos,desdedescargados,desderrordescargas,strmfile,Serie,subtitle))
    except:
        pass

    try:
        server = server.lower()
    except:
        server = ""

    if server=="":
        server="directo"

    try:
        from core import descargas
        download_enable=True
    except:
        download_enable=False

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action="+default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode")=="0" and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(server,url,video_password,muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        
        for video_url in video_urls:
            opciones.append(config.get_localized_string(30151) + " " + video_url[0])

        if server=="local":
            opciones.append(config.get_localized_string(30164))
        else:
            if download_enable:
                opcion = config.get_localized_string(30153)
                opciones.append(opcion) # "Descargar"
    
            if channel=="favoritos": 
                opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"
            else:
                opciones.append(config.get_localized_string(30155)) # "Añadir a favoritos"
        
            if not strmfile:
                opciones.append(config.get_localized_string(30161)) # "Añadir a Biblioteca"
        
            if download_enable:
                if channel!="descargas":
                    opciones.append(config.get_localized_string(30157)) # "Añadir a lista de descargas"
                else:
                    if category=="errores":
                        opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
                        opciones.append(config.get_localized_string(30160)) # "Pasar de nuevo a lista de descargas"
                    else:
                        opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
    
            if config.get_setting("jdownloader_enabled")=="true":
                opciones.append(config.get_localized_string(30158)) # "Enviar a JDownloader"
            if config.get_setting("pyload_enabled")=="true":
                opciones.append(config.get_localized_string(30158).replace("jDownloader","pyLoad")) # "Enviar a pyLoad"

        if default_action=="3":
            seleccion = len(opciones)-1
    
        # Busqueda de trailers en youtube    
        if not channel in ["Trailer","ecarteleratrailers"]:
            opciones.append(config.get_localized_string(30162)) # "Buscar Trailer"

    # Si no puedes ver el vídeo te informa
    else:
        import xbmcgui
        if server!="":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok( "Non è possibile guardare il video perché...",motivo.split("<br/>")[0],motivo.split("<br/>")[1],url)
            else:
                resultado = advertencia.ok( "Non è possibile guardare il video perché...",motivo,url)
        else:
            resultado = advertencia.ok( "Non è possibile guardare il video perché...","Il server che lo ospita non è","ancora supportato da streamondemand",url)

        if channel=="favoritos": 
            opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"

        if channel=="descargas":
            if category=="errores":
                opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
        
        if len(opciones)==0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action=="0": # and server!="torrent":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163), opciones) # "Elige una opción"
        #dia.close()
        '''
        elif default_action=="0" and server=="torrent":
            advertencia = xbmcgui.Dialog()
            logger.info("video_urls[0]="+str(video_urls[0][1]))
            if puedes and ('"status":"COMPLETED"' in video_urls[0][1] or '"percent_done":100' in video_urls[0][1]):
                listo  = "y está listo para ver"
            else:
                listo = "y se está descargando"
            resultado = advertencia.ok( "Torrent" , "El torrent ha sido añadido a la lista" , listo )
            seleccion=-1
        '''
    elif default_action=="1":
        seleccion = 0
    elif default_action=="2":
        seleccion = len(video_urls)-1
    elif default_action=="3":
        seleccion = seleccion
    else:
        seleccion=0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC 
    if seleccion==-1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),False,listitem)    # JUR Added
        #if config.get_setting("subtitulo") == "true":
        #    config.set_setting("subtitulo", "false")
        return

    if opciones[seleccion]==config.get_localized_string(30158): # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools
        
        if subtitle!="":
            data = scrapertools.cache_page(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+url+ " " +thumbnail + " " + subtitle)
        else:
            data = scrapertools.cache_page(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+url+ " " +thumbnail)

        return

    if opciones[seleccion]==config.get_localized_string(30158).replace("jDownloader","pyLoad"): # "Enviar a pyLoad"
        logger.info("Enviando a pyload...")

        if Serie!="":
            package_name = Serie
        else:
            package_name = "streamondemand"

        from core import pyload_client
        pyload_client.download(url=url,package_name=package_name)
        return

    elif opciones[seleccion]==config.get_localized_string(30164): # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os
        os.remove( url )
        xbmc.executebuiltin( "Container.Refresh" )
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion])>2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0
        view = True

    # Descargar
    elif opciones[seleccion]==config.get_localized_string(30153): # "Descargar"
        import xbmc
        # El vídeo de más calidad es el último
        mediaurl = video_urls[len(video_urls)-1][1]

        from core import downloadtools
        keyboard = xbmc.Keyboard(fulltitle)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            title = keyboard.getText()
            devuelve = downloadtools.downloadbest(video_urls,title)
            
            if devuelve==0:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Scaricato con successo")
            elif devuelve==-1:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Download interrotto")
            else:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Errore nel download")
        return

    elif opciones[seleccion]==config.get_localized_string(30154): #"Quitar de favoritos"
        from core import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30159): #"Borrar descarga definitivamente"
        from core import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de la lista'
        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30160): #"Pasar de nuevo a lista de descargas":
        from core import descargas
        descargas.mover_descarga_error_a_pendiente(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30107)) # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30155): #"Añadir a favoritos":
        from core import favoritos
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle)+" ["+channel+"]")
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion]==config.get_localized_string(30156): #"Quitar de lista de descargas":
        from core import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus( extra )))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30157): #"Añadir a lista de descargas":
        from core import descargas
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle))
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            descargas.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30161): #"Añadir a Biblioteca":  # Library
        from platformcode import library
        titulo = fulltitle
        if fulltitle=="":
            titulo = title
        library.savelibrary(titulo,url,thumbnail,server,plot,canal=channel,category=category,Serie=Serie)
        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , fulltitle , config.get_localized_string(30135)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30162): #"Buscar Trailer":
        config.set_setting("subtitulo", "false")
        import sys
        xbmc.executebuiltin("Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s&server=%s)" % ( sys.argv[ 0 ] , "trailertools" , "buscartrailer" , urllib.quote_plus( category ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" ) , server ))
        return

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("[xbmctools.py] mediaurl="+mediaurl)
    if mediaurl=="":
        logger.info("b1")
        if server == "unknown":
            alertUnsopportedServer()
        else:
            alertnodisponibleserver(server)
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time>0:
        logger.info("b2")
        continuar = handle_wait(wait_time,server,"Caricamento vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        logger.info("b3")
        xlistitem = getLibraryInfo(mediaurl)
    else:
        logger.info("b4")
        try:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail, path=mediaurl)
        except:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        xlistitem.setInfo( "video", { "Title": title, "Plot" : plot , "Studio" : channel , "Genre" : category } )

    # Descarga el subtitulo
    if channel=="cuevana" and subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        logger.info("b5")
        try:
            import os
            ficherosubtitulo = os.path.join( config.get_data_path(), 'subtitulo.srt' )
            if os.path.exists(ficherosubtitulo):
                try:
                  os.remove(ficherosubtitulo)
                except IOError:
                  logger.info("Errore nell'eliminazione del file subtitulo.srt "+ficherosubtitulo)
                  raise
        
            from core import scrapertools
            data = scrapertools.cache_page(subtitle)
            #print data
            fichero = open(ficherosubtitulo,"w")
            fichero.write(data)
            fichero.close()
            #from core import downloadtools
            #downloadtools.downloadfile(subtitle, ficherosubtitulo )
        except:
            logger.info("Errore nel download del sottotitolo")

    # Lanza el reproductor
    if strmfile: #Si es un fichero strm no hace falta el play
        logger.info("b6")
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,xlistitem)
        #if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        #    logger.info("[xbmctools.py] Con subtitulos")
        #    setSubtitles()
        
    else:
        logger.info("b7")
        logger.info("player_mode="+config.get_setting("player_mode"))
        logger.info("mediaurl="+mediaurl)
        if config.get_setting("player_mode")=="3" or "megacrypter.com" in mediaurl:
            logger.info("b11")
            import download_and_play
            download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") )
            return

        elif config.get_setting("player_mode")=="0" or (config.get_setting("player_mode")=="3" and mediaurl.startswith("rtmp")):
            logger.info("b8")
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()
            playlist.add( mediaurl, xlistitem )

            # Reproduce
            # playersettings = config.get_setting('player_type')
            # logger.info("[xbmctools.py] playersettings="+playersettings)
        
            # player_type = xbmc.PLAYER_CORE_AUTO
            # if playersettings == "0":
            #     player_type = xbmc.PLAYER_CORE_AUTO
            #     logger.info("[xbmctools.py] PLAYER_CORE_AUTO")
            # elif playersettings == "1":
            #     player_type = xbmc.PLAYER_CORE_MPLAYER
            #     logger.info("[xbmctools.py] PLAYER_CORE_MPLAYER")
            # elif playersettings == "2":
            #     player_type = xbmc.PLAYER_CORE_DVDPLAYER
            #     logger.info("[xbmctools.py] PLAYER_CORE_DVDPLAYER")
        
            xbmcPlayer = xbmc.Player()
            xbmcPlayer.play(playlist)
            
            if channel=="cuevana" and subtitle!="":
                logger.info("subtitulo="+subtitle)
                if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
                    logger.info("[xbmctools.py] Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode")=="1":
            logger.info("b9")
            #xlistitem.setProperty('IsPlayable', 'true')
            #xlistitem.setProperty('path', mediaurl)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=mediaurl))
        
        elif config.get_setting("player_mode")=="2":
            logger.info("b10")
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )
        
    # Descarga en segundo plano para vidxden, sólo en modo free
    '''
    elif server=="vidxden" and seleccion==0:
        from core import downloadtools
        import thread,os
        import xbmc
        
        logger.info("[xbmctools.py] ---------------------------------")
        logger.info("[xbmctools.py] DESCARGA EN SEGUNDO PLANO")
        logger.info("[xbmctools.py]   de "+mediaurl)
        temp_file = config.get_temp_file("background.file")
        if os.path.exists(temp_file):
            os.remove(temp_file)
        logger.info("[xbmctools.py]   a "+temp_file)
        logger.info("[xbmctools.py] ---------------------------------")
        thread.start_new_thread(downloadtools.downloadfile, (mediaurl,temp_file), {'silent':True})

        handle_wait(60,"Descarga en segundo plano","Se está descargando un trozo antes de empezar")

        playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
        playlist.clear()
        playlist.add( temp_file, xlistitem )
    
        player_type = xbmc.PLAYER_CORE_AUTO
        xbmcPlayer = xbmc.Player( player_type )
        xbmcPlayer.play(playlist)
        
        while xbmcPlayer.isPlaying():
            xbmc.sleep(5000)
            logger.info("sigo aquí...")

        logger.info("fin")
    '''

    if config.get_setting("subtitulo") == "true" and view:
        logger.info("b11")
        from platformcode import subtitletools
        wait2second()
        subtitletools.set_Subtitle()
        if subtitle!="":
            xbmc.Player().setSubtitles(subtitle)
    #FIXME: Qué cosa más fea...
    elif channel=="moviezet":
        xbmc.Player().setSubtitles(subtitle)
Ejemplo n.º 23
0
def play_video(channel="",server="",url="",category="",title="", thumbnail="",plot="",extra="",desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False,Serie="",subtitle="", video_password="",fulltitle=""):
    from servers import servertools
    import sys
    import xbmcgui
    
    if url.startswith("http://"):
        url = url.replace(" ","%20")
    
    try:
        logger.info("[xbmctools.py] play_video(channel=%s, server=%s, url=%s, category=%s, title=%s, thumbnail=%s, plot=%s, desdefavoritos=%s, desdedescargados=%s, desderrordescargas=%s, strmfile=%s, Serie=%s, subtitle=%s" % (channel,server,url,category,title,thumbnail,plot,desdefavoritos,desdedescargados,desderrordescargas,strmfile,Serie,subtitle))
    except:
        pass

    try:
        server = server.lower()
    except:
        server = ""

    if server=="":
        server="directo"

    try:
        from core import descargas
        download_enable=True
    except:
        download_enable=False

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action="+default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode")=="0" and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(server,url,video_password,muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            opciones.append(config.get_localized_string(30151) + " " + video_url[0])

        if server=="local":
            opciones.append(config.get_localized_string(30164))
        else:
            if download_enable:
                opcion = config.get_localized_string(30153)
                opciones.append(opcion) # "Descargar"
    
            if channel=="favoritos": 
                opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"
            else:
                opciones.append(config.get_localized_string(30155)) # "Añadir a favoritos"
        
            if not strmfile:
                opciones.append(config.get_localized_string(30161)) # "Añadir a Biblioteca"
        
            if download_enable:
                if channel!="descargas":
                    opciones.append(config.get_localized_string(30157)) # "Añadir a lista de descargas"
                else:
                    if category=="errores":
                        opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
                        opciones.append(config.get_localized_string(30160)) # "Pasar de nuevo a lista de descargas"
                    else:
                        opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
    
            opciones.append(config.get_localized_string(30158)) # "Enviar a JDownloader"

        if default_action=="3":
            seleccion = len(opciones)-1
    
        # Busqueda de trailers en youtube    
        if not channel in ["Trailer","ecarteleratrailers"]:
            opciones.append(config.get_localized_string(30162)) # "Buscar Trailer"

    # Si no puedes ver el vídeo te informa
    else:
        import xbmcgui
        if server!="":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok( "No puedes ver ese vídeo porque...",motivo.split("<br/>")[0],motivo.split("<br/>")[1],url)
            else:
                resultado = advertencia.ok( "No puedes ver ese vídeo porque...",motivo,url)
        else:
            resultado = advertencia.ok( "No puedes ver ese vídeo porque...","El servidor donde está alojado no está","soportado en pelisalacarta todavía",url)

        if channel=="favoritos": 
            opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"

        if channel=="descargas":
            if category=="errores":
                opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
        
        if len(opciones)==0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action=="0":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163), opciones) # "Elige una opción"
        #dia.close()
    elif default_action=="1":
        seleccion = 0
    elif default_action=="2":
        seleccion = len(video_urls)-1
    elif default_action=="3":
        seleccion = seleccion
    else:
        seleccion=0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC 
    if seleccion==-1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),False,listitem)    # JUR Added
        #if config.get_setting("subtitulo") == "true":
        #    config.set_setting("subtitulo", "false")
        return

    if opciones[seleccion]==config.get_localized_string(30158): # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools
        data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+url+ " " +thumbnail)
        return

    elif opciones[seleccion]==config.get_localized_string(30164): # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os
        os.remove( url )
        xbmc.executebuiltin( "Container.Refresh" )
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion])>2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0

        if len(video_urls[seleccion])>3:
            use_download_and_play = (video_urls[seleccion][3]=="download_and_play")
        else:
            use_download_and_play = False

        view = True

    # Descargar
    elif opciones[seleccion]==config.get_localized_string(30153): # "Descargar"
        
        # El vídeo de más calidad es el último
        mediaurl = video_urls[len(video_urls)-1][1]
        
        # Si no quiere usar filenium para descargas, coge el anterior
        if config.get_setting("filenium_for_download")=="false" and video_urls[len(video_urls)-1][0]=="[filenium]":
            mediaurl = video_urls[len(video_urls)-2][1]

        from core import downloadtools
        keyboard = xbmc.Keyboard(fulltitle)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            title = keyboard.getText()
            downloadtools.downloadtitle(mediaurl,title)
        return

    elif opciones[seleccion]==config.get_localized_string(30154): #"Quitar de favoritos"
        from core import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30159): #"Borrar descarga definitivamente"
        from core import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de la lista'
        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30160): #"Pasar de nuevo a lista de descargas":
        from core import descargas
        descargas.mover_descarga_error_a_pendiente(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30107)) # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30155): #"Añadir a favoritos":
        from core import favoritos
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle)+" ["+channel+"]")
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion]==config.get_localized_string(30156): #"Quitar de lista de descargas":
        from core import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus( extra )))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30157): #"Añadir a lista de descargas":
        from core import descargas
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle))
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            descargas.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30161): #"Añadir a Biblioteca":  # Library
        from platformcode.xbmc import library
        titulo = fulltitle
        if fulltitle=="":
            titulo = title
        library.savelibrary(titulo,url,thumbnail,server,plot,canal=channel,category=category,Serie=Serie)
        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , fulltitle , config.get_localized_string(30135)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30162): #"Buscar Trailer":
        config.set_setting("subtitulo", "false")
        import sys
        xbmc.executebuiltin("Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s&server=%s)" % ( sys.argv[ 0 ] , "trailertools" , "buscartrailer" , urllib.quote_plus( category ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" ) , server ))
        return

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("[xbmctools.py] mediaurl="+mediaurl)
    if mediaurl=="":
        logger.info("b1")
        if server == "unknown":
            alertUnsopportedServer()
        else:
            alertnodisponibleserver(server)
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time>0:
        logger.info("b2")
        continuar = handle_wait(wait_time,server,"Cargando vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        logger.info("b3")
        xlistitem = getLibraryInfo(mediaurl)
    else:
        logger.info("b4")
        try:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail, path=mediaurl)
        except:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        xlistitem.setInfo( "video", { "Title": title, "Plot" : plot , "Studio" : channel , "Genre" : category } )

    # Descarga el subtitulo
    if channel=="cuevana" and subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        logger.info("b5")
        try:
            import os
            ficherosubtitulo = os.path.join( config.get_data_path(), 'subtitulo.srt' )
            if os.path.exists(ficherosubtitulo):
                try:
                  os.remove(ficherosubtitulo)
                except IOError:
                  logger.info("Error al eliminar el archivo subtitulo.srt "+ficherosubtitulo)
                  raise
        
            from core import scrapertools
            data = scrapertools.cache_page(subtitle)
            #print data
            fichero = open(ficherosubtitulo,"w")
            fichero.write(data)
            fichero.close()
            #from core import downloadtools
            #downloadtools.downloadfile(subtitle, ficherosubtitulo )
        except:
            logger.info("Error al descargar el subtítulo")

    # Lanza el reproductor
    if strmfile: #Si es un fichero strm no hace falta el play
        logger.info("b6")
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,xlistitem)
        #if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        #    logger.info("[xbmctools.py] Con subtitulos")
        #    setSubtitles()
    else:
        logger.info("b7")
        if use_download_and_play or config.get_setting("player_mode")=="3":
            logger.info("b11")
            import download_and_play

            # El canal exige usar download_and_play, pero el usuario no lo ha elegido -> le quitamos los diálogos
            if use_download_and_play and config.get_setting("player_mode")!="3":
                download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") , show_dialog=False )
            else:
                download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") )
            return

        elif config.get_setting("player_mode")=="0":
            logger.info("b8")
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()
            playlist.add( mediaurl, xlistitem )

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info("[xbmctools.py] playersettings="+playersettings)
        
            player_type = xbmc.PLAYER_CORE_AUTO
            if playersettings == "0":
                player_type = xbmc.PLAYER_CORE_AUTO
                logger.info("[xbmctools.py] PLAYER_CORE_AUTO")
            elif playersettings == "1":
                player_type = xbmc.PLAYER_CORE_MPLAYER
                logger.info("[xbmctools.py] PLAYER_CORE_MPLAYER")
            elif playersettings == "2":
                player_type = xbmc.PLAYER_CORE_DVDPLAYER
                logger.info("[xbmctools.py] PLAYER_CORE_DVDPLAYER")
        
            xbmcPlayer = xbmc.Player( player_type )
            xbmcPlayer.play(playlist)
            
            if channel=="cuevana" and subtitle!="":
                logger.info("subtitulo="+subtitle)
                if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
                    logger.info("[xbmctools.py] Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode")=="1":
            logger.info("b9")
            #xlistitem.setProperty('IsPlayable', 'true')
            #xlistitem.setProperty('path', mediaurl)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=mediaurl))
        
        elif config.get_setting("player_mode")=="2":
            logger.info("b10")
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )

    if (config.get_setting("subtitulo") == "true") and view:
        logger.info("b11")
        from core import subtitletools
        wait2second()
        subtitletools.set_Subtitle()
        if subtitle!="":
            xbmc.Player().setSubtitles(subtitle)
def play_video(channel="",server="",url="",category="",title="", thumbnail="",plot="",extra="",desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False,Serie="",subtitle="", video_password="",fulltitle=""):
    from servers import servertools
    import sys
    import xbmcgui,xbmc
    try:
        logger.info("[xbmctools.py] play_video(channel=%s, server=%s, url=%s, category=%s, title=%s, thumbnail=%s, plot=%s, desdefavoritos=%s, desdedescargados=%s, desderrordescargas=%s, strmfile=%s, Serie=%s, subtitle=%s" % (channel,server,url,category,title,thumbnail,plot,desdefavoritos,desdedescargados,desderrordescargas,strmfile,Serie,subtitle))
    except:
        pass

    try:
        server = server.lower()
    except:
        server = ""

    if server=="":
        server="directo"

    try:
        from core import descargas
        download_enable=True
    except:
        download_enable=False

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action="+default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode")=="0" and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(server,url,video_password,muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        
        for video_url in video_urls:
            opciones.append(config.get_localized_string(30151) + " " + video_url[0])

        if server=="local":
            opciones.append(config.get_localized_string(30164))
        else:
            if download_enable:
                opcion = config.get_localized_string(30153)
                opciones.append(opcion) # "Descargar"
    
            if channel=="favoritos": 
                opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"
            else:
                opciones.append(config.get_localized_string(30155)) # "Añadir a favoritos"
        
            if not strmfile:
                opciones.append(config.get_localized_string(30161)) # "Añadir a Biblioteca"
        
            if download_enable:
                if channel!="descargas":
                    opciones.append(config.get_localized_string(30157)) # "Añadir a lista de descargas"
                else:
                    if category=="errores":
                        opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
                        opciones.append(config.get_localized_string(30160)) # "Pasar de nuevo a lista de descargas"
                    else:
                        opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
    
            if config.get_setting("jdownloader_enabled")=="true":
                opciones.append(config.get_localized_string(30158)) # "Enviar a JDownloader"
            if config.get_setting("pyload_enabled")=="true":
                opciones.append(config.get_localized_string(30158).replace("jDownloader","pyLoad")) # "Enviar a pyLoad"

        if default_action=="3":
            seleccion = len(opciones)-1
    
        # Busqueda de trailers en youtube    
        if not channel in ["Trailer","ecarteleratrailers"]:
            opciones.append(config.get_localized_string(30162)) # "Buscar Trailer"

    # Si no puedes ver el vídeo te informa
    else:
        import xbmcgui
        if server!="":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok( "Non è possibile guardare il video perché...",motivo.split("<br/>")[0],motivo.split("<br/>")[1],url)
            else:
                resultado = advertencia.ok( "Non è possibile guardare il video perché...",motivo,url)
        else:
            resultado = advertencia.ok( "Non è possibile guardare il video perché...","Il server che lo ospita non è","ancora supportato da streamondemand",url)

        if channel=="favoritos": 
            opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"

        if channel=="descargas":
            if category=="errores":
                opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
        
        if len(opciones)==0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action=="0": # and server!="torrent":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163), opciones) # "Elige una opción"
        #dia.close()
        '''
        elif default_action=="0" and server=="torrent":
            advertencia = xbmcgui.Dialog()
            logger.info("video_urls[0]="+str(video_urls[0][1]))
            if puedes and ('"status":"COMPLETED"' in video_urls[0][1] or '"percent_done":100' in video_urls[0][1]):
                listo  = "y está listo para ver"
            else:
                listo = "y se está descargando"
            resultado = advertencia.ok( "Torrent" , "El torrent ha sido añadido a la lista" , listo )
            seleccion=-1
        '''
    elif default_action=="1":
        seleccion = 0
    elif default_action=="2":
        seleccion = len(video_urls)-1
    elif default_action=="3":
        seleccion = seleccion
    else:
        seleccion=0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC 
    if seleccion==-1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),False,listitem)    # JUR Added
        #if config.get_setting("subtitulo") == "true":
        #    config.set_setting("subtitulo", "false")
        return

    if opciones[seleccion]==config.get_localized_string(30158): # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools
        
        if subtitle!="":
            data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+url+ " " +thumbnail + " " + subtitle)
        else:
            data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+url+ " " +thumbnail)

        return

    if opciones[seleccion]==config.get_localized_string(30158).replace("jDownloader","pyLoad"): # "Enviar a pyLoad"
        logger.info("Enviando a pyload...")

        if Serie!="":
            package_name = Serie
        else:
            package_name = "streamondemand"

        from core import pyload_client
        pyload_client.download(url=url,package_name=package_name)
        return

    elif opciones[seleccion]==config.get_localized_string(30164): # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os
        os.remove( url )
        xbmc.executebuiltin( "Container.Refresh" )
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion])>2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0
        view = True

    # Descargar
    elif opciones[seleccion]==config.get_localized_string(30153): # "Descargar"
        import xbmc
        # El vídeo de más calidad es el último
        mediaurl = video_urls[len(video_urls)-1][1]

        from core import downloadtools
        keyboard = xbmc.Keyboard(fulltitle)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            title = keyboard.getText()
            devuelve = downloadtools.downloadbest(video_urls,title)
            
            if devuelve==0:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Scaricato con successo")
            elif devuelve==-1:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Download interrotto")
            else:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Errore nel download")
        return

    elif opciones[seleccion]==config.get_localized_string(30154): #"Quitar de favoritos"
        from core import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30159): #"Borrar descarga definitivamente"
        from core import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de la lista'
        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30160): #"Pasar de nuevo a lista de descargas":
        from core import descargas
        descargas.mover_descarga_error_a_pendiente(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30107)) # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30155): #"Añadir a favoritos":
        from core import favoritos
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle)+" ["+channel+"]")
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion]==config.get_localized_string(30156): #"Quitar de lista de descargas":
        from core import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus( extra )))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30157): #"Añadir a lista de descargas":
        from core import descargas
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle))
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            descargas.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30161): #"Añadir a Biblioteca":  # Library
        from platformcode import library
        titulo = fulltitle
        if fulltitle=="":
            titulo = title
        library.savelibrary(titulo,url,thumbnail,server,plot,canal=channel,category=category,Serie=Serie)
        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , fulltitle , config.get_localized_string(30135)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30162): #"Buscar Trailer":
        config.set_setting("subtitulo", "false")
        import sys
        xbmc.executebuiltin("Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s&server=%s)" % ( sys.argv[ 0 ] , "trailertools" , "buscartrailer" , urllib.quote_plus( category ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" ) , server ))
        return

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("[xbmctools.py] mediaurl="+mediaurl)
    if mediaurl=="":
        logger.info("b1")
        if server == "unknown":
            alertUnsopportedServer()
        else:
            alertnodisponibleserver(server)
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time>0:
        logger.info("b2")
        continuar = handle_wait(wait_time,server,"Caricamento vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        logger.info("b3")
        xlistitem = getLibraryInfo(mediaurl)
    else:
        logger.info("b4")
        try:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail, path=mediaurl)
        except:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        xlistitem.setInfo( "video", { "Title": title, "Plot" : plot , "Studio" : channel , "Genre" : category } )

    # Descarga el subtitulo
    if channel=="cuevana" and subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        logger.info("b5")
        try:
            import os
            ficherosubtitulo = os.path.join( config.get_data_path(), 'subtitulo.srt' )
            if os.path.exists(ficherosubtitulo):
                try:
                  os.remove(ficherosubtitulo)
                except IOError:
                  logger.info("Errore nell'eliminazione del file subtitulo.srt "+ficherosubtitulo)
                  raise
        
            from core import scrapertools
            data = scrapertools.cache_page(subtitle)
            #print data
            fichero = open(ficherosubtitulo,"w")
            fichero.write(data)
            fichero.close()
            #from core import downloadtools
            #downloadtools.downloadfile(subtitle, ficherosubtitulo )
        except:
            logger.info("Errore nel download del sottotitolo")

    # Lanza el reproductor
    if strmfile: #Si es un fichero strm no hace falta el play
        logger.info("b6")
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,xlistitem)
        #if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        #    logger.info("[xbmctools.py] Con subtitulos")
        #    setSubtitles()
        
    else:
        logger.info("b7")
        logger.info("player_mode="+config.get_setting("player_mode"))
        logger.info("mediaurl="+mediaurl)
        if config.get_setting("player_mode")=="3" or "megacrypter.com" in mediaurl:
            logger.info("b11")
            import download_and_play
            download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") )
            return

        elif config.get_setting("player_mode")=="0" or (config.get_setting("player_mode")=="3" and mediaurl.startswith("rtmp")):
            logger.info("b8")
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()
            playlist.add( mediaurl, xlistitem )

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info("[xbmctools.py] playersettings="+playersettings)
        
            player_type = xbmc.PLAYER_CORE_AUTO
            if playersettings == "0":
                player_type = xbmc.PLAYER_CORE_AUTO
                logger.info("[xbmctools.py] PLAYER_CORE_AUTO")
            elif playersettings == "1":
                player_type = xbmc.PLAYER_CORE_MPLAYER
                logger.info("[xbmctools.py] PLAYER_CORE_MPLAYER")
            elif playersettings == "2":
                player_type = xbmc.PLAYER_CORE_DVDPLAYER
                logger.info("[xbmctools.py] PLAYER_CORE_DVDPLAYER")
        
            xbmcPlayer = xbmc.Player( player_type )
            xbmcPlayer.play(playlist)
            
            if channel=="cuevana" and subtitle!="":
                logger.info("subtitulo="+subtitle)
                if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
                    logger.info("[xbmctools.py] Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode")=="1":
            logger.info("b9")
            #xlistitem.setProperty('IsPlayable', 'true')
            #xlistitem.setProperty('path', mediaurl)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=mediaurl))
        
        elif config.get_setting("player_mode")=="2":
            logger.info("b10")
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )
        
    # Descarga en segundo plano para vidxden, sólo en modo free
    '''
    elif server=="vidxden" and seleccion==0:
        from core import downloadtools
        import thread,os
        import xbmc
        
        logger.info("[xbmctools.py] ---------------------------------")
        logger.info("[xbmctools.py] DESCARGA EN SEGUNDO PLANO")
        logger.info("[xbmctools.py]   de "+mediaurl)
        temp_file = config.get_temp_file("background.file")
        if os.path.exists(temp_file):
            os.remove(temp_file)
        logger.info("[xbmctools.py]   a "+temp_file)
        logger.info("[xbmctools.py] ---------------------------------")
        thread.start_new_thread(downloadtools.downloadfile, (mediaurl,temp_file), {'silent':True})

        handle_wait(60,"Descarga en segundo plano","Se está descargando un trozo antes de empezar")

        playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
        playlist.clear()
        playlist.add( temp_file, xlistitem )
    
        player_type = xbmc.PLAYER_CORE_AUTO
        xbmcPlayer = xbmc.Player( player_type )
        xbmcPlayer.play(playlist)
        
        while xbmcPlayer.isPlaying():
            xbmc.sleep(5000)
            logger.info("sigo aquí...")

        logger.info("fin")
    '''

    if config.get_setting("subtitulo") == "true" and view:
        logger.info("b11")
        from platformcode import subtitletools
        wait2second()
        subtitletools.set_Subtitle()
        if subtitle!="":
            xbmc.Player().setSubtitles(subtitle)
    #FIXME: Qué cosa más fea...
    elif channel=="moviezet":
        xbmc.Player().setSubtitles(subtitle)
Ejemplo n.º 25
0
def menu_video(item):
    itemlist = []
    logger.info("menu_video url=" + item.url + ", server=" + item.server +
                ", fulltitle=" + item.fulltitle)

    from servers import servertools
    video_urls, puede, motivo = servertools.resolve_video_urls_for_playing(
        item.server, item.url, video_password="", muestra_dialogo=False)

    if puede:
        for video_url in video_urls:
            itemlist.append(
                Item(channel=item.channel,
                     title="Ver " + video_url[0],
                     url=video_url[1],
                     action="play_video"))

        refered_item_encoded = urllib.quote(item.title.replace(
            "|", "-")) + "|" + urllib.quote(item.server) + "|" + urllib.quote(
                item.url) + "|" + urllib.quote(item.extra)

        itemlist.append(
            Item(channel=item.channel,
                 title="Descargar",
                 action="descargar",
                 url=refered_item_encoded,
                 fulltitle=urllib.quote(item.fulltitle)))

        if item.channel != "favoritos":
            itemlist.append(
                Item(channel=item.channel,
                     title="Añadir a favoritos",
                     action="add_to_favorites",
                     url=refered_item_encoded,
                     fulltitle=urllib.quote(item.fulltitle)))
        else:
            itemlist.append(
                Item(channel=item.channel,
                     title="Quitar de favoritos",
                     action="remove_from_favorites",
                     url=refered_item_encoded,
                     fulltitle=urllib.quote(item.fulltitle)))

        if item.channel != "descargas":
            itemlist.append(
                Item(channel=item.channel,
                     title="Añadir a la lista de descargas",
                     action="add_to_downloads",
                     url=refered_item_encoded,
                     fulltitle=urllib.quote(item.fulltitle)))
        else:
            if item.category == "errores":
                itemlist.append(
                    Item(
                        channel=item.channel,
                        title="Quitar definitivamente de la lista de descargas",
                        action="remove_from_error_downloads",
                        url=refered_item_encoded))
                itemlist.append(
                    Item(channel=item.channel,
                         title="Pasar de nuevo a la lista de descargas",
                         action="add_again_to_downloads",
                         url=refered_item_encoded))
            else:
                itemlist.append(
                    Item(channel=item.channel,
                         title="Quitar de la lista de descargas",
                         action="remove_from_downloads",
                         url=refered_item_encoded))

        itemlist.append(
            Item(channel=item.channel,
                 title="Enviar a jdownloader",
                 action="send_to_jdownloader",
                 url=refered_item_encoded))
        itemlist.append(
            Item(channel=item.channel,
                 title="Buscar trailer",
                 action="search_trailer",
                 url=refered_item_encoded))
        if item.category == "wiideoteca":
            itemlist.append(
                Item(channel=item.channel,
                     title="Marcar como Ultimo Episodio Visto",
                     action="UltimoVisto",
                     url=item.extra,
                     fulltitle=item.fulltitle))

    # Si no puedes ver el vídeo te informa
    else:
        itemlist.append(Item(title="No puedes ver ese vídeo porque..."))
        if item.server != "":
            if "<br/>" in motivo:
                itemlist.append(Item(title=motivo.split("<br/>")[0]))
                itemlist.append(Item(title=motivo.split("<br/>")[1]))
                itemlist.append(Item(title=item.url))
            else:
                itemlist.append(Item(title=motivo))
                itemlist.append(Item(title=item.url))
        else:
            itemlist.append(
                Item(title="El servidor donde está alojado no está"))
            itemlist.append(Item(title="soportado en pelisalacarta todavía"))
            itemlist.append(Item(title=item.url))

    return itemlist
def download_all_episodes(item, channel, first_episode="", preferred_server="vidspot", filter_language=""):
    logger.info("streamondemand-pureita.platformcode.launcher download_all_episodes, show=" + item.show)
    show_title = item.show

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

    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if "###" in item.extra:
        action = item.extra.split("###")[0]
        item.extra = item.extra.split("###")[1]

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

    # Ordena los episodios para que funcione el filtro de first_episode
    episode_itemlist = sorted(episode_itemlist, key=lambda Item: Item.title)

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

    best_server = preferred_server
    worst_server = "moevideos"

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

    for episode_item in episode_itemlist:
        try:
            logger.info(
                "streamondemand-pureita.platformcode.launcher download_all_episodes, episode=" + episode_item.title
            )
            episode_title = scrapertools.get_match(episode_item.title, "(\d+x\d+)")
            logger.info("streamondemand-pureita.platformcode.launcher download_all_episodes, episode=" + episode_title)
        except:
            import traceback

            logger.info(traceback.format_exc())
            continue

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

        if episodio_ya_descargado(show_title, episode_title):
            continue

        if not empezar:
            continue

        # Extrae los mirrors
        try:
            mirrors_itemlist = channel.findvideos(episode_item)
        except:
            mirrors_itemlist = servertools.find_video_items(episode_item)
        print mirrors_itemlist

        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 "(Latino)" 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)
            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(
                "streamondemand-pureita.platformcode.launcher download_all_episodes, mirror=" + mirror_item.title
            )

            if "(Español)" in mirror_item.title:
                idioma = "(Español)"
                codigo_idioma = "es"
            elif "(Latino)" in mirror_item.title:
                idioma = "(Latino)"
                codigo_idioma = "lat"
            elif "(VOS)" in mirror_item.title:
                idioma = "(VOS)"
                codigo_idioma = "vos"
            elif "(VO)" in mirror_item.title:
                idioma = "(VO)"
                codigo_idioma = "vo"
            else:
                idioma = "(Desconocido)"
                codigo_idioma = "desconocido"

            logger.info(
                "streamondemand-pureita.platformcode.launcher filter_language=#"
                + filter_language
                + "#, codigo_idioma=#"
                + codigo_idioma
                + "#"
            )
            if filter_language == "" or (filter_language != "" and filter_language == codigo_idioma):
                logger.info("streamondemand-pureita.platformcode.launcher download_all_episodes, downloading mirror")
            else:
                logger.info(
                    "streamondemand-pureita.platformcode.launcher language " + codigo_idioma + " filtered, skipping"
                )
                continue

            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(
                        "streamondemand-pureita.platformcode.launcher download_all_episodes, downloading mirror started..."
                    )
                    # El vídeo de más calidad es el último
                    mediaurl = video_urls[len(video_urls) - 1][1]
                    devuelve = downloadtools.downloadbest(
                        video_urls,
                        show_title + " " + episode_title + " " + idioma + " [" + video_item.server + "]",
                        continuar=False,
                    )

                    if devuelve == 0:
                        logger.info("streamondemand-pureita.platformcode.launcher download_all_episodes, download ok")
                        descargado = True
                        break
                    elif devuelve == -1:
                        try:
                            import xbmcgui

                            advertencia = xbmcgui.Dialog()
                            resultado = advertencia.ok("plugin", "Download interrotto")
                        except:
                            pass
                        return
                    else:
                        logger.info(
                            "streamondemand-pureita.platformcode.launcher download_all_episodes, download error, try another mirror"
                        )
                        continue

                else:
                    logger.info(
                        "streamondemand-pureita.platformcode.launcher download_all_episodes, downloading mirror not available... trying next"
                    )

        if not descargado:
            logger.info(
                "streamondemand-pureita.platformcode.launcher download_all_episodes, EPISODIO NO DESCARGADO "
                + episode_title
            )
def MenuVideo(item):
    logger.info("[launcher.py] MenuVideo")
    
    # Lista de Opciones Disponibles
    OpcionesDisponibles =[]
    OpcionesDisponibles.append(config.get_localized_string(30151)) #"Ver el vídeo"
    OpcionesDisponibles.append(config.get_localized_string(30164)) #"Borrar este fichero"
    OpcionesDisponibles.append(config.get_localized_string(30153)) #"Descargar"
    OpcionesDisponibles.append(config.get_localized_string(30154)) #"Quitar de favoritos"
    OpcionesDisponibles.append(config.get_localized_string(30155)) #"Añadir a favoritos"
    OpcionesDisponibles.append(config.get_localized_string(30161)) #"Añadir a Biblioteca"
    OpcionesDisponibles.append(config.get_localized_string(30157)) #"Añadir a lista de descargas"
    OpcionesDisponibles.append(config.get_localized_string(30159)) #"Borrar descarga definitivamente"
    OpcionesDisponibles.append(config.get_localized_string(30160)) #"Pasar de nuevo a lista de descargas"
    OpcionesDisponibles.append(config.get_localized_string(30156)) #"Quitar de lista de descargas"
    OpcionesDisponibles.append(config.get_localized_string(30158)) #"Enviar a JDownloader"
    OpcionesDisponibles.append(config.get_localized_string(30158).replace("jDownloader","pyLoad")) # "Enviar a pyLoad"
    OpcionesDisponibles.append(config.get_localized_string(30162)) #"Buscar Trailer"
    
    
    itemlist = []
    if item.server=="": item.server="directo"   
    default_action = config.get_setting("default_action")
    
    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    from servers import servertools
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(item.server,item.url,item.password, True)
    
 
    
    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
      for video_url in video_urls:
        itemlist.append(Item(title=OpcionesDisponibles[0] + " " + video_url[0], url=video_url, action="play_video"))
        
      if item.server=="local":
        itemlist.append(Item(title=OpcionesDisponibles[1], url=video_urls, action="delete"))

      if not item.server=="local":
        itemlist.append(Item(title=OpcionesDisponibles[2], url=video_urls, action="download")) #"Descargar"

      if item.channel=="favoritos":
        itemlist.append(Item(title=OpcionesDisponibles[3], url=video_urls, action="remove_from_favorites")) #"Quitar de favoritos"
      
      if not item.channel=="favoritos":
        itemlist.append(Item(title=OpcionesDisponibles[4], url=video_urls, action="add_to_favorites"))  #"Añadir a favoritos"
      
      if not item.channel=="library":
        itemlist.append(Item(title=OpcionesDisponibles[5], url=video_urls, action="add_to_library")) #"Añadir a Biblioteca"
      if item.channel=="library":
        itemlist.append(Item(title="Quitar de la Biblioteca", url=video_urls, action="remove_from_library")) #"Añadir a Biblioteca"

      if not item.channel=="descargas":
        itemlist.append(Item(title=OpcionesDisponibles[6], url=video_urls, action="add_to_downloads")) #"Añadir a lista de descargas"
            
      if item.channel =="descargas" and item.category=="errores":
        itemlist.append(Item(title=OpcionesDisponibles[7], url=video_urls, action="remove_from_error_downloads")) #"Borrar descarga definitivamente"
        itemlist.append(Item(title=OpcionesDisponibles[8], url=video_urls, action="add_again_to_downloads")) #"Pasar de nuevo a lista de descargas"          
      if item.channel =="descargas" and item.category=="pendientes": 
        itemlist.append(Item(title=OpcionesDisponibles[9], url=video_urls, action="remove_from_downloads")) #"Quitar de lista de descargas"

      if config.get_setting("jdownloader_enabled")=="true": 
        itemlist.append(Item(title=OpcionesDisponibles[10], url=video_urls, action="send_to_jdownloader")) #"Enviar a JDownloader"
          
      if config.get_setting("pyload_enabled")=="true": 
        itemlist.append(Item(title=OpcionesDisponibles[11], url=video_urls, action="send_to_pyLoad")) #"Enviar a pyLoad"

      if not item.channel in ["trailertools","ecarteleratrailers"]: 
        itemlist.append(Item(title=OpcionesDisponibles[12], url=video_urls, action="search_trailer")) # "Buscar Trailer" 
        
    else:
        if item.server!="":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok( "No puedes ver ese vídeo porque...",motivo.split("<br/>")[0],motivo.split("<br/>")[1],item.url)
            else:
                resultado = advertencia.ok( "No puedes ver ese vídeo porque...",motivo,item.url)
        else:
            resultado = advertencia.ok( "No puedes ver ese vídeo porque...","El servidor donde está alojado no está","soportado en pelisalacarta todavía",url)

            if item.channel=="favoritos":
              itemlist.append(Item(title=OpcionesDisponibles[3], url=video_urls, action="remove_from_favorites")) #"Quitar de favoritos"
            if item.channel=="library":
              itemlist.append(Item(title="Quitar de la Biblioteca", url=video_urls, action="remove_from_library")) #"Añadir a Biblioteca"

            if item.channel =="descargas" and item.category=="errores":
              itemlist.append(Item(title=OpcionesDisponibles[7], url=video_urls, action="remove_from_error_downloads")) #"Borrar descarga definitivamente"         
            if item.channel =="descargas" and not item.category=="errores": 
              itemlist.append(Item(title=OpcionesDisponibles[9], url=video_urls, action="remove_from_downloads")) #"Quitar de lista de descargas"

    return itemlist
Ejemplo n.º 28
0
def play_video(item,desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False):
    logger.info('tvalacarta.platformcode.xbmctools add_new_video item='+item.tostring())
    
    if item.url.startswith("http://"):
        item.url = item.url.replace(" ","%20")

    try:
        item.server = item.server.lower()
    except:
        item.server = ""

    if item.server=="":
        item.server="directo"

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action="+default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode")=="0" and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(item.server , item.url , item.video_password , item.muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            opciones.append(config.get_localized_string(30151) + " " + video_url[0])

        if item.server=="local":
            opciones.append(config.get_localized_string(30164))
        else:
            opcion = config.get_localized_string(30153)
            opciones.append(opcion) # "Descargar"
    
            if item.channel=="favoritos": 
                opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"
            else:
                opciones.append(config.get_localized_string(30155)) # "Añadir a favoritos"
        
            #if not strmfile:
            #    opciones.append(config.get_localized_string(30161)) # "Añadir a Biblioteca"
        
            if item.channel!="descargas":
                opciones.append(config.get_localized_string(30157)) # "Añadir a lista de descargas"
            else:
                if item.category=="errores":
                    opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
                    opciones.append(config.get_localized_string(30160)) # "Pasar de nuevo a lista de descargas"
                else:
                    opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"

            #opciones.append(config.get_localized_string(30158)) # "Enviar a JDownloader"

        if default_action=="3":
            seleccion = len(opciones)-1
    
    # Si no puedes ver el vídeo te informa
    else:
        alert_no_puedes_ver_video(item.server,"",motivo)

        if item.channel=="favoritos": 
            opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"

        if item.channel=="descargas":
            if item.category=="errores":
                opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
        
        if len(opciones)==0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action=="0":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163), opciones) # "Elige una opción"
        #dia.close()
    elif default_action=="1":
        seleccion = len(video_urls)-1
    elif default_action=="2":
        seleccion = 0
    elif default_action=="3":
        seleccion = seleccion
    else:
        seleccion=0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC 
    if seleccion==-1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem( item.title, iconImage="DefaultVideo.png", thumbnailImage=item.thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),False,listitem)
        return

    if opciones[seleccion]==config.get_localized_string(30158): # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools
        data = scrapertools.cachePage(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+item.url+ " " +item.thumbnail)
        return

    elif opciones[seleccion]==config.get_localized_string(30164): # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os

        os.remove( item.url )

        if os.path.exists(item.url[:-4]+".tbn"):
            os.remove( item.url[:-4]+".tbn" )

        if os.path.exists(item.url[:-4]+".nfo"):
            os.remove( item.url[:-4]+".nfo" )

        xbmc.executebuiltin( "Container.Refresh" )
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion])>2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0

        if len(video_urls[seleccion])>3:
            use_download_and_play = (video_urls[seleccion][3]=="download_and_play")
        else:
            use_download_and_play = False

        view = True

    # Descargar
    elif opciones[seleccion]==config.get_localized_string(30153): # "Descargar"
        
        # El vídeo de más calidad es el primero
        mediaurl = video_urls[0][1]
        
        from core import downloadtools
        keyboard = xbmc.Keyboard(item.fulltitle)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            title = keyboard.getText()
            downloadtools.downloadtitle(mediaurl,title)
        return

    elif opciones[seleccion]==config.get_localized_string(30154): #"Quitar de favoritos"
        from channels import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30102) , item.title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30159): #"Borrar descarga definitivamente"
        from channels import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30106)) # 'Se ha quitado de la lista'
        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30160): #"Pasar de nuevo a lista de descargas":
        from channels import descargas
        descargas.mover_descarga_error_a_pendiente(urllib.unquote_plus( item.extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30107)) # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30155): #"Añadir a favoritos":
        from channels import favoritos
        from core import downloadtools

        keyboard = xbmc.Keyboard(item.fulltitle)
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=title,url=item.url,thumbnail=item.thumbnail,server=item.server,plot=item.plot,fulltitle=item.title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion]==config.get_localized_string(30156): #"Quitar de lista de descargas":
        from channels import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus( item.extra )))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30106)) # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30157): #"Añadir a lista de descargas":

        from channels import descargas
        from core import downloadtools

        if item.show<>"":
            filename = item.show+" - "+item.title
        elif item.show_title<>"":
            filename = item.show_title+" - "+item.title
        else:
            filename = item.title

        keyboard = xbmc.Keyboard(filename)
        keyboard.doModal()
        if keyboard.isConfirmed():
            filename = keyboard.getText()
            descargas.savebookmark(titulo=filename,url=item.url,thumbnail=item.thumbnail,server=item.server,plot=item.plot,fulltitle=filename)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30101) , filename , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30161): #"Añadir a Biblioteca":  # Library
        from platformcode.xbmc import library
        titulo = item.fulltitle
        if item.fulltitle=="":
            titulo = item.title
        library.savelibrary(titulo , item.url , item.thumbnail , item.server , item.plot , canal=item.channel , category=item.category , Serie=item.Serie)
        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , item.fulltitle , config.get_localized_string(30135)) # 'se ha añadido a la lista de descargas'
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time>0:
    
        continuar = handle_wait(wait_time,server,"Cargando vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        xlistitem = getLibraryInfo(mediaurl)
    else:
        try:
            xlistitem = xbmcgui.ListItem( item.title, iconImage="DefaultVideo.png", thumbnailImage=item.thumbnail, path=mediaurl)
        except:
            xlistitem = xbmcgui.ListItem( item.title, iconImage="DefaultVideo.png", thumbnailImage=item.thumbnail)
        xlistitem.setInfo( "video", { "Title": item.title, "Plot" : item.plot , "Studio" : item.channel , "Genre" : item.category } )

    # Lanza el reproductor
    if strmfile: #Si es un fichero strm no hace falta el play
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,xlistitem)
        #if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        #    logger.info("tvalacarta.platformcode.xbmctools Con subtitulos")
        #    setSubtitles()
    else:
        if use_download_and_play or config.get_setting("player_mode")=="3":
            import download_and_play

            # El canal exige usar download_and_play, pero el usuario no lo ha elegido -> le quitamos los diálogos
            if use_download_and_play and config.get_setting("player_mode")!="3":
                download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") , show_dialog=False )
            else:
                download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") )
            return

        elif config.get_setting("player_mode")=="0":
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()
            playlist.add( mediaurl, xlistitem )

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info("tvalacarta.platformcode.xbmctools playersettings="+playersettings)
        
            player_type = xbmc.PLAYER_CORE_AUTO
            if playersettings == "0":
                player_type = xbmc.PLAYER_CORE_AUTO
                logger.info("tvalacarta.platformcode.xbmctools PLAYER_CORE_AUTO")
            elif playersettings == "1":
                player_type = xbmc.PLAYER_CORE_MPLAYER
                logger.info("tvalacarta.platformcode.xbmctools PLAYER_CORE_MPLAYER")
            elif playersettings == "2":
                player_type = xbmc.PLAYER_CORE_DVDPLAYER
                logger.info("tvalacarta.platformcode.xbmctools PLAYER_CORE_DVDPLAYER")
        
            xbmcPlayer = xbmc.Player( player_type )
            xbmcPlayer.play(playlist)

        elif config.get_setting("player_mode")=="1":
            #xlistitem.setProperty('IsPlayable', 'true')
            #xlistitem.setProperty('path', mediaurl)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=mediaurl))
        
        elif config.get_setting("player_mode")=="2":
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )

    if (config.get_setting("subtitulo") == "true") and view:
        from core import subtitletools
        wait2second()
        subtitletools.set_Subtitle()
        if subtitle!="":
            xbmc.Player().setSubtitles(subtitle)
Ejemplo n.º 29
0
def downloadall(item):
    logger.info("[descargas.py] downloadall")

    if usingsamba(DOWNLOAD_LIST_PATH):
        ficheros = samba.get_files(DOWNLOAD_LIST_PATH)
    else:
        ficheros = os.listdir(DOWNLOAD_LIST_PATH)
    ficheros.sort()

    for fichero in ficheros:
        if fichero.endswith('.txt'):
            try:
                item = LeerDescarga(fichero, DOWNLOAD_LIST_PATH)
                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
                nfofilepath = downloadtools.getfilefromtitle(
                    "sample.nfo", item.title)
                outfile = open(nfofilepath, "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 != "":
                    thumbnailfile = downloadtools.getfilefromtitle(
                        item.thumbnail, item.title)
                    thumbnailfile = thumbnailfile[:-4] + ".tbn"
                    try:
                        downloadtools.downloadfile(item.thumbnail,
                                                   thumbnailfile)
                    except:
                        logger.info(
                            "[descargas.py] error al descargar thumbnail")
                        for line in sys.exc_info():
                            logger.error("%s" % line)

                dev = downloadtools.downloadbest(video_urls, item.title)
                if dev == -1:
                    logger.info("[descargas.py] Descarga cancelada")
                    break
                elif dev == -2:
                    logger.info("[descargas.py] ERROR EN DESCARGA DE " +
                                fichero)
                    BorrarDescarga(item, DOWNLOAD_LIST_PATH)
                    GuardarDescarga(item, ERROR_PATH)
                else:
                    BorrarDescarga(item, DOWNLOAD_LIST_PATH)
            except:
                logger.info("[descargas.py] ERROR EN DESCARGA DE " + fichero)
                import sys
                for line in sys.exc_info():
                    logger.error("%s" % line)
                    GuardarDescarga(item, ERROR_PATH)
                    BorrarDescarga(item, DOWNLOAD_LIST_PATH)

    return ""
def download_all_episodes(item,
                          channel,
                          first_episode="",
                          preferred_server="vidspot",
                          filter_language=""):
    plugintools.log(
        "streamondemand-pureita.navigation.py download_all_episodes, show=" +
        item.show)
    show_title = item.show

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

    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if "###" in item.extra:
        action = item.extra.split("###")[0]
        item.extra = item.extra.split("###")[1]

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

    # Ordena los episodios para que funcione el filtro de first_episode
    episode_itemlist = sorted(episode_itemlist, key=lambda Item: Item.title)

    from servers import servertools
    from core import downloadtools

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

    for episode_item in episode_itemlist:
        if episode_item.action == "add_serie_to_library" or episode_item.action == "download_all_episodes":
            continue

        try:
            plugintools.log(
                "streamondemand-pureita.navigation.py download_all_episodes, episode="
                + episode_item.title)
            #episode_title = scrapertools.get_match(episode_item.title,"(\d+x\d+)")
            episode_title = episode_item.title
            episode_title = re.sub(r"\[COLOR [^]]*\]", "", episode_title)
            episode_title = re.sub(r"\[/COLOR\]", "", episode_title)
            plugintools.log(
                "streamondemand-pureita.navigation.py download_all_episodes, episode="
                + episode_title)
        except:
            import traceback
            plugintools.log(traceback.format_exc())
            continue

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

        if episodio_ya_descargado(show_title, episode_title):
            continue

        if not empezar:
            continue

        # Extrae los mirrors
        try:
            #mirrors_itemlist = channel.findvideos(episode_item)
            exec "mirrors_itemlist = channel." + episode_item.action + "(episode_item)"
        except:
            mirrors_itemlist = servertools.find_video_items(episode_item)
        print mirrors_itemlist

        descargado = False

        for mirror_item in mirrors_itemlist:
            plugintools.log(
                "streamondemand-pureita.navigation.py download_all_episodes, mirror="
                + mirror_item.title)

            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:
                    plugintools.log(
                        "streamondemand-pureita.navigation.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]
                    devuelve = downloadtools.downloadbest(
                        video_urls,
                        show_title + " " + episode_title + " [" +
                        video_item.server + "]",
                        continuar=False)
                    if devuelve == 0:
                        plugintools.log(
                            "streamondemand-pureita.navigation.py download_all_episodes, download ok"
                        )
                        descargado = True
                        break
                    elif devuelve == -1:
                        try:
                            import xbmcgui
                            advertencia = xbmcgui.Dialog()
                            resultado = advertencia.ok("plugin",
                                                       "Download interrotto")
                        except:
                            pass
                        return
                    else:
                        plugintools.log(
                            "streamondemand-pureita.navigation.py download_all_episodes, download error, try another mirror"
                        )
                        continue

                else:
                    plugintools.log(
                        "streamondemand-pureita.navigation.py download_all_episodes, downloading mirror not available... trying next"
                    )

        if not descargado:
            plugintools.log(
                "streamondemand-pureita.navigation.py download_all_episodes, EPISODIO NO DESCARGADO "
                + episode_title)
        return itemlist
Ejemplo n.º 31
0
def MenuVideo(item):
    if item.server=="": item.server="directo" 
    default_action = config.get_setting("default_action")
    itemlist = []
    
    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    from servers import servertools
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(item.server,item.url,item.password, True)
 
    
    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
      for video_url in video_urls:
        itemlist.append(Item(title=config.get_localized_string(30151) + " " + video_url[0], url=video_url, action="play_video"))
        
      if item.server=="local":
        itemlist.append(Item(title=config.get_localized_string(30164), url=video_urls, action="delete"))

      if not item.server=="local":
        itemlist.append(Item(title=config.get_localized_string(30153), url=video_urls, action="download")) #"Descargar"

      if item.channel=="favoritos":
        itemlist.append(Item(title=config.get_localized_string(30154), url=video_urls, action="remove_from_favorites")) #"Quitar de favoritos"
      
      if not item.channel=="favoritos":
        itemlist.append(Item(title=config.get_localized_string(30155), url=video_urls, action="add_to_favorites"))  #"Añadir a favoritos"
      
      if not item.channel=="library":
        itemlist.append(Item(title=config.get_localized_string(30161), url=video_urls, action="add_to_library")) #"Añadir a Biblioteca"
        
      if item.channel=="library":
        itemlist.append(Item(title="Quitar de la Biblioteca", url=video_urls, action="remove_from_library")) #"Añadir a Biblioteca"

      if not item.channel=="descargas":
        itemlist.append(Item(title=config.get_localized_string(30157), url=video_urls, action="add_to_downloads")) #"Añadir a lista de descargas"
            
      if item.channel =="descargas" and item.category=="errores":
        itemlist.append(Item(title=config.get_localized_string(30159), url=video_urls, action="remove_from_error_downloads")) #"Borrar descarga definitivamente"
        itemlist.append(Item(title=config.get_localized_string(30160), url=video_urls, action="add_again_to_downloads")) #"Pasar de nuevo a lista de descargas"   
               
      if item.channel =="descargas" and item.category=="pendientes": 
        itemlist.append(Item(title=config.get_localized_string(30156), url=video_urls, action="remove_from_downloads")) #"Quitar de lista de descargas"

      if config.get_setting("jdownloader_enabled")=="true": 
        itemlist.append(Item(title=config.get_localized_string(30158), url=video_urls, action="send_to_jdownloader")) #"Enviar a JDownloader"
          
      if config.get_setting("pyload_enabled")=="true": 
        itemlist.append(Item(title=config.get_localized_string(30158).replace("jDownloader","pyLoad"), url=video_urls, action="send_to_pyLoad")) #"Enviar a pyLoad"

      if not item.channel in ["trailertools","ecarteleratrailers"]: 
        itemlist.append(Item(title=config.get_localized_string(30162), url=video_urls, action="search_trailer")) # "Buscar Trailer" 
        
    else:
        if item.server!="":
          guitools.Dialog_OK( "No puedes ver ese vídeo porque..." , motivo.replace("<br/>","\n") + "\n" + item.url)

        else:
            guitools.Dialog_OK("No puedes ver ese vídeo porque...","El servidor donde está alojado no está\nsoportado en pelisalacarta todavía\n"+url)

            if item.channel=="favoritos":
              itemlist.append(Item(title=config.get_localized_string(30154), url=video_urls, action="remove_from_favorites")) #"Quitar de favoritos"
            if item.channel=="library":
              itemlist.append(Item(title="Quitar de la Biblioteca", url=video_urls, action="remove_from_library")) #"Añadir a Biblioteca"

            if item.channel =="descargas" and item.category=="errores":
              itemlist.append(Item(title=config.get_localized_string(30159), url=video_urls, action="remove_from_error_downloads")) #"Borrar descarga definitivamente"         
            if item.channel =="descargas" and not item.category=="errores": 
              itemlist.append(Item(title=config.get_localized_string(30156), url=video_urls, action="remove_from_downloads")) #"Quitar de lista de descargas"

    return itemlist
Ejemplo n.º 32
0
def download_all_episodes(item):
    from servers import servertools
    from core import downloadtools
    from core import scrapertools

    # Esto es poco elegante...
    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if item.extra: action = item.extra
    if item.refered_action: action = item.refered_action
    if "###" in action:
      item.extra = action.split("###")[1]
      action = action.split("###")[0]    
        
    #Importamos el canal    
    channel = ImportarCanal(item.channel)
    
    #Ejecutamos la funcion
    exec "itemlist = channel."+action+"(item)"
    
    #Quitamos estos dos elementos de la lista (si los hay)
    for episodio in itemlist:
      if episodio.action=="add_serie_to_library" or episodio.action=="download_all_episodes":
        itemlist.remove(episodio)
    

    #Abrimos el dialogo
    pDialog = guitools.Dialog_Progress('pelisalacarta', 'Descargando ' + item.show)
    
    for x, episodio in enumerate(itemlist):
    
      #Si se presiona cancelar, se cancela
      if pDialog.iscanceled():
        return
      #Extraemos la Temporada y el Episodio  
      episodio.title = scrapertools.get_season_and_episode(episodio.title)
      
      #Actualizamos el progreso
      pDialog.Actualizar(((x)*100)/len(itemlist), 'Descargando ' + item.show, 'Descargando episodio: ' + episodio.title)

      # Extrae los mirrors
      if hasattr(channel, 'findvideos'):
          mirrors_itemlist = channel.findvideos(episodio)
      else:
          mirrors_itemlist = findvideos(episodio,episodio.channel)
      
      
      descargado = False
      
      #Descarga el primer mirror que funcione
      for mirror_item in mirrors_itemlist:
      
        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 descarga
            if puedes:
            
              # El vídeo de más calidad es el último
              devuelve = downloadtools.downloadbest(video_urls,item.show+" "+episodio.title+" ["+video_item.server+"]",continuar=False)
              if devuelve==0:
                  logger.info("[launcher.py] download_all_episodes - Archivo Descargado")
                  descargado = True
                  break
              elif devuelve==-1:
                  pDialog.Cerrar()
                  logger.info("[launcher.py] download_all_episodes - Descarga abortada")
                  guitools.Dialog_OK("pelisalacarta" , "La descarga ha sido cancelada")
                  return
              else:
                  continue
    pDialog.Cerrar()
Ejemplo n.º 33
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)
Ejemplo n.º 34
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 )
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)
Ejemplo n.º 36
0
def download_all_episodes(item, channel, first_episode=""):
    logger.info("[launcher.py] download_all_episodes, show=" + item.show)
    show_title = item.show

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

    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
    if "###" in item.extra:
        action = item.extra.split("###")[0]
        item.extra = item.extra.split("###")[1]

    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:
        logger.info("[launcher.py] download_all_episodes, episode=" +
                    episode_item.title)
        episode_title = scrapertools.get_match(episode_item.title, "(\d+x\d+)")
        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 = 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 = "(Desconocido)"
            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]
                    devuelve = downloadtools.downloadbest(
                        video_urls,
                        show_title + " " + episode_title + " " + idioma +
                        " [" + video_item.server + "]",
                        continuar=False)

                    if devuelve == 0:
                        logger.info(
                            "[launcher.py] download_all_episodes, download ok")
                        descargado = True
                        break
                    elif devuelve == -1:
                        advertencia = xbmcgui.Dialog()
                        resultado = advertencia.ok("plugin",
                                                   "Descarga abortada")
                        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)
Ejemplo n.º 37
0
def MenuVideo(item):
    logger.info("[launcher.py] MenuVideo")

    # Lista de Opciones Disponibles
    OpcionesDisponibles = []
    OpcionesDisponibles.append(
        config.get_localized_string(30151))  #"Ver el vídeo"
    OpcionesDisponibles.append(
        config.get_localized_string(30164))  #"Borrar este fichero"
    OpcionesDisponibles.append(
        config.get_localized_string(30153))  #"Descargar"
    OpcionesDisponibles.append(
        config.get_localized_string(30154))  #"Quitar de favoritos"
    OpcionesDisponibles.append(
        config.get_localized_string(30155))  #"Añadir a favoritos"
    OpcionesDisponibles.append(
        config.get_localized_string(30161))  #"Añadir a Biblioteca"
    OpcionesDisponibles.append(
        config.get_localized_string(30157))  #"Añadir a lista de descargas"
    OpcionesDisponibles.append(
        config.get_localized_string(30159))  #"Borrar descarga definitivamente"
    OpcionesDisponibles.append(config.get_localized_string(
        30160))  #"Pasar de nuevo a lista de descargas"
    OpcionesDisponibles.append(
        config.get_localized_string(30156))  #"Quitar de lista de descargas"
    OpcionesDisponibles.append(
        config.get_localized_string(30158))  #"Enviar a JDownloader"
    OpcionesDisponibles.append(
        config.get_localized_string(30158).replace(
            "jDownloader", "pyLoad"))  # "Enviar a pyLoad"
    OpcionesDisponibles.append(
        config.get_localized_string(30162))  #"Buscar Trailer"

    itemlist = []
    if item.server == "": item.server = "directo"
    default_action = config.get_setting("default_action")

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    from servers import servertools
    video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
        item.server, item.url, item.password, True)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            itemlist.append(
                Item(title=OpcionesDisponibles[0] + " " + video_url[0],
                     url=video_url,
                     action="play_video"))

        if item.server == "local":
            itemlist.append(
                Item(title=OpcionesDisponibles[1],
                     url=video_urls,
                     action="delete"))

        if not item.server == "local":
            itemlist.append(
                Item(title=OpcionesDisponibles[2],
                     url=video_urls,
                     action="download"))  #"Descargar"

        if item.channel == "favoritos":
            itemlist.append(
                Item(title=OpcionesDisponibles[3],
                     url=video_urls,
                     action="remove_from_favorites"))  #"Quitar de favoritos"

        if not item.channel == "favoritos":
            itemlist.append(
                Item(title=OpcionesDisponibles[4],
                     url=video_urls,
                     action="add_to_favorites"))  #"Añadir a favoritos"

        if not item.channel == "library":
            itemlist.append(
                Item(title=OpcionesDisponibles[5],
                     url=video_urls,
                     action="add_to_library"))  #"Añadir a Biblioteca"
        if item.channel == "library":
            itemlist.append(
                Item(title="Quitar de la Biblioteca",
                     url=video_urls,
                     action="remove_from_library"))  #"Añadir a Biblioteca"

        if not item.channel == "descargas":
            itemlist.append(
                Item(
                    title=OpcionesDisponibles[6],
                    url=video_urls,
                    action="add_to_downloads"))  #"Añadir a lista de descargas"

        if item.channel == "descargas" and item.category == "errores":
            itemlist.append(
                Item(title=OpcionesDisponibles[7],
                     url=video_urls,
                     action="remove_from_error_downloads")
            )  #"Borrar descarga definitivamente"
            itemlist.append(
                Item(title=OpcionesDisponibles[8],
                     url=video_urls,
                     action="add_again_to_downloads")
            )  #"Pasar de nuevo a lista de descargas"
        if item.channel == "descargas" and item.category == "pendientes":
            itemlist.append(
                Item(title=OpcionesDisponibles[9],
                     url=video_urls,
                     action="remove_from_downloads")
            )  #"Quitar de lista de descargas"

        if config.get_setting("jdownloader_enabled") == "true":
            itemlist.append(
                Item(title=OpcionesDisponibles[10],
                     url=video_urls,
                     action="send_to_jdownloader"))  #"Enviar a JDownloader"

        if config.get_setting("pyload_enabled") == "true":
            itemlist.append(
                Item(title=OpcionesDisponibles[11],
                     url=video_urls,
                     action="send_to_pyLoad"))  #"Enviar a pyLoad"

        if not item.channel in ["trailertools", "ecarteleratrailers"]:
            itemlist.append(
                Item(title=OpcionesDisponibles[12],
                     url=video_urls,
                     action="search_trailer"))  # "Buscar Trailer"

    else:
        if item.server != "":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok("No puedes ver ese vídeo porque...",
                                           motivo.split("<br/>")[0],
                                           motivo.split("<br/>")[1], item.url)
            else:
                resultado = advertencia.ok("No puedes ver ese vídeo porque...",
                                           motivo, item.url)
        else:
            resultado = advertencia.ok(
                "No puedes ver ese vídeo porque...",
                "El servidor donde está alojado no está",
                "soportado en pelisalacarta todavía", url)

            if item.channel == "favoritos":
                itemlist.append(
                    Item(title=OpcionesDisponibles[3],
                         url=video_urls,
                         action="remove_from_favorites")
                )  #"Quitar de favoritos"
            if item.channel == "library":
                itemlist.append(
                    Item(title="Quitar de la Biblioteca",
                         url=video_urls,
                         action="remove_from_library"))  #"Añadir a Biblioteca"

            if item.channel == "descargas" and item.category == "errores":
                itemlist.append(
                    Item(title=OpcionesDisponibles[7],
                         url=video_urls,
                         action="remove_from_error_downloads")
                )  #"Borrar descarga definitivamente"
            if item.channel == "descargas" and not item.category == "errores":
                itemlist.append(
                    Item(title=OpcionesDisponibles[9],
                         url=video_urls,
                         action="remove_from_downloads")
                )  #"Quitar de lista de descargas"

    return itemlist