def download_and_install_package(item):
    logger.info()

    from core import updater
    from platformcode import platformtools

    if item.package=="plugin":
        if int(item.version)<updater.get_current_plugin_version():
            if not platformtools.dialog_yesno("Installazione versione precedente","Sei sicuro di voler installare una versione precedente?"):
                return
        elif int(item.version)==updater.get_current_plugin_version():
            if not platformtools.dialog_yesno("Reinstallare versione attuale","Sei sicuro di voler reinstallare la stessa versione già presente?"):
                return
        elif int(item.version)>updater.get_current_plugin_version():
            if not platformtools.dialog_yesno("Installazione nuova versione","Sei sicuro di voler installare questa nuova versione?"):
                return
    else:
        if not platformtools.dialog_yesno("Pacchetto di installazione","Sei sicuro di voler installare questo pacchetto?"):
            return

    local_file_name = os.path.join( config.get_data_path() , item.filename)
    updater.download_and_install(item.url,local_file_name)

    if item.package=="channels":
        updater.set_current_channels_version(item.version)
    elif item.package=="servers":
        updater.set_current_servers_version(item.version)
    elif item.package=="plugin":
        updater.set_current_plugin_version(item.version)

    if config.is_xbmc() and config.get_system_platform() != "xbox":
        import xbmc
        xbmc.executebuiltin("Container.Refresh")
Esempio n. 2
0
def download_and_install_package(item):
    logger.info()

    from core import updater
    from core import versiontools

    if item.package=="plugin":
        if int(item.version)<versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Instalando versión anterior","¿Seguro que quieres instalar una versión anterior?"):
                return
        elif int(item.version)==versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Reinstalando versión actual","¿Seguro que quieres reinstalar la misma versión que ya tienes?"):
                return
        elif int(item.version)>versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Instalando nueva versión","¿Seguro que quieres instalar esta nueva versión?"):
                return
    else:
        if not platformtools.dialog_yesno("Instalando paquete","¿Seguro que quieres instalar este paquete?"):
            return

    local_file_name = os.path.join( config.get_data_path() , item.filename)
    updater.download_and_install(item.url,local_file_name)

    if config.is_xbmc() and config.get_system_platform() != "xbox":
        import xbmc
        xbmc.executebuiltin("Container.Refresh")
Esempio n. 3
0
def GetDownloadPath(version, platform=""):
    zipfile = "bin/pelsialacarta-%s-%s.zip"
    if not platform:
        if config.PLATFORM_NAME == "kodi-isengard":
            platform = "kodi-isengard"
        elif config.PLATFORM_NAME == "kodi-helix":
            platform = "kodi-helix"
        elif config.PLATFORM_NAME == "xbmceden":
            platform = "xbmc-eden"
        elif config.PLATFORM_NAME == "xbmcfrodo":
            platform = "xbmc-frodo"
        elif config.PLATFORM_NAME == "xbmcgotham":
            platform = "xbmc-gotham"
        elif config.PLATFORM_NAME == "xbmc":
            platform = "xbmc-plugin"
        elif config.PLATFORM_NAME == "wiimc":
            platform = "wiimc"
        elif config.PLATFORM_NAME == "rss":
            platform = "rss"
        elif config.PLATFORM_NAME == "mediaserver":
            if config.get_system_platform() == "blusens":
                platform = "blusens"
            else:
                platform = "mediaserver"

    return zipfile % (platform, version)
Esempio n. 4
0
def download_and_install_package(item):
    logger.info()

    from core import updater
    from core import versiontools

    if item.package == "plugin":
        if int(item.version) < versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Instalando versión anterior",
                                              "¿Seguro que quieres instalar una versión anterior?"):
                return
        elif int(item.version) == versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Reinstalando versión actual",
                                              "¿Seguro que quieres reinstalar la misma versión que ya tienes?"):
                return
        elif int(item.version) > versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Instalando nueva versión",
                                              "¿Seguro que quieres instalar esta nueva versión?"):
                return
    else:
        if not platformtools.dialog_yesno("Instalando paquete", "¿Seguro que quieres instalar este paquete?"):
            return

    local_file_name = os.path.join(config.get_data_path(), item.filename)
    updater.download_and_install(item.url, local_file_name)

    if config.is_xbmc() and config.get_system_platform() != "xbox":
        import xbmc
        xbmc.executebuiltin("Container.Refresh")
Esempio n. 5
0
def download_and_install_package(item):
    logger.info()

    from core import updater
    from platformcode import platformtools

    if item.package == "plugin":
        if int(item.version) < updater.get_current_plugin_version():
            if not platformtools.dialog_yesno(
                    "Installazione versione precedente",
                    "Sei sicuro di voler installare una versione precedente?"):
                return
        elif int(item.version) == updater.get_current_plugin_version():
            if not platformtools.dialog_yesno(
                    "Reinstallare versione attuale",
                    "Sei sicuro di voler reinstallare la stessa versione già presente?"
            ):
                return
        elif int(item.version) > updater.get_current_plugin_version():
            if not platformtools.dialog_yesno(
                    "Installazione nuova versione",
                    "Sei sicuro di voler installare questa nuova versione?"):
                return
    else:
        if not platformtools.dialog_yesno(
                "Pacchetto di installazione",
                "Sei sicuro di voler installare questo pacchetto?"):
            return

    local_file_name = os.path.join(config.get_data_path(), item.filename)
    updater.download_and_install(item.url, local_file_name)

    if item.package == "channels":
        updater.set_current_channels_version(item.version)
    elif item.package == "servers":
        updater.set_current_servers_version(item.version)
    elif item.package == "plugin":
        updater.set_current_plugin_version(item.version)

    if config.is_xbmc() and config.get_system_platform() != "xbox":
        import xbmc
        xbmc.executebuiltin("Container.Refresh")
Esempio n. 6
0
def run():
    logger.info("streamondemand.platformcode.launcher run")

    # The start() function is not always executed on old platforms (XBMC versions under 12.0)
    if config.OLD_PLATFORM:
        config.verify_directories_created()

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

    # If no item, this is mainlist
    else:
        item = Item(action="selectchannel", viewmode="movie")

    logger.info("streamondemand.platformcode.launcher " + item.tostring())

    # Set server filters
    server_white_list = []
    server_black_list = []
    if config.get_setting('filter_servers') == 'true':
        server_white_list, server_black_list = set_server_list()

    try:

        # If item has no action, stops here
        if item.action == "":
            logger.info("streamondemand.platformcode.launcher Item sin accion")
            return

        # Action for main menu in channelselector
        if (item.action == "selectchannel"):
            import channelselector
            itemlist = channelselector.getmainlist()

            # Check for updates only on first screen
            if config.get_setting("updatecheck2") == "true":
                logger.info(
                    "streamondemand.platformcode.launcher Check for plugin updates enabled"
                )
                from core import updater

                try:
                    version = updater.checkforupdates()

                    if version:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok(
                            "Versione " + version + " disponible",
                            "E' possibile fare il download della nuova versione\nselezionare la relativa voce nel menu principale"
                        )

                        itemlist.insert(
                            0,
                            Item(
                                title="Download versione " + version,
                                version=version,
                                channel="updater",
                                action="update",
                                thumbnail=channelselector.get_thumbnail_path()
                                + "Crystal_Clear_action_info.png"))
                except:
                    import xbmcgui
                    advertencia = xbmcgui.Dialog()
                    advertencia.ok("Impossibile connettersi",
                                   "Non è stato possibile verificare",
                                   "aggiornamenti")
                    logger.info(
                        "cstreamondemand.platformcode.launcher Fallo al verificar la actualización"
                    )

            else:
                logger.info(
                    "streamondemand.platformcode.launcher Check for plugin updates disabled"
                )

            xbmctools.renderItems(itemlist, item)

        # Action for updating plugin
        elif (item.action == "update"):

            from core import updater
            updater.update(item)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # Action for channel types on channelselector: movies, series, etc.
        elif (item.action == "channeltypes"):
            import channelselector
            itemlist = channelselector.getchanneltypes()

            xbmctools.renderItems(itemlist, item)

        # Action for channel listing on channelselector
        elif (item.action == "listchannels"):
            import channelselector
            itemlist = channelselector.filterchannels(item.category)

            xbmctools.renderItems(itemlist, item)

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            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

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels',
                                        item.channel + ".py")
            logger.info(
                "streamondemand.platformcode.launcher channel_file=%s" %
                channel_file)

            if item.channel in [
                    "personal", "personal2", "personal3", "personal4",
                    "personal5"
            ]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                try:
                    channel = __import__(
                        'channels.%s' % item.channel,
                        fromlist=["channels.%s" % item.channel])
                except:
                    exec "import channels." + item.channel + " as channel"

            logger.info(
                "streamondemand.platformcode.launcher running channel {0} {1}".
                format(channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                logger.info("streamondemand.platformcode.launcher play")

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info(
                        "streamondemand.platformcode.launcher executing channel 'play' method"
                    )
                    itemlist = channel.play(item)

                    # Play should return a list of playable URLS
                    if len(itemlist) > 0:
                        item = itemlist[0]
                        xbmctools.play_video(item)

                    # If not, shows user an error message
                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok("plugin",
                                              "No hay nada para reproducir")

                # If player don't have a "play" function, not uses the standard play from xbmctools
                else:
                    logger.info(
                        "streamondemand.platformcode.launcher executing core 'play' method"
                    )
                    xbmctools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                if item.strm:
                    # Special action for playing a video from the library
                    play_from_library(item, channel, server_white_list,
                                      server_black_list)

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

                # If not, uses the generic findvideos function
                else:
                    logger.info(
                        "streamondemand.platformcode.launcher no channel 'findvideos' method, "
                        "executing core method")
                    from core 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)

                # Show xbmc items as "movies", so plot is visible
                import xbmcplugin

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

                # Add everything to XBMC item list
                if type(itemlist) == list and itemlist:
                    xbmctools.renderItems(itemlist, item)

                # If not, it shows an empty list
                # FIXME: Aquí deberíamos mostrar alguna explicación del tipo "No hay elementos, esto pasa por bla bla bla"
                else:
                    xbmctools.renderItems([], item)

            # DrZ3r0
            # Special action for play_from_library, where the plugin looks for known urls
            elif item.action == "play_from_library":
                # Special action for playing a video from the library
                play_from_library(item, channel, server_white_list,
                                  server_black_list)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                library.add_pelicula_to_library(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                library.add_serie_to_library(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                downloadtools.download_all_episodes(item, channel)

            # Special action for searching, first asks for the words then call the "search" function
            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)

            # For all other actions
            else:
                logger.info(
                    "streamondemand.platformcode.launcher executing channel '"
                    + item.action + "' method")
                itemlist = getattr(channel, item.action)(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
                if type(itemlist) == list and itemlist:
                    xbmctools.renderItems(itemlist, item)

                # If not, it shows an empty list
                # FIXME: Aquí deberíamos mostrar alguna explicación del tipo "No hay elementos, esto pasa por bla bla bla"
                else:
                    xbmctools.renderItems([], item)

    except urllib2.URLError, e:
        import traceback
        logger.error("streamondemand.platformcode.launcher " +
                     traceback.format_exc())

        import xbmcgui
        ventana_error = xbmcgui.Dialog()

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info(
                "streamondemand.platformcode.launcher Razon del error, codigo: {0}, Razon: {1}"
                .format(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)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.info(
                "streamondemand.platformcode.launcher 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)
Esempio n. 7
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)
Esempio n. 8
0
from core import scrapertools
from core.item import Item
from servers import servertools
import xbmc, xbmcgui

PLUGIN_NAME = "pelisalacarta"

__channel__ = "seriesdanko"
__category__ = "S"
__type__ = "generic"
__title__ = "Seriesdanko"
__language__ = "ES"

DEBUG = config.get_setting("debug")

if config.get_system_platform() == "xbox":
    MaxResult = "55"
else:
    MaxResult = "500"


def isGeneric():
    return True


def mainlist(item):
    logger.info("pelisalacarta.channels.seriesdanko mainlist")
    item.url = 'http://seriesdanko.com/'

    itemlist = []
    itemlist.append(
Esempio n. 9
0
def run():
    logger.info("pelisalacarta.platformcode.launcher run")

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

    # If no item, this is mainlist
    else:
        item = Item(channel="channelselector", action="getmainlist", viewmode="movie")

    logger.info("pelisalacarta.platformcode.launcher "+item.tostring())
    
    try:

        # If item has no action, stops here
        if item.action == "":
            logger.info("pelisalacarta.platformcode.launcher Item sin accion")
            return

        # Action for main menu in channelselector
        if item.action == "getmainlist":
            import channelselector
            itemlist = channelselector.getmainlist()

            # Check for updates only on first screen
            if config.get_setting("updatecheck2") == "true":
                logger.info("pelisalacarta.platformcode.launcher Check for plugin updates enabled")
                from core import updater
                
                try:
                    version = updater.checkforupdates()

                    if version:
                        platformtools.dialog_ok("Versión "+version+" disponible",
                                                "Ya puedes descargar la nueva versión del plugin\n"
                                                "desde el listado principal")

                        itemlist.insert(0, Item(title="Descargar version "+version, version=version, channel="updater",
                                                action="update", thumbnail=channelselector.get_thumbnail_path() +
                                                "Crystal_Clear_action_info.png"))
                except:
                    platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar",
                                            "si hay actualizaciones")
                    logger.info("cpelisalacarta.platformcode.launcher Fallo al verificar la actualización")

            else:
                logger.info("pelisalacarta.platformcode.launcher Check for plugin updates disabled")

            platformtools.render_items(itemlist, item)

        # Action for updating plugin
        elif item.action == "update":

            from core import updater
            updater.update(item)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            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") != "":

                    tecleado = platformtools.dialog_input("", "PIN para canales de adultos", True)
                    if tecleado is not None:
                        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

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py")
            logger.info("pelisalacarta.platformcode.launcher channel_file=%s" % channel_file)

            channel = None

            if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                try:
                    channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel])
                except ImportError:
                    exec "import channels."+item.channel+" as channel"

            logger.info("pelisalacarta.platformcode.launcher running channel "+channel.__name__+" "+channel.__file__)

            # Special play action
            if item.action == "play":
                logger.info("pelisalacarta.platformcode.launcher play")
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0:
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok("plugin", "No hay nada para reproducir")

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.info("pelisalacarta.platformcode.launcher executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

                # If not, uses the generic findvideos function
                else:
                    logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, "
                                "executing core method")
                    from core import servertools
                    itemlist = servertools.find_video_items(item)

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

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                library.add_pelicula_to_library(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                library.add_serie_to_library(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from channels import descargas
                item.action = item.extra
                del item.extra
                descargas.save_download(item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                logger.info("pelisalacarta.platformcode.launcher search")
                
                tecleado = platformtools.dialog_input("")
                if tecleado is not None:
                    tecleado = tecleado.replace(" ", "+")
                    # TODO revisar 'personal.py' porque no tiene función search y daría problemas
                    itemlist = channel.search(item, tecleado)
                else:
                    itemlist = []
                
                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("pelisalacarta.platformcode.launcher executing channel '"+item.action+"' method")
                itemlist = getattr(channel, item.action)(item)
                platformtools.render_items(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        logger.error("pelisalacarta.platformcode.launcher "+traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info("pelisalacarta.platformcode.launcher Razon del error, codigo: "+str(e.reason[0])+", Razon: " +
                        str(e.reason[1]))
            texto = config.get_localized_string(30050)  # "No se puede conectar con el sitio web"
            platformtools.dialog_ok("plugin", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.info("pelisalacarta.platformcode.launcher codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
Esempio n. 10
0
def run():
    logger.info("[launcher.py] run")

    # Test if all the required directories are created
    config.verify_directories_created()

    # Extract parameters from sys.argv
    params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password = extract_parameters(
    )
    logger.info(
        "[launcher.py] 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"
        % (fanart, channel_name, title, fulltitle, url, thumbnail, plot,
           action, server, extra, subtitle, category, show, password))

    try:
        # Accion por defecto - elegir canal
        if (action == "selectchannel"):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)

            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()

        # Actualizar version
        elif (action == "update"):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info(
                    "[launcher.py] 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")

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            if action == "mainlist" and config.get_setting(
                    "updatechannels") == "true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(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(),
                                                PLUGIN_NAME, 'channels',
                                                channel_name + ".py")
            core_channel_path = os.path.join(config.get_runtime_path(), 'core',
                                             channel_name + ".py")
            logger.info("[launcher.py] regular_channel_path=%s" %
                        regular_channel_path)
            logger.info("[launcher.py] core_channel_path=%s" %
                        core_channel_path)

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

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

                if action == "play":
                    logger.info("[launcher.py] play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info(
                            "[launcher.py] 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)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok(
                                "plugin", "No hay nada para reproducir")
                    else:
                        logger.info(
                            "[launcher.py] 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)

                elif action == "strm_detail" or action == "play_from_library":
                    logger.info("[launcher.py] 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
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    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.xbmc 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("[launcher.py] add_pelicula_to_library")
                    from platformcode.xbmc 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("[launcher.py] add_serie_to_library, show=" +
                                item.show)
                    from platformcode.xbmc 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('mywebtv', '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)
                        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 último (el que dice "Añadir esta serie...")
                            if i < len(itemlist):
                                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(
                                "[launcher.py]Error 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_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)
                    f.write(item.show + "," + item.url + "," + item.channel +
                            "\n")
                    f.close()

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

                elif action == "search":
                    logger.info("[launcher.py] 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("[launcher.py] 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)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info(
                                "[launcher.py] no channel 'findvideos' method, executing core method"
                            )
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)

                        from core 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)
Esempio n. 11
0
def run(item=None):
    logger.info()


    print "UUUUUUUUUUUUUUUUUUUUU"
    print sys.argv

    params = dict(urlparse.parse_qsl(sys.argv[2].replace('?', '')))
    action = params.get('action')

    if not item:
        # Extract item from sys.argv
        if sys.argv[2] and action != "sod":
            item = Item().fromurl(sys.argv[2])

        # If no item, this is mainlist
        else:
            item = Item(channel="channelselector", action="getmainlist", viewmode="movie")
    logger.info(item.tostring())

    try:

        # If item has no action, stops here
        if item.action == "":
            logger.info("Item sin accion")
            return

        # Action for main menu in channelselector
        if item.action == "getmainlist":
            import channelselector

            # Check for updates only on first screen
            # if config.get_setting("check_for_plugin_updates") == True:
            #     logger.info("Check for plugin updates enabled")
            #     from core import updater
            #
            #     try:
            #         config.set_setting("plugin_updates_available", 0)
            #         version = updater.checkforupdates()
            #         itemlist = channelselector.getmainlist()
            #
            #         if version:
            #             config.set_setting("plugin_updates_available",1)
            #
            #             platformtools.dialog_ok("Versione "+version+" disponible",
            #                                     "E' possibile fare il download della nuova versione\n"
            #                                     "selezionare la relativa voce nel menu principale")
            #
            #             itemlist = channelselector.getmainlist()
            #             itemlist.insert(0, Item(title="Download versione "+version, version=version, channel="updater",
            #                                     action="update", thumbnail=os.path.join(config.get_runtime_path() , "resources" , "images", "service_update.png")))
            #     except:
            #         import traceback
            #         logger.info(traceback.format_exc())
            #         platformtools.dialog_ok("Impossibile connettersi", "Non è stato possibile verificare",
            #                                 "aggiornamenti")
            #         logger.info("Fallo al verificar la actualización")
            #         config.set_setting("plugin_updates_available","0")
            #         itemlist = channelselector.getmainlist()
            #
            # else:
            #     logger.info("Check for plugin updates disabled")
            #     config.set_setting("plugin_updates_available", 0)
            #     itemlist = channelselector.getmainlist()

            # Check for updates only on first screen
            if config.get_setting("check_for_plugin_updates"):
                try:
                    from core import update_channels
                except:
                    logger.info("Stefano.library_service Error in update_channels")
                    # ----------------------------------------------------------------------

                    # -- Update servertools and servers from repository Stefano ------
                try:
                    from core import update_servers
                except:
                    logger.info("Stefano.library_service Error in update_servers")

            itemlist = channelselector.getmainlist()
            platformtools.render_items(itemlist, item)

        # Action for updating plugin
        elif item.action == "update":

            from core import updater
            updater.update(item)
            config.set_setting("plugin_updates_available", 0)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            if item.action == "mainlist":

                # Parental control
                # 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") != "":
                    tecleado = platformtools.dialog_input("", "PIN per canali per adulti", True)
                    if tecleado is None or tecleado != config.get_setting("adult_pin"):
                        return

            # Actualiza el canal individual
            if (item.action == "mainlist" and
                    item.channel != "channelselector" and
                    config.get_setting("check_for_channel_updates") == True):
                from core import updater
                updater.update_channel(item.channel)

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(),
                                        'channels', item.channel + ".py")
            logger.info("channel_file=%s" % channel_file)

            channel = None

            if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                try:
                    channel = __import__('channels.%s' % item.channel, None,
                                         None, ["channels.%s" % item.channel])
                except ImportError:
                    exec "import channels." + item.channel + " as channel"

            logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                logger.info("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("Executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0 and isinstance(itemlist[0], Item):
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # Permitir varias calidades desde play en el canal
                    elif len(itemlist) > 0 and isinstance(itemlist[0], list):
                        item.video_urls = itemlist
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok("plugin", "Niente da riprodurre o riprova (de-link)")

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.info("Executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)
                    itemlist = servertools.filter_servers(itemlist)

                # If not, uses the generic findvideos function
                else:
                    logger.info("No channel 'findvideos' method, "
                                "executing core method")
                    itemlist = servertools.find_video_items(item)

                if config.get_setting("max_links", "biblioteca") != 0:
                    itemlist = limit_itemlist(itemlist)

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                library.add_pelicula_to_library(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                library.add_serie_to_library(item, channel)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                logger.info("item.action=%s" % item.action.upper())

                tecleado = platformtools.dialog_input('')
                if tecleado is not None:

                    # TODO revisar 'personal.py' porque no tiene función search y daría problemas
                    # DrZ3r0
                    itemlist = channel.search(item, tecleado.replace(" ", "+"))
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                platformtools.render_items(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        logger.error(traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.error("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1])))
            texto = config.get_localized_string(30050)  # "No se puede conectar con el sitio web"
            platformtools.dialog_ok("plugin", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.error("Codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
def run():
    logger.info()

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

    # If no item, this is mainlist
    else:
        item = Item(channel="channelselector", action="getmainlist", viewmode="movie")

    logger.info(item.tostring())
    
    try:

        # If item has no action, stops here
        if item.action == "":
            logger.info("Item sin accion")
            return

        # Action for main menu in channelselector
        if item.action == "getmainlist":
            import channelselector

            # Check for updates only on first screen
            if config.get_setting("check_for_plugin_updates") == "true":
                logger.info("Check for plugin updates enabled")
                from core import updater
                
                try:
                    config.set_setting("plugin_updates_available","0")
                    version = updater.checkforupdates()
                    itemlist = channelselector.getmainlist()

                    if version:
                        config.set_setting("plugin_updates_available","1")

                        platformtools.dialog_ok("Versione "+version+" disponible",
                                                "E' possibile fare il download della nuova versione\n"
                                                "selezionare la relativa voce nel menu principale")

                        itemlist = channelselector.getmainlist()
                        itemlist.insert(0, Item(title="Download versione "+version, version=version, channel="updater",
                                                action="update", thumbnail=os.path.join(config.get_runtime_path() , "resources" , "images", "service_update.png")))
                except:
                    import traceback
                    logger.info(traceback.format_exc())
                    platformtools.dialog_ok("Impossibile connettersi", "Non è stato possibile verificare",
                                            "aggiornamenti")
                    logger.info("Fallo al verificar la actualización")
                    config.set_setting("plugin_updates_available","0")
                    itemlist = channelselector.getmainlist()

            else:
                logger.info("Check for plugin updates disabled")
                config.set_setting("plugin_updates_available","0")
                itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

        # Action for updating plugin
        elif item.action == "update":

            from core import updater
            updater.update(item)
            config.set_setting("plugin_updates_available","0")
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            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") != "":

                    tecleado = platformtools.dialog_input("", "PIN per canali per adulti", True)
                    if tecleado is not None:
                        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

            # Actualiza el canal individual
            if (item.action == "mainlist" and
                    item.channel != "channelselector" and
                    config.get_setting("check_for_channel_updates") == "true"):
                from core import updater
                updater.update_channel(item.channel)

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(),
                                        'channels', item.channel + ".py")
            logger.info("channel_file=%s" % channel_file)

            channel = None

            if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                try:
                    channel = __import__('channels.%s' % item.channel, None,
                                         None, ["channels.%s" % item.channel])
                except ImportError:
                    exec "import channels." + item.channel + " as channel"

            logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                logger.info("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("Executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0 and isinstance(itemlist[0], Item):
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # Permitir varias calidades desde play en el canal
                    elif len(itemlist) > 0 and isinstance(itemlist[0], list):
                        item.video_urls = itemlist
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok("plugin", "Niente da riprodurre")

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.info("Executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

                # If not, uses the generic findvideos function
                else:
                    logger.info("No channel 'findvideos' method, "
                                "executing core method")
                    from core import servertools
                    itemlist = servertools.find_video_items(item)

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

                if config.get_setting("max_links", "biblioteca") != 0:
                    itemlist = limit_itemlist(itemlist)

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                library.add_pelicula_to_library(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                library.add_serie_to_library(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from channels import descargas
                item.action = item.extra
                del item.extra
                descargas.save_download(item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                logger.info("item.action=%s" % item.action.upper())

                tecleado = platformtools.dialog_input('')
                if tecleado is not None:

                    # TODO revisar 'personal.py' porque no tiene función search y daría problemas
                    # DrZ3r0
                    itemlist = channel.search(item, tecleado.replace(" ", "+"))
                else:
                    return
                
                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                platformtools.render_items(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        logger.error(traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %s | Razon: %s" %
                        (str(e.reason[0]), str(e.reason[1])))
            texto = config.get_localized_string(30050)  # "No se puede conectar con el sitio web"
            platformtools.dialog_ok("plugin", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.info("Codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
Esempio n. 13
0
def set_player(item, xlistitem, mediaurl, view, strm):
    logger.info()
    logger.debug("item:\n" + item.tostring('\n'))

    # Si es un fichero strm no hace falta el play
    if strm:
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    else:
        logger.info("player_mode=%s" % config.get_setting("player_mode"))
        logger.info("mediaurl=" + mediaurl)

        if config.get_setting("player_mode") == 0 or \
                (config.get_setting("player_mode") == 3 and mediaurl.startswith("rtmp")):
            # 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("playersettings=%s" % playersettings)

            if config.get_system_platform() == "xbox":
                player_type = xbmc.PLAYER_CORE_AUTO
                if playersettings == 0:
                    player_type = xbmc.PLAYER_CORE_AUTO
                    logger.debug("PLAYER_CORE_AUTO")
                elif playersettings == 1:
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.debug("PLAYER_CORE_MPLAYER")
                elif playersettings == 2:
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.debug("PLAYER_CORE_DVDPLAYER")

                xbmc_player = xbmc.Player(player_type)
            else:
                xbmc_player = xbmc.Player()

            xbmc_player.play(playlist, xlistitem)

        elif config.get_setting("player_mode") == 1:
            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:
            xbmc.executebuiltin("PlayMedia(" + mediaurl + ")")

    # TODO MIRAR DE QUITAR VIEW
    if item.subtitle != "" and view:
        logger.info("Subtítulos externos: " + item.subtitle)
        xbmc.sleep(2000)
        xbmc.Player().setSubtitles(item.subtitle)

    # si es un archivo de la biblioteca enviar a marcar como visto
    if strm or item.strm_path:
        from platformcode import xbmc_library
        xbmc_library.mark_auto_as_watched(item)
Esempio n. 14
0
def play_video(item,desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False):
    from core import servertools
    
    logger.info("streamondemand.platformcode.xbmctools play_video")
    #logger.info(item.tostring('\n'))

    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.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:
            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"

            if config.get_setting("jdownloader_enabled")=="true":
                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 item.channel in ["Trailer","ecarteleratrailers"]:
            opciones.append(config.get_localized_string(30162)) # "Buscar Trailer"

    # Si no puedes ver el vídeo te informa
    else:
        if item.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], item.url)
            else:
                resultado = advertencia.ok("Non è possibile guardare il video perché...", motivo, item.url)
        else:
            resultado = advertencia.ok("Non è possibile guardare il video perché...", "Il server che lo ospita non è",
                                       "ancora supportato da streamondemand", 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":
        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)
        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 = "streamondemand"

        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
        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

        # 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", "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 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

        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=title,url=item.url,thumbnail=download_thumbnail,server=item.server,plot=download_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":
        # La categoría es el nombre del fichero en la lista de descargas
        from channels import 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 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()

            from channels import descargas
            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

        titulo = item.fulltitle
        if titulo == "":
            titulo = item.title
        #library.savelibrary(titulo,item.url,item.thumbnail,item.server,item.plot,canal=item.channel,category=item.category,Serie=item.show)
        # TODO ¿SOLO peliculas?
        #logger.debug(item.tostring('\n'))
        new_item = item.clone(title=titulo, action="play_from_library", category="Cine",
                              fulltitle=item.fulltitle, channel=item.channel)
        #logger.debug(new_item.tostring('\n'))
        insertados, sobreescritos, fallidos = library.save_library_movie(new_item)

        advertencia = xbmcgui.Dialog()
        if fallidos == 0:
            advertencia.ok(config.get_localized_string(30131), titulo,
                           config.get_localized_string(30135))  # 'se ha añadido a la biblioteca'
        return

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

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("streamondemand.platformcode.xbmctools mediaurl="+mediaurl)
    if mediaurl=="":
        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:
        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)
    if strmfile:
        xlistitem = getLibraryInfo(mediaurl)
    else:
        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)
        except:
            xlistitem = xbmcgui.ListItem( play_title, iconImage="DefaultVideo.png", thumbnailImage=play_thumbnail)

        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 not item.from_biblioteca: #Si es un fichero strm no hace falta el play
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    #Movido del conector "torrent" aqui
    elif item.server=="torrent":

        #Opciones disponibles para Reproducir torrents
        torrent_options = []
        torrent_options.append(["Cliente interno (necesario libtorrent)"])
        torrent_options.append(["Cliente interno MCT (necesario libtorrent)"])

        #Plugins externos se pueden añadir otros
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.xbmctorrent")'):
            torrent_options.append(["Plugin externo: xbmctorrent","plugin://plugin.video.xbmctorrent/play/%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.pulsar")'):
            torrent_options.append(["Plugin externo: pulsar","plugin://plugin.video.pulsar/play?uri=%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.quasar")'):
            torrent_options.append(["Plugin externo: quasar","plugin://plugin.video.quasar/play?uri=%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.stream")'):
            torrent_options.append(["Plugin externo: stream","plugin://plugin.video.stream/play/%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.torrenter")'):
            torrent_options.append(["Plugin externo: torrenter","plugin://plugin.video.torrenter/?action=playSTRM&url=%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.torrentin")'):
            torrent_options.append(["Plugin externo: torrentin","plugin://plugin.video.torrentin/?uri=%s&image="])


        if len(torrent_options)>1:
            seleccion = xbmcgui.Dialog().select("Abrir torrent con...", [opcion[0] for opcion in torrent_options])
        else:
            seleccion = 0

        #Plugins externos
        if seleccion > 1:
            mediaurl = urllib.quote_plus(item.url)
            xbmc.executebuiltin( "PlayMedia(" + torrent_options[seleccion][1] % mediaurl +")" )

        if seleccion ==1:
            from platformcode import mct
            mct.play( mediaurl, xbmcgui.ListItem("", iconImage=item.thumbnail, thumbnailImage=item.thumbnail), subtitle=item.subtitle )

        #Reproductor propio (libtorrent)
        if seleccion == 0:
            import time
            videourl = None
            played = False
  
            #Importamos el cliente
            from btserver import Client
  
            #Iniciamos el cliente:
            c = Client(url=mediaurl, is_playing_fnc= xbmc.Player().isPlaying, wait_time=None, timeout=5, temp_path =os.path.join(config.get_data_path(),"torrent") )
  
            #Mostramos el progreso
            progreso = xbmcgui.DialogProgress()
            progreso.create( "streamondemand - Torrent" , "Iniciando...")
  
  
            #Mientras el progreso no sea cancelado ni el cliente cerrado
            while not progreso.iscanceled() and not c.closed:
  
                try:
                    #Obtenemos el estado del torrent
                    s = c.status
      
                    #Montamos las tres lineas con la info del torrent
                    txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
                    (s.progress_file, s.file_size, s.str_state, s._download_rate)
                    txt2 =  'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d' % \
                    (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes, s.trackers)
                    txt3 = 'Origen Peers TRK: %d DHT: %d PEX: %d LSD %d ' % \
                    (s.trk_peers,s.dht_peers, s.pex_peers, s.lsd_peers)
      
                    progreso.update(s.buffer,txt, txt2, txt3)
      
      
                    time.sleep(1)
      
                    #Si el buffer se ha llenado y la reproduccion no ha sido iniciada, se inicia
                    if s.buffer == 100 and not played:
      
                        #Cerramos el progreso
                        progreso.close()
        
                        #Obtenemos el playlist del torrent
                        videourl = c.get_play_list()
        
                        #Iniciamos el reproductor
                        playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
                        playlist.clear()
                        playlist.add( videourl, xlistitem )
                        xbmcPlayer = xbmc.Player()
                        xbmcPlayer.play(playlist)
        
                        #Marcamos como reproducido para que no se vuelva a iniciar
                        played = True
        
                        #Y esperamos a que el reproductor se cierre
                        while xbmc.Player().isPlaying():
                          time.sleep(1)
        
                        #Cuando este cerrado,  Volvemos a mostrar el dialogo
                        progreso.create( "streamondemand - Torrent" , "Iniciando...")
      
                except:
                    import traceback
                    logger.info(traceback.format_exc())
                    break

            progreso.update(100,"Terminato, elimina dati"," "," ")

            #Detenemos el cliente
            if not c.closed:
                c.stop()

            #Y cerramos el progreso
            progreso.close()

            return

    else:
        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:
            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")):
            # 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("streamondemand.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("streamondemand.platformcode.xbmctools PLAYER_CORE_AUTO")
                elif playersettings == "1":
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.info("streamondemand.platformcode.xbmctools PLAYER_CORE_MPLAYER")
                elif playersettings == "2":
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.info("streamondemand.platformcode.xbmctools 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("streamondemand.platformcode.xbmctools Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode")=="1":
            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":
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )

    if item.subtitle!="" and view:
        logger.info("Subtítulos externos: "+item.subtitle)
        xbmc.Player().setSubtitles(item.subtitle)
Esempio n. 15
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)
Esempio n. 16
0
def run(item=None):
    logger.info("tvalacarta.platformcode.launcher run")

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

        # If no item, this is mainlist
        else:
            item = Item(action="selectchannel")
            params = ""

    logger.info(item.tostring())

    # If item has no action, stops here
    if item.action == "":
        logger.info("Item sin accion")
        return

    try:
        # Action for main menu in channelselector
        if item.action == "selectchannel":

            import channelselector
            # TODO: Que channelselector devuelva items, procesados por el mismo add_items_to_kodi_directory que el resto
            itemlist = channelselector.mainlist(params, item.url,
                                                item.category)

            # Check for updates only on first screen
            if config.get_setting("updatecheck2") == "true":
                logger.info(
                    "tvalacarta.platformcode.launcher Check for plugin updates enabled"
                )
                from core import updater

                try:
                    version = updater.checkforupdates()

                    if version:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok(
                            "Versión " + version + " disponible",
                            "Ya puedes descargar la nueva versión del plugin\ndesde el listado principal"
                        )

                        itemlist.insert(
                            0,
                            Item(
                                title="Descargar version " + version,
                                version=version,
                                channel="updater",
                                action="update",
                                thumbnail=channelselector.get_thumbnail_path()
                                + "Crystal_Clear_action_info.png"))
                except:
                    import xbmcgui
                    advertencia = xbmcgui.Dialog()
                    advertencia.ok("No se puede conectar",
                                   "No ha sido posible comprobar",
                                   "si hay actualizaciones")
                    logger.info(
                        "channelselector.mainlist Fallo al verificar la actualización"
                    )

            else:
                logger.info(
                    "tvalacarta.platformcode.launcher Check for plugin updates disabled"
                )

            #xbmctools.add_items_to_kodi_directory(itemlist, item)

        # Action for updating plugin
        elif item.action == "update":

            from core import updater
            updater.update(item)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "channeltypes":
            import channelselector
            # TODO: Que channelselector devuelva items, procesados por el mismo add_items_to_kodi_directory que el resto
            itemlist = channelselector.channeltypes(params, item.url,
                                                    item.category)

            #xbmctools.add_items_to_kodi_directory(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "listchannels":
            import channelselector
            # TODO: Que channelselector devuelva items, procesados por el mismo add_items_to_kodi_directory que el resto
            itemlist = channelselector.listchannels(params, item.url,
                                                    item.category)

            #xbmctools.add_items_to_kodi_directory(itemlist, item)

        elif item.action == "player_directo":

            from core import window_player_background
            from channels import directos
            import plugintools

            window = window_player_background.PlayerWindowBackground(
                "player_background.xml", plugintools.get_runtime_path())
            window.setItemlist(directos.build_channel_list())
            window.setCurrentPosition(item.position)
            window.doModal()
            del window
            return

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels',
                                        item.channel + ".py")
            logger.info("tvalacarta.platformcode.launcher channel_file=%s" %
                        channel_file)

            channel = __import__('channels.%s' % item.channel,
                                 fromlist=["channels.%s" % item.channel])
            logger.info(
                "tvalacarta.platformcode.launcher running channel {0} {1}".
                format(channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                logger.info("tvalacarta.platformcode.launcher play")

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info(
                        "tvalacarta.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",
                                              "No hay nada para reproducir")
                else:
                    logger.info(
                        "tvalacarta.platformcode.launcher executing core 'play' method"
                    )
                    xbmctools.play_video(item)

            elif item.action.startswith("serie_options##"):
                from core import suscription
                import xbmcgui
                dia = xbmcgui.Dialog()
                opciones = []

                suscription_item = Item(channel=item.channel,
                                        title=item.show,
                                        url=item.url,
                                        action=item.action.split("##")[1],
                                        extra=item.extra,
                                        plot=item.plot,
                                        show=item.show,
                                        thumbnail=item.thumbnail)

                if not suscription.already_suscribed(suscription_item):
                    opciones.append("Activar descarga automática")
                else:
                    opciones.append("Cancelar descarga automática")

                #opciones.append("Añadir esta serie a favoritos")
                opciones.append("Descargar todos los episodios")
                seleccion = dia.select("Elige una opción",
                                       opciones)  # "Elige una opción"

                if seleccion == 0:
                    if not suscription.already_suscribed(suscription_item):
                        suscription.append_suscription(suscription_item)

                        yes_pressed = xbmcgui.Dialog().yesno(
                            "Descarga automática activada",
                            "A partir de ahora los nuevos vídeos que se publiquen de este programa se descargarán automáticamente, podrás encontrarlos en la sección 'Descargas'."
                        )

                        if yes_pressed:
                            download_all_episodes(suscription_item, channel)

                    else:
                        suscription.remove_suscription(suscription_item)
                        xbmcgui.Dialog().ok(
                            "Descarga automática cancelada",
                            "Los vídeos que hayas descargado se mantienen, pero los nuevos ya no se descargarán ellos solos."
                        )

                elif seleccion == 1:
                    downloadtools.download_all_episodes(item, channel)
                '''
                elif seleccion==1:
                    from core import favoritos
                    from core import downloadtools
                    import xbmc

                    keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(item.show)+" ["+item.channel+"]")
                    keyboard.doModal()
                    if keyboard.isConfirmed():
                        title = keyboard.getText()
                        favoritos.savebookmark(titulo=title,url=item.url,thumbnail=item.thumbnail,server="",plot=item.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 item.action == "search":
                logger.info("tvalacarta.platformcode.launcher search")

                import xbmc
                keyboard = xbmc.Keyboard("")
                keyboard.doModal()

                itemlist = []
                if (keyboard.isConfirmed()):
                    tecleado = keyboard.getText()
                    #tecleado = tecleado.replace(" ", "+")
                    itemlist = channel.search(item, tecleado)
                    if itemlist is None:
                        itemlist = []

                xbmctools.add_items_to_kodi_directory(itemlist, item)

            else:
                logger.info(
                    "tvalacarta.platformcode.launcher executing channel '" +
                    item.action + "' method")
                exec "itemlist = channel." + item.action + "(item)"
                if itemlist is None:
                    itemlist = []

                # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                handle = sys.argv[1]
                xbmcplugin.setContent(int(handle), "movies")

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

    except UserException, e:
        import xbmcgui
        xbmcgui.Dialog().ok("Se ha producido un error", e.value)
Esempio n. 17
0
from core import scrapertools
from core.item import Item
from servers import servertools
import xbmc, xbmcgui

PLUGIN_NAME = "pelisalacarta"

__channel__ = "seriesdanko"
__category__ = "S"
__type__ = "generic"
__title__ = "Seriesdanko"
__language__ = "ES"

DEBUG = config.get_setting("debug")

if config.get_system_platform() == "xbox":
    MaxResult = "55"
else:
    MaxResult = "500"

def isGeneric():
    return True

def mainlist(item):
    logger.info("pelisalacarta.channels.seriesdanko mainlist")
    item.url = 'http://seriesdanko.com/'

    itemlist = []
    itemlist.append( Item(channel=__channel__, title="Novedades", action="novedades"   , url=item.url))
    itemlist.append( Item(channel=__channel__, title="A-Z", action="letras", url=item.url))
    itemlist.append( Item(channel=__channel__, title="Listado completo", action="allserieslist", url=item.url))
Esempio n. 18
0
def run():
    logger.info()

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

    # If no item, this is mainlist
    else:
        item = Item(channel="channelselector",
                    action="getmainlist",
                    viewmode="movie")

    logger.info(item.tostring())

    try:

        # If item has no action, stops here
        if item.action == "":
            logger.info("Item sin accion")
            return

        # Action for main menu in channelselector
        if item.action == "getmainlist":
            import channelselector

            # Check for updates only on first screen
            if config.get_setting("check_for_plugin_updates") == "true":
                logger.info("Check for plugin updates enabled")
                from core import updater

                try:
                    config.set_setting("plugin_updates_available", "0")
                    new_published_version_tag, number_of_updates = updater.get_available_updates(
                    )

                    config.set_setting("plugin_updates_available",
                                       str(number_of_updates))
                    itemlist = channelselector.getmainlist()

                    if new_published_version_tag != "":

                        platformtools.dialog_notification(
                            new_published_version_tag + " disponible",
                            "Ya puedes descargar la nueva versión del plugin\n"
                            "desde el listado principal")

                        itemlist = channelselector.getmainlist()
                        itemlist.insert(
                            0,
                            Item(title="Descargar version " +
                                 new_published_version_tag,
                                 version=new_published_version_tag,
                                 channel="updater",
                                 action="update",
                                 thumbnail=channelselector.get_thumb(
                                     "squares", "thumb_actualizar.png")))
                except:
                    import traceback
                    logger.info(traceback.format_exc())
                    platformtools.dialog_ok("No se puede conectar",
                                            "No ha sido posible comprobar",
                                            "si hay actualizaciones")
                    logger.info("Fallo al verificar la actualización")
                    config.set_setting("plugin_updates_available", "0")
                    itemlist = channelselector.getmainlist()

            else:
                logger.info("Check for plugin updates disabled")
                config.set_setting("plugin_updates_available", "0")
                itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

        # Action for updating plugin
        elif item.action == "update":

            from core import updater
            updater.update(item)
            config.set_setting("plugin_updates_available", "0")
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            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") != "":

                    tecleado = platformtools.dialog_input(
                        "", "PIN para canales de adultos", True)
                    if tecleado is not None:
                        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

            # Actualiza el canal individual
            if (item.action == "mainlist" and item.channel != "channelselector"
                    and config.get_setting("check_for_channel_updates")
                    == "true"):
                from core import updater
                updater.update_channel(item.channel)

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels',
                                        item.channel + ".py")
            logger.info("channel_file=%s" % channel_file)

            channel = None

            if item.channel in [
                    "personal", "personal2", "personal3", "personal4",
                    "personal5"
            ]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                try:
                    channel = __import__('channels.%s' % item.channel, None,
                                         None, ["channels.%s" % item.channel])
                except ImportError:
                    exec "import channels." + item.channel + " as channel"

            logger.info("Running channel %s | %s" %
                        (channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                logger.info("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("Executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0 and isinstance(itemlist[0], Item):
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # Permitir varias calidades desde play en el canal
                    elif len(itemlist) > 0 and isinstance(itemlist[0], list):
                        item.video_urls = itemlist
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok("pelisalacarta",
                                                "No hay nada para reproducir")

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.info("Executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

                # If not, uses the generic findvideos function
                else:
                    logger.info("No channel 'findvideos' method, "
                                "executing core method")
                    from core import servertools
                    itemlist = servertools.find_video_items(item)

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

                if config.get_setting("max_links", "biblioteca") != 0:
                    itemlist = limit_itemlist(itemlist)

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                library.add_pelicula_to_library(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                library.add_serie_to_library(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from channels import descargas
                item.action = item.extra
                del item.extra
                descargas.save_download(item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                logger.info("item.action=%s" % item.action.upper())

                last_search = ""
                last_search_active = config.get_setting(
                    "last_search", "buscador")
                if last_search_active:
                    try:
                        current_saved_searches_list = list(
                            config.get_setting("saved_searches_list",
                                               "buscador"))
                        last_search = current_saved_searches_list[0]
                    except:
                        pass

                tecleado = platformtools.dialog_input(last_search)
                if tecleado is not None:
                    if last_search_active and not tecleado.startswith("http"):
                        from channels import buscador
                        buscador.save_search(tecleado)

                    # TODO revisar 'personal.py' porque no tiene función search y daría problemas
                    itemlist = channel.search(item, tecleado)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                platformtools.render_items(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        logger.error(traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %s | Razon: %s" %
                        (str(e.reason[0]), str(e.reason[1])))
            texto = config.get_localized_string(
                30050)  # "No se puede conectar con el sitio web"
            platformtools.dialog_ok("pelisalacarta", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.info("Codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok(
                "pelisalacarta",
                config.get_localized_string(30051) % e.code)
Esempio n. 19
0
def run():
    logger.info("[launcher.py] run")
    
    # Test if all the required directories are created
    config.verify_directories_created()
    
    # Extract parameters from sys.argv
    params, channel_name, title, channel_title, show_title, fulltitle, url, thumbnail, plot, uid, action, server, extra, subtitle, category, show, password = extract_parameters()
    logger.info("[launcher.py] 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" % (channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password))

    if action=="":
        return

    try:
        # Accion por defecto - elegir canal
        if ( action=="selectchannel" ):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)
            
            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("[launcher.py] 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=="listchannels"):
            import channelselector as plugin
            plugin.listchannels(params,url,category)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(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("[launcher.py] regular_channel_path=%s" % regular_channel_path)
            logger.info("[launcher.py] core_channel_path=%s" % core_channel_path)

            if channel_name=="buscador":
                import pelisalacarta.buscador 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("[launcher.py] 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("[launcher.py] 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("[launcher.py] multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name, title=title , channel_title=channel_title , show_title=show_title , fulltitle=fulltitle, url=url, thumbnail=thumbnail , plot=plot , uid=uid, server=server, category=category, extra=extra, subtitle=subtitle, show=show, password=password)
                
                '''
                if item.subtitle!="":
                    logger.info("[launcher.py] 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("[launcher.py] No subtitle")
                '''
                from platformcode import xbmctools

                if action=="play":
                    logger.info("[launcher.py] play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info("[launcher.py] 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)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                    else:
                        logger.info("[launcher.py] 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)

                elif action=="strm_detail" or action=="play_from_library":
                    logger.info("[launcher.py] 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
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    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("[launcher.py] 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("[launcher.py] add_serie_to_library")
                    from platformcode import library
                    import xbmcgui
                
                    # Obtiene el listado desde el que se llamó
                    action = item.extra
                    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)
                        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 último (el que dice "Añadir esta serie...")
                            if i<len(itemlist):
                                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 )
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error( "%s" % line )
                            logger.info("[launcher.py]Error 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_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)
                    f.write(item.show+","+item.url+","+item.channel+"\n")
                    f.close();

                elif action.startswith("serie_options##"):
                    from core import suscription
                    import xbmcgui
                    dia = xbmcgui.Dialog()
                    opciones = []

                    suscription_item = Item(channel=item.channel, title=item.show, url=item.url, action=action.split("##")[1], extra=item.extra, plot=item.plot, show=item.show, thumbnail=item.thumbnail)

                    if not suscription.already_suscribed(suscription_item):
                        opciones.append("Suscribirme a esta serie")
                    else:
                        opciones.append("Quitar suscripción a esta serie")

                    #opciones.append("Añadir esta serie a favoritos")
                    opciones.append("Descargar todos los episodios")
                    seleccion = dia.select("Elige una opción", opciones) # "Elige una opción"

                    if seleccion==0:
                        if not suscription.already_suscribed(suscription_item):
                            suscription.append_suscription(suscription_item)

                            yes_pressed = xbmcgui.Dialog().yesno( "tvalacarta" , "Suscripción a \""+suscription_item.title+"\" creada" , "¿Quieres descargar los vídeos existentes ahora?" )

                            if yes_pressed:
                                download_all_episodes(suscription_item,channel)

                        else:
                            suscription.remove_suscription(suscription_item)
                            xbmcgui.Dialog().ok( "tvalacarta" , "Suscripción a \""+suscription_item.title+"\" eliminada" , "Los vídeos que hayas descargado se mantienen" )

                    elif seleccion==1:
                        download_all_episodes(suscription_item,channel)

                    '''
                    elif seleccion==1:
                        from core import favoritos
                        from core import downloadtools
                        import xbmc

                        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(item.show)+" ["+item.channel+"]")
                        keyboard.doModal()
                        if keyboard.isConfirmed():
                            title = keyboard.getText()
                            favoritos.savebookmark(titulo=title,url=item.url,thumbnail=item.thumbnail,server="",plot=item.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 action=="search":
                    logger.info("[launcher.py] 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("[launcher.py] executing channel '"+action+"' method")
                    if action!="findvideos":
                        exec "itemlist = channel."+action+"(item)"
                    else:
                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        try:
                            exec "itemlist = channel."+action+"(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        except:
                            logger.info("[launcher.py] no channel 'findvideos' method, executing core method")
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                        from core 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
        import 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)    
Esempio n. 20
0
def set_player(item, xlistitem, mediaurl, view, strm):
    logger.info("platformtools set_player")
    logger.debug("item:\n" + item.tostring('\n'))

    # Movido del conector "torrent" aqui
    if item.server == "torrent":
        play_torrent(item, xlistitem, mediaurl)
        return

    # Si es un fichero strm no hace falta el play
    elif strm:
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    else:
        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:
            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")):
            # 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("pelisalacarta.platformcode.platformstools 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("pelisalacarta.platformcode.platformstools PLAYER_CORE_AUTO")
                elif playersettings == "1":
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.info("pelisalacarta.platformcode.platformstools PLAYER_CORE_MPLAYER")
                elif playersettings == "2":
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.info("pelisalacarta.platformcode.platformstools PLAYER_CORE_DVDPLAYER")

                xbmc_player = xbmc.Player(player_type)
            else:
                xbmc_player = xbmc.Player()

            xbmc_player.play(playlist, xlistitem)

        elif config.get_setting("player_mode") == "1":
            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":
            xbmc.executebuiltin("PlayMedia(" + mediaurl + ")")

    # TODO MIRAR DE QUITAR VIEW
    if item.subtitle != "" and view:
        logger.info("Subtítulos externos: " + item.subtitle)
        xbmc.sleep(2000)
        xbmc.Player().setSubtitles(item.subtitle)
Esempio n. 21
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)
Esempio n. 22
0
def play_video(item,desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False):
    from core import servertools
    
    logger.info("pelisalacarta.platformcode.xbmctools play_video")
    #logger.info(item.tostring('\n'))

    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.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:
            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"

            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:
        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":
        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)
        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
        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

        # 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 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"
        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":
        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

        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":
        # 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 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

        titulo = item.fulltitle
        if titulo == "":
            titulo = item.title
        #library.savelibrary(titulo,item.url,item.thumbnail,item.server,item.plot,canal=item.channel,category=item.category,Serie=item.show)
        # TODO ¿SOLO peliculas?
        #logger.debug(item.tostring('\n'))
        new_item = item.clone(title=titulo, action="play_from_library", category="Cine",
                              fulltitle=item.fulltitle, channel=item.channel)
        #logger.debug(new_item.tostring('\n'))
        insertados, sobreescritos, fallidos = library.save_library_movie(new_item)

        advertencia = xbmcgui.Dialog()
        if fallidos == 0:
            advertencia.ok(config.get_localized_string(30131), titulo,
                           config.get_localized_string(30135))  # 'se ha añadido a la biblioteca'
        return

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

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("pelisalacarta.platformcode.xbmctools mediaurl="+mediaurl)
    if mediaurl=="":
        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:
        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)
    if strmfile:
        xlistitem = getLibraryInfo(mediaurl)
    else:
        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)
        except:
            xlistitem = xbmcgui.ListItem( play_title, iconImage="DefaultVideo.png", thumbnailImage=play_thumbnail)

        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 not item.from_biblioteca: #Si es un fichero strm no hace falta el play
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    #Movido del conector "torrent" aqui
    elif item.server=="torrent":

        #Opciones disponibles para Reproducir torrents
        torrent_options = []
        torrent_options.append(["Cliente interno (necesario libtorrent)"])
        torrent_options.append(["Cliente interno MCT (necesario libtorrent)"])

        #Plugins externos se pueden añadir otros
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.xbmctorrent")'):
            torrent_options.append(["Plugin externo: xbmctorrent","plugin://plugin.video.xbmctorrent/play/%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.pulsar")'):
            torrent_options.append(["Plugin externo: pulsar","plugin://plugin.video.pulsar/play?uri=%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.quasar")'):
            torrent_options.append(["Plugin externo: quasar","plugin://plugin.video.quasar/play?uri=%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.stream")'):
            torrent_options.append(["Plugin externo: stream","plugin://plugin.video.stream/play/%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.torrenter")'):
            torrent_options.append(["Plugin externo: torrenter","plugin://plugin.video.torrenter/?action=playSTRM&url=%s"])
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.torrentin")'):
            torrent_options.append(["Plugin externo: torrentin","plugin://plugin.video.torrentin/?uri=%s&image="])


        if len(torrent_options)>1:
            seleccion = xbmcgui.Dialog().select("Abrir torrent con...", [opcion[0] for opcion in torrent_options])
        else:
            seleccion = 0

        #Plugins externos
        if seleccion > 1:
            mediaurl = urllib.quote_plus(item.url)
            xbmc.executebuiltin( "PlayMedia(" + torrent_options[seleccion][1] % mediaurl +")" )

        if seleccion ==1:
            from platformcode import mct
            mct.play( mediaurl, xbmcgui.ListItem("", iconImage=item.thumbnail, thumbnailImage=item.thumbnail), subtitle=item.subtitle )

        #Reproductor propio (libtorrent)
        if seleccion == 0:
            import time
            videourl = None
            played = False
  
            #Importamos el cliente
            from btserver import Client
  
            #Iniciamos el cliente:
            c = Client(url=mediaurl, is_playing_fnc= xbmc.Player().isPlaying, wait_time=None, timeout=5, temp_path =os.path.join(config.get_data_path(),"torrent") )
  
            #Mostramos el progreso
            progreso = xbmcgui.DialogProgress()
            progreso.create( "Pelisalacarta - Torrent" , "Iniciando...")
  
  
            #Mientras el progreso no sea cancelado ni el cliente cerrado
            while not progreso.iscanceled() and not c.closed:
  
                try:
                    #Obtenemos el estado del torrent
                    s = c.status
      
                    #Montamos las tres lineas con la info del torrent
                    txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
                    (s.progress_file, s.file_size, s.str_state, s._download_rate)
                    txt2 =  'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d' % \
                    (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes, s.trackers)
                    txt3 = 'Origen Peers TRK: %d DHT: %d PEX: %d LSD %d ' % \
                    (s.trk_peers,s.dht_peers, s.pex_peers, s.lsd_peers)
      
                    progreso.update(s.buffer,txt, txt2, txt3)
      
      
                    time.sleep(1)
      
                    #Si el buffer se ha llenado y la reproduccion no ha sido iniciada, se inicia
                    if s.buffer == 100 and not played:
      
                        #Cerramos el progreso
                        progreso.close()
        
                        #Obtenemos el playlist del torrent
                        videourl = c.get_play_list()
        
                        #Iniciamos el reproductor
                        playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
                        playlist.clear()
                        playlist.add( videourl, xlistitem )
                        xbmcPlayer = xbmc.Player()
                        xbmcPlayer.play(playlist)
        
                        #Marcamos como reproducido para que no se vuelva a iniciar
                        played = True
        
                        #Y esperamos a que el reproductor se cierre
                        while xbmc.Player().isPlaying():
                          time.sleep(1)
        
                        #Cuando este cerrado,  Volvemos a mostrar el dialogo
                        progreso.create( "Pelisalacarta - Torrent" , "Iniciando...")
      
                except:
                    import traceback
                    logger.info(traceback.format_exc())
                    break

            progreso.update(100,"Terminando y eliminando datos"," "," ")

            #Detenemos el cliente
            if not c.closed:
                c.stop()

            #Y cerramos el progreso
            progreso.close()

            return

    else:
        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:
            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")):
            # 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("pelisalacarta.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("pelisalacarta.platformcode.xbmctools PLAYER_CORE_AUTO")
                elif playersettings == "1":
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.info("pelisalacarta.platformcode.xbmctools PLAYER_CORE_MPLAYER")
                elif playersettings == "2":
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.info("pelisalacarta.platformcode.xbmctools 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("pelisalacarta.platformcode.xbmctools Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode")=="1":
            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":
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )

    if item.subtitle!="" and view:
        logger.info("Subtítulos externos: "+item.subtitle)
        xbmc.Player().setSubtitles(item.subtitle)
Esempio n. 23
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
                    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)    
Esempio n. 24
0
def set_player(item, xlistitem, mediaurl, view, strm):
    logger.info("platformtools set_player")
    logger.debug("item:\n" + item.tostring('\n'))

    # Movido del conector "torrent" aqui
    if item.server == "torrent":
        play_torrent(item, xlistitem, mediaurl)
        return

    # Si es un fichero strm no hace falta el play
    elif strm:
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    else:
        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:
            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")):
            # 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("pelisalacarta.platformcode.platformstools 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("pelisalacarta.platformcode.platformstools PLAYER_CORE_AUTO")
                elif playersettings == "1":
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.info("pelisalacarta.platformcode.platformstools PLAYER_CORE_MPLAYER")
                elif playersettings == "2":
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.info("pelisalacarta.platformcode.platformstools PLAYER_CORE_DVDPLAYER")

                xbmc_player = xbmc.Player(player_type)
            else:
                xbmc_player = xbmc.Player()

            xbmc_player.play(playlist, xlistitem)

        elif config.get_setting("player_mode") == "1":
            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":
            xbmc.executebuiltin("PlayMedia(" + mediaurl + ")")

    # TODO MIRAR DE QUITAR VIEW
    if item.subtitle != "" and view:
        logger.info("Subtítulos externos: " + item.subtitle)
        xbmc.sleep(2000)
        xbmc.Player().setSubtitles(item.subtitle)
Esempio n. 25
0
def run(item=None):
    logger.info("tvalacarta.platformcode.launcher run")
    
    if item is None:
        # Extract item from sys.argv
        if sys.argv[2]:
            item = Item().fromurl(sys.argv[2])
            params = ""

        # If no item, this is mainlist
        else:
            item = Item(action="selectchannel")
            params = ""

    logger.info(item.tostring())

    # If item has no action, stops here
    if item.action == "":
        logger.info("Item sin accion")
        return

    try:
        # Action for main menu in channelselector
        if item.action=="selectchannel":
            
            import channelselector
            # TODO: Que channelselector devuelva items, procesados por el mismo add_items_to_kodi_directory que el resto
            itemlist = channelselector.mainlist(params, item.url, item.category)

            # Check for updates only on first screen
            if config.get_setting("updatecheck2") == "true":
                logger.info("tvalacarta.platformcode.launcher Check for plugin updates enabled")
                from core import updater
                
                try:
                    version = updater.checkforupdates()

                    if version:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("Versión "+version+" disponible","Ya puedes descargar la nueva versión del plugin\ndesde el listado principal")

                        itemlist.insert(0,Item(title="Descargar version "+version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png"))
                except:
                    import xbmcgui
                    advertencia = xbmcgui.Dialog()
                    advertencia.ok("No se puede conectar","No ha sido posible comprobar","si hay actualizaciones")
                    logger.info("channelselector.mainlist Fallo al verificar la actualización")

            else:
                logger.info("tvalacarta.platformcode.launcher Check for plugin updates disabled")

            #xbmctools.add_items_to_kodi_directory(itemlist, item)

        # Action for updating plugin
        elif item.action=="update":

            from core import updater
            updater.update(item)
            if config.get_system_platform()!="xbox":
                import xbmc
                xbmc.executebuiltin( "Container.Refresh" )

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action=="channeltypes":
            import channelselector
            # TODO: Que channelselector devuelva items, procesados por el mismo add_items_to_kodi_directory que el resto
            itemlist = channelselector.channeltypes(params,item.url,item.category)

            #xbmctools.add_items_to_kodi_directory(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action=="listchannels":
            import channelselector
            # TODO: Que channelselector devuelva items, procesados por el mismo add_items_to_kodi_directory que el resto
            itemlist = channelselector.listchannels(params,item.url,item.category)

            #xbmctools.add_items_to_kodi_directory(itemlist, item)

        elif item.action=="player_directo":

            from core import window_player_background
            from channels import directos
            import plugintools

            window = window_player_background.PlayerWindowBackground("player_background.xml",plugintools.get_runtime_path())
            window.setItemlist(directos.build_channel_list())
            window.setCurrentPosition(item.position)
            window.doModal()
            del window
            return

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Checks if channel exists
            channel_file = os.path.join( config.get_runtime_path() , 'channels' , item.channel+".py" )
            logger.info("tvalacarta.platformcode.launcher channel_file=%s" % channel_file)

            channel = __import__('channels.%s' % item.channel, fromlist=["channels.%s" % item.channel])
            logger.info("tvalacarta.platformcode.launcher running channel {0} {1}".format(channel.__name__, channel.__file__))


            # Special play action
            if item.action == "play":
                logger.info("tvalacarta.platformcode.launcher play")

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("tvalacarta.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", "No hay nada para reproducir")
                else:
                    logger.info("tvalacarta.platformcode.launcher executing core 'play' method")
                    xbmctools.play_video(item)

            elif item.action.startswith("serie_options##"):
                from core import suscription
                import xbmcgui
                dia = xbmcgui.Dialog()
                opciones = []

                suscription_item = Item(channel=item.channel, title=item.show, url=item.url, action=item.action.split("##")[1], extra=item.extra, plot=item.plot, show=item.show, thumbnail=item.thumbnail)

                if not suscription.already_suscribed(suscription_item):
                    opciones.append("Activar descarga automática")
                else:
                    opciones.append("Cancelar descarga automática")

                #opciones.append("Añadir esta serie a favoritos")
                opciones.append("Descargar todos los episodios")
                seleccion = dia.select("Elige una opción", opciones) # "Elige una opción"

                if seleccion==0:
                    if not suscription.already_suscribed(suscription_item):
                        suscription.append_suscription(suscription_item)

                        yes_pressed = xbmcgui.Dialog().yesno( "Descarga automática activada" , "A partir de ahora los nuevos vídeos que se publiquen de este programa se descargarán automáticamente, podrás encontrarlos en la sección 'Descargas'." )

                        if yes_pressed:
                            download_all_episodes(suscription_item,channel)

                    else:
                        suscription.remove_suscription(suscription_item)
                        xbmcgui.Dialog().ok( "Descarga automática cancelada" , "Los vídeos que hayas descargado se mantienen, pero los nuevos ya no se descargarán ellos solos." )

                elif seleccion==1:
                    downloadtools.download_all_episodes(item, channel)

                '''
                elif seleccion==1:
                    from core import favoritos
                    from core import downloadtools
                    import xbmc

                    keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(item.show)+" ["+item.channel+"]")
                    keyboard.doModal()
                    if keyboard.isConfirmed():
                        title = keyboard.getText()
                        favoritos.savebookmark(titulo=title,url=item.url,thumbnail=item.thumbnail,server="",plot=item.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 item.action=="search":
                logger.info("tvalacarta.platformcode.launcher search")

                import xbmc
                keyboard = xbmc.Keyboard("")
                keyboard.doModal()

                itemlist = []
                if (keyboard.isConfirmed()):
                    tecleado = keyboard.getText()
                    #tecleado = tecleado.replace(" ", "+")
                    itemlist = channel.search(item,tecleado)
                    if itemlist is None:
                        itemlist = []

                xbmctools.add_items_to_kodi_directory(itemlist, item)

            else:
                logger.info("tvalacarta.platformcode.launcher executing channel '"+item.action+"' method")
                exec "itemlist = channel."+item.action+"(item)"
                if itemlist is None:
                    itemlist = []

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

    except UserException,e:
        import xbmcgui
        xbmcgui.Dialog().ok ("Se ha producido un error", e.value)
Esempio n. 26
0
def run():
    logger.info("pelisalacarta.platformcode.launcher run")

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

    # If no item, this is mainlist
    else:
        item = Item(action="selectchannel", viewmode="movie")

    logger.info("pelisalacarta.platformcode.launcher "+item.tostring())

    # Set server filters
    server_white_list = []
    server_black_list = []
    if config.get_setting('filter_servers') == 'true':
        server_white_list, server_black_list = set_server_list()

    try:

        # If item has no action, stops here
        if item.action == "":
            logger.info("pelisalacarta.platformcode.launcher Item sin accion")
            return

        # Action for main menu in channelselector
        if ( item.action=="selectchannel" ):
            import channelselector
            itemlist = channelselector.getmainlist()

            # Check for updates only on first screen
            if config.get_setting("updatecheck2") == "true":
                logger.info("pelisalacarta.platformcode.launcher Check for plugin updates enabled")
                from core import updater
                
                try:
                    version = updater.checkforupdates()

                    if version:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("Versión "+version+" disponible","Ya puedes descargar la nueva versión del plugin\ndesde el listado principal")

                        itemlist.insert(0,Item(title="Descargar version "+version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png"))
                except:
                    import xbmcgui
                    advertencia = xbmcgui.Dialog()
                    advertencia.ok("No se puede conectar","No ha sido posible comprobar","si hay actualizaciones")
                    logger.info("cpelisalacarta.platformcode.launcher Fallo al verificar la actualización")

            else:
                logger.info("pelisalacarta.platformcode.launcher Check for plugin updates disabled")

            xbmctools.renderItems(itemlist, item)

        # Action for updating plugin
        elif (item.action=="update"):

            from core import updater
            updater.update(item)
            if config.get_system_platform()!="xbox":
                import xbmc
                xbmc.executebuiltin( "Container.Refresh" )

        # Action for channel types on channelselector: movies, series, etc.
        elif (item.action=="channeltypes"):
            import channelselector
            itemlist = channelselector.getchanneltypes()

            xbmctools.renderItems(itemlist, item)

        # Action for channel listing on channelselector
        elif (item.action=="listchannels"):
            import channelselector
            itemlist = channelselector.filterchannels(item.category)

            xbmctools.renderItems(itemlist, item)

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            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

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py")
            logger.info("pelisalacarta.platformcode.launcher channel_file=%s" % channel_file)

            if item.channel in ["personal","personal2","personal3","personal4","personal5"]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                channel = __import__('channels.%s' % item.channel, fromlist=["channels.%s" % item.channel])

            logger.info("pelisalacarta.platformcode.launcher running channel {0} {1}".format(channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                logger.info("pelisalacarta.platformcode.launcher play")

                # Mark as watched item on Library channel
                id_video = 0
                category = ''
                if 'infoLabels' in item:
                    if 'episodeid' in item.infoLabels and item.infoLabels['episodeid']:
                        category = 'Series'
                        id_video = item.infoLabels['episodeid']
                    elif 'movieid' in item.infoLabels and item.infoLabels['movieid']:
                        category = 'Movies'
                        id_video = item.infoLabels['movieid']

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method")
                    itemlist = channel.play(item)

                    # Play should return a list of playable URLS
                    if len(itemlist) > 0:
                        item = itemlist[0]
                        xbmctools.play_video(item)
                        if id_video != 0:
                            library.mark_as_watched(category, id_video)
                    
                    # If not, shows user an error message
                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok("plugin", "No hay nada para reproducir")

                # If player don't have a "play" function, not uses the standard play from xbmctools
                else:
                    logger.info("pelisalacarta.platformcode.launcher executing core 'play' method")
                    xbmctools.play_video(item)
                    if id_video != 0:
                        library.mark_as_watched(category, id_video)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

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

                # If not, uses the generic findvideos function
                else:
                    logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, executing core method")
                    from core 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)

                # Copy infolabels from parent item
                if 'infoLabels' in item:
                    
                    # All but title
                    if 'title' in item.infoLabels:
                        item.infoLabels.pop('title')
                    new_itemlist = itemlist[:]
                    itemlist = []
                    
                    for i in new_itemlist:
                        itemlist.append(i.clone(infoLabels=item.infoLabels))


                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                # Show xbmc items as "movies", so plot is visible
                import xbmcplugin

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

                # Add everything to XBMC item list
                if type(itemlist) == list and itemlist:
                    xbmctools.renderItems(itemlist, item)

                # If not, it shows an empty list
                # FIXME: Aquí deberíamos mostrar alguna explicación del tipo "No hay elementos, esto pasa por bla bla bla"
                else:
                    xbmctools.renderItems([], item)

            # Special action for playing a video from the library
            elif item.action == "play_from_library":
                play_from_library(item, channel, server_white_list, server_black_list)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                library.add_pelicula_to_library(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                library.add_serie_to_library(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                downloadtools.download_all_episodes(item, channel)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.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, item)

            # For all other actions
            else:
                logger.info("pelisalacarta.platformcode.launcher executing channel '"+item.action+"' method")
                itemlist = getattr(channel, item.action)(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
                if type(itemlist) == list and itemlist:
                    xbmctools.renderItems(itemlist, item)

                # If not, it shows an empty list
                # FIXME: Aquí deberíamos mostrar alguna explicación del tipo "No hay elementos, esto pasa por bla bla bla"
                else:
                    xbmctools.renderItems([], item)

    except urllib2.URLError,e:
        import traceback
        logger.error("pelisalacarta.platformcode.launcher "+traceback.format_exc())

        import xbmcgui
        ventana_error = xbmcgui.Dialog()

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info("pelisalacarta.platformcode.launcher Razon del error, codigo: {0}, Razon: {1}".format(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)
        
        # Grab server response errors
        elif hasattr(e,'code'):
            logger.info("pelisalacarta.platformcode.launcher 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)
Esempio n. 27
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)