Exemplo n.º 1
0
def play(params,url,category):
    logger.info("[sonolatino.py] play")

    title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "utf-8" )
    
    try:
        thumbnail = urllib.unquote_plus( params.get("thumbnail") )
    except:
        thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )
    plot = urllib.unquote_plus( params.get("plot") )
    plot = urllib.unquote_plus( params.get("plot") )

    try:
        plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" )
    except:
        plot = xbmc.getInfoLabel( "ListItem.Plot" )

    server = params["server"]
    logger.info("[sonolatino.py] thumbnail="+thumbnail)
    logger.info("[sonolatino.py] server="+server)
    
    if server == "izlesene":
        print server
        data = scrapertools.cachePage(url)
        print data
        patron = 'durl="([^"]+)"'
        matches = re.compile(patron,re.DOTALL).findall(data)
        if len(matches)>0:
            url = matches[0]
            server = "Directo"
    xbmctools.play_video(__channel__,server,url,category,title,thumbnail,plot)
Exemplo n.º 2
0
def play(params,url,category):
    logger.info("[sonolatino.py] play")

    title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "utf-8" )
    
    try:
        thumbnail = urllib.unquote_plus( params.get("thumbnail") )
    except:
        thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )
    plot = urllib.unquote_plus( params.get("plot") )
    plot = urllib.unquote_plus( params.get("plot") )

    try:
        plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" )
    except:
        plot = xbmc.getInfoLabel( "ListItem.Plot" )

    server = params["server"]
    logger.info("[sonolatino.py] thumbnail="+thumbnail)
    logger.info("[sonolatino.py] server="+server)
    
    if server == "izlesene":
        print server
        data = scrapertools.cachePage(url)
        print data
        patron = 'durl="([^"]+)"'
        matches = re.compile(patron,re.DOTALL).findall(data)
        if len(matches)>0:
            url = matches[0]
            server = "Directo"
    xbmctools.play_video(__channel__,server,url,category,title,thumbnail,plot)
Exemplo n.º 3
0
def enlaces(item):
    logger.info("pelisalacarta.arenavision scraper")
    
    itemlist = []
    import xbmcgui
    patron = '(AV\d+)'
    matches = re.compile(patron,re.DOTALL).findall(item.extra)
    for (i , f) in enumerate(matches):
        if "AV" in f:
            a = re.compile('AV(\d+)',re.DOTALL).findall(f)
            for (b,c) in enumerate(a):
                   
                   
                if c== "9" or c =="8" or c =="7" or c =="6" or c =="5" or c =="4" or c =="3" :
                    c= " "+c
                   
                if c <= "20" :
                    matches[i] = f.replace(f,"[COLOR crimson][B]"+matches[i]+"[/B][/COLOR]")+ "[COLOR palegreen][B]  Acestream[/B][/COLOR]"
                else:
                    matches[i] = f.replace(f,"[COLOR crimson][B]"+matches[i]+"[/B][/COLOR]")+ "[COLOR deepskyblue][B]  Sopcast[/B][/COLOR]"
            
            
        get_url= [(i,x) for i, x in enumerate(matches)]
        get_url = repr(get_url)
            #get_url= re.sub(r"\[COLOR.*?\]\[.*?]|\[.*?\]\[/COLOR\].*?\[.*?\]\[/COLOR\]","",get_url)
        print "marco"
        print get_url
        fulltitle =item.fulltitle
        print "pacopepe"
        print fulltitle
    index = xbmcgui.Dialog().select("[COLOR orange][B]Selecciona Canal...[/B][/COLOR]", matches)
        
    if index != -1:
        index =str(index)
        print "kkkk"
        print get_url
        if index == 0:
            catch_url=scrapertools.get_match(get_url,'\('+index+',.*?\'\[COLOR crimson\]\[B\](.*?)\[')
        catch_url=scrapertools.get_match(get_url,''+index+',.*?\'\[COLOR crimson\]\[B\](.*?)\[')
        url =urlparse.urljoin(host,catch_url)
            
        import xbmc
        xbmc.executebuiltin('xbmc.PlayMedia(Stop)')
        ### Esto sustituye a la función go
        data = scrapertools.cache_page(url)
        patron = '\*INFO.*?Click.*?<a href="([^"]+)"'
        url = scrapertools.find_single_match(data, patron)
        item.url = url +"|" + fulltitle
        print "tu vieja"
        print item.url
        item.server = "p2p"        
        xbmctools.play_video(item)
			
    else:
        import xbmc
        xbmc.executebuiltin( "XBMC.Container.Update" )
        return
Exemplo n.º 4
0
def play(params,url,category):
    logger.info("[stagevusite.py] play")

    title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "utf-8" )
    thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )
    plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" )
    logger.info("[stagevusite.py] thumbnail="+thumbnail)
    server="stagevu"

    xbmctools.play_video(__channel__,server,url,category,title,thumbnail,plot)
Exemplo n.º 5
0
def play(params, url, category):
    logger.info("[stagevusite.py] play")

    title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
    thumbnail = xbmc.getInfoImage("ListItem.Thumb")
    plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")
    logger.info("[stagevusite.py] thumbnail=" + thumbnail)
    server = "stagevu"

    xbmctools.play_video(__channel__, server, url, category, title, thumbnail,
                         plot)
Exemplo n.º 6
0
def youtubeplay(params,url,category):
    logger.info("[trailertools.py] youtubeplay")
    #http://www.youtube.com/watch?v=byvXidWNf2A&feature=youtube_gdata
    title = urllib.unquote_plus( params.get("title") )
    thumbnail = urllib.unquote_plus( params.get("thumbnail") )
    plot = "Ver Video"
    server = "youtube"
    #id = youtube.Extract_id(url)
    #videourl = youtube.geturl(id)

    xbmctools.play_video("Trailer",server,url,category,title,thumbnail,plot)
def youtubeplay(params, url, category):
    logger.info("[trailertools.py] youtubeplay")
    # http://www.youtube.com/watch?v=byvXidWNf2A&feature=youtube_gdata
    title = urllib.unquote_plus(params.get("title"))
    thumbnail = urllib.unquote_plus(params.get("thumbnail"))
    plot = "Ver Video"
    server = "youtube"
    # id = youtube.Extract_id(url)
    # videourl = youtube.geturl(id)

    xbmctools.play_video("Trailer", server, url, category, title, thumbnail, plot)
Exemplo n.º 8
0
def p2p(item):
    if "Sopcast" in item.title:
        texto = dialog_input(default='sop://broker.sopcast.com:3912/', heading="Introduce la url de sopcast")
        titulo = "[Sopcast]"
    else:
        texto = dialog_input(default='acestream://', heading="Introduce la url de acestream")
        titulo = "[Acestream]"
    if texto != "":
        url = texto + "|" + titulo
        from platformcode import xbmctools
        item_play = item.clone()
        item_play.url = url
        item_play.server = "p2p"
        xbmctools.play_video(item_play)
Exemplo n.º 9
0
def p2p(item):
    if "Sopcast" in item.title:
        texto = dialog_input(default='sop://broker.sopcast.com:3912/',
                             heading="Introduce la url de sopcast")
        titulo = "[Sopcast]"
    else:
        texto = dialog_input(default='acestream://',
                             heading="Introduce la url de acestream")
        titulo = "[Acestream]"
    if texto != "":
        url = texto + "|" + titulo
        from platformcode import xbmctools
        item_play = item.clone()
        item_play.url = url
        item_play.server = "p2p"
        xbmctools.play_video(item_play)
Exemplo n.º 10
0
def play_from_library(item, channel, server_white_list, server_black_list):
    logger.info("streamondemand.platformcode.launcher play_from_library")

    logger.info(
        "streamondemand.platformcode.launcher play_from_library item.server=#"
        + item.server + "#")

    elegido = item
    # DrZ3r0
    if item.action == "findvideos":
        # Ejecuta find_videos, del canal o común
        if hasattr(channel, 'findvideos'):
            itemlist = getattr(channel, item.action)(item)
        else:
            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)

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

            seleccion = platformtools.dialog_select(
                config.get_localized_string(30163), opciones)
            elegido = itemlist[seleccion]

            if seleccion == -1:
                return

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

    xbmctools.play_video(item, strmfile=True)
    library.mark_as_watched(item)
Exemplo n.º 11
0
def play_from_library(item, channel, server_white_list, server_black_list):
    logger.info("pelisalacarta.platformcode.launcher play_from_library")

    category = item.category

    logger.info("pelisalacarta.platformcode.launcher play_from_library item.server=#"+item.server+"#")
    # Ejecuta find_videos, del canal o común
    try:
        itemlist = getattr(channel, "findvideos")(item)

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

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

    if len(itemlist) > 0:
        # 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("pelisalacarta.platformcode.launcher play_from_library Elegido %s (sub %s)" % (item.title, item.subtitle))

    xbmctools.play_video(item, strmfile=True)
    library.mark_as_watched(category, 0)
Exemplo n.º 12
0
def play_from_library(item, channel, server_white_list, server_black_list):
    logger.info("streamondemand.platformcode.launcher play_from_library")

    logger.info("streamondemand.platformcode.launcher play_from_library item.server=#"+item.server+"#")

    elegido = item
    # DrZ3r0
    if item.action == "findvideos":
        # Ejecuta find_videos, del canal o común
        if hasattr(channel, 'findvideos'):
            itemlist = getattr(channel, item.action)(item)
        else:
            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)

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

            seleccion = platformtools.dialog_select(config.get_localized_string(30163), opciones)
            elegido = itemlist[seleccion]

            if seleccion == -1:
                return

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

    xbmctools.play_video(item, strmfile=True)
    library.mark_as_watched(item)
Exemplo n.º 13
0
def get_next_items(item):

    plugintools.log("navigation.get_next_items item=" + item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel == "navigation":

            if item.action == "mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel == "channelselector":

            if item.action == "channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            if item.action == "program_types":
                plugintools.log("navigation.get_next_items Program types menu")
                itemlist = channelselector.get_program_types("bannermenu")

            elif item.action == "listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(
                    item.category, "bannermenu")

        elif item.channel == "configuracion":
            plugintools.open_settings_dialog()
            return []

        else:

            if item.action == "":
                item.action = "mainlist"

            plugintools.log("navigation.get_next_items Channel code (" +
                            item.channel + "." + item.action + ")")

            try:
                exec "import channels." + item.channel + " as channel"
            except:
                exec "import core." + item.channel + " as channel"

            from platformcode import xbmctools

            if item.action == "play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log(
                        "pelisalacarta.platformcode.launcher Channel has its own 'play' method"
                    )
                    itemlist = channel.play(item)
                    if len(itemlist) > 0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(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=item.fulltitle,
                                                 Serie=item.show)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok("plugin",
                                              "No hay nada para reproducir")
                else:
                    plugintools.log(
                        "pelisalacarta.platformcode.launcher No channel 'play' method, executing core method"
                    )

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(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=item.fulltitle,
                                             Serie=item.show)
                    except:
                        pass

                return []

            elif item.action == "findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log(
                        "pelisalacarta.platformcode.launcher Channel has its own 'findvideos' method"
                    )
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist) == 0:
                    from servers import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist) == 0:
                    itemlist = [
                        Item(title="No se han encontrado vídeos",
                             thumbnail=os.path.join(
                                 plugintools.get_runtime_path(), "resources",
                                 "images", "thumb_error.png"))
                    ]

            else:

                if item.action == "search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado != "":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                elif item.channel == "novedades" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                elif item.channel == "buscador" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                else:
                    exec "itemlist = channel." + item.action + "(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail == "":
                        if loaded_item.folder:
                            loaded_item.thumbnail = os.path.join(
                                plugintools.get_runtime_path(), "resources",
                                "images", "thumb_folder.png")
                        else:
                            loaded_item.thumbnail = os.path.join(
                                plugintools.get_runtime_path(), "resources",
                                "images", "thumb_nofolder.png")

                if len(itemlist) == 0:
                    itemlist = [
                        Item(title="No hay elementos para mostrar",
                             thumbnail=os.path.join(
                                 plugintools.get_runtime_path(), "resources",
                                 "images", "thumb_error.png"))
                    ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items " + traceback.format_exc())
        itemlist = [
            Item(title="Se ha producido un error",
                 thumbnail=os.path.join(plugintools.get_runtime_path(),
                                        "resources", "images",
                                        "thumb_error.png"))
        ]

    return itemlist
Exemplo n.º 14
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)
def get_next_items( item ):

    plugintools.log("navigation.get_next_items item="+item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel=="navigation":
		            # --- Update channels list ---------------------------------------
            from core import config
            if item.action=="mainlist":
                plugintools.log("navigation.get_next_items Main menu")

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

            if item.action=="mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel=="channelselector":

            if item.action=="channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action=="listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(item.category,"bannermenu")

        elif item.channel=="configuracion":
            plugintools.open_settings_dialog()
            return []

        else:

            if item.action=="":
                item.action="mainlist"

            plugintools.log("navigation.get_next_items Channel code ("+item.channel+"."+item.action+")")

            # --- Update channels files --------------------------------------
            if item.action=="mainlist":
                from core import config
                if 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",item.channel,config.get_localized_string(30063))
                    except:
                        pass
            # ----------------------------------------------------------------

            try:
                exec "import channels."+item.channel+" as channel"
            except:
                exec "import core."+item.channel+" as channel"

            from platformcode import xbmctools

            if item.action=="play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log("streamondemand-pureita.navigation.py Channel has its own 'play' method")
                    itemlist = channel.play(item)
                    if len(itemlist)>0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(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=item.fulltitle, Serie=item.show)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                else:
                    plugintools.log("streamondemand-pureita.navigation.py No channel 'play' method, executing core method")

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(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=item.fulltitle, Serie=item.show)
                    except:
                        pass


                return []

            elif item.action=="findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log("streamondemand-pureita.navigation.py Channel has its own 'findvideos' method")
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist)==0:
                    from servers import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist)==0:
                    itemlist = [ Item(title="No se han encontrado vídeos", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]
            # ---------------add_serie_to_library-----------
            elif item.action=="add_serie_to_library":
                plugintools.log("navigation.get_next_items add_serie_to_library")
                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-pureita', 'Añadiendo episodios...')
                pDialog.update(0, 'Añadiendo episodio...')
                totalepisodes = len(itemlist)
                plugintools.log ("navigation.get_next_items 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)
                    plugintools.log("streamondemand-pureita.navigation.py 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 )
                        plugintools.log("streamondemand-pureita.navigation.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="ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"))
                    plugintools.log ("navigation.get_next_items No se pudo añadir "+str(errores)+" episodios")
                else:
                    itemlist.append(Item(title="La serie è stata aggiunta alla biblioteca"))
                    plugintools.log ("navigation.get_next_items 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
                from core import config
                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" )

                plugintools.log("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();
                return itemlist
            # --------------------------------------------------------------------
            elif item.action=="download_all_episodes":
                plugintools.log("navigation.get_next_items download_all_episodes")
                download_all_episodes(item,channel)
			#---------------------------------------------------------------------
            else:

                if item.action=="search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado!="":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                elif item.channel=="novedades" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                elif item.channel=="buscador" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                else:
                    exec "itemlist = channel."+item.action+"(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail=="":
                        if loaded_item.folder:
                            loaded_item.thumbnail = os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_folder.png" )
                        else:
                            loaded_item.thumbnail = os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_nofolder.png" )

                if len(itemlist)==0:
                    itemlist = [ Item(title="No hay elementos para mostrar", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items "+traceback.format_exc())
        itemlist = [ Item(title="Se ha producido un error", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]


    return itemlist
def get_next_items(item):

    plugintools.log("navigation.get_next_items item=" + item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel == "navigation":
            # --- Update channels list ---------------------------------------
            from core import config
            if item.action == "mainlist":
                plugintools.log("navigation.get_next_items Main menu")

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

            if item.action == "mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel == "channelselector":

            if item.action == "channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action == "listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(
                    item.category, "bannermenu")

        elif item.channel == "configuracion":
            plugintools.open_settings_dialog()
            return []

        else:

            if item.action == "":
                item.action = "mainlist"

            plugintools.log("navigation.get_next_items Channel code (" +
                            item.channel + "." + item.action + ")")

            # --- Update channels files --------------------------------------
            if item.action == "mainlist":
                from core import config
                if 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", item.channel,
                                           config.get_localized_string(30063))
                    except:
                        pass
            # ----------------------------------------------------------------

            try:
                exec "import channels." + item.channel + " as channel"
            except:
                exec "import core." + item.channel + " as channel"

            from platformcode import xbmctools

            if item.action == "play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log(
                        "streamondemand-pureita.navigation.py Channel has its own 'play' method"
                    )
                    itemlist = channel.play(item)
                    if len(itemlist) > 0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(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=item.fulltitle,
                                                 Serie=item.show)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok("plugin",
                                              "Nessun File Da Riprodurre")
                else:
                    plugintools.log(
                        "streamondemand-pureita.navigation.py No channel 'play' method, executing core method"
                    )

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(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=item.fulltitle,
                                             Serie=item.show)
                    except:
                        pass

                return []

            elif item.action == "findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log(
                        "streamondemand-pureita.navigation.py Channel has its own 'findvideos' method"
                    )
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist) == 0:
                    from servers import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist) == 0:
                    itemlist = [
                        Item(title="No se han encontrado vídeos",
                             thumbnail=os.path.join(
                                 plugintools.get_runtime_path(), "resources",
                                 "images", "thumb_error.png"))
                    ]
            # ---------------add_serie_to_library-----------
            elif item.action == "add_serie_to_library":
                plugintools.log(
                    "navigation.get_next_items add_serie_to_library")
                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-pureita',
                                     'Añadiendo episodios...')
                pDialog.update(0, 'Añadiendo episodio...')
                totalepisodes = len(itemlist)
                plugintools.log("navigation.get_next_items 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)
                    plugintools.log(
                        "streamondemand-pureita.navigation.py 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)
                        plugintools.log(
                            "streamondemand-pureita.navigation.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=
                            "ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"
                        ))
                    plugintools.log(
                        "navigation.get_next_items No se pudo añadir " +
                        str(errores) + " episodios")
                else:
                    itemlist.append(
                        Item(
                            title="La serie è stata aggiunta alla biblioteca"))
                    plugintools.log(
                        "navigation.get_next_items 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
                from core import config
                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")

                plugintools.log("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()
                return itemlist
            # --------------------------------------------------------------------
            elif item.action == "download_all_episodes":
                plugintools.log(
                    "navigation.get_next_items download_all_episodes")
                download_all_episodes(item, channel)

#---------------------------------------------------------------------
            else:

                if item.action == "search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado != "":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                elif item.channel == "novedades" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                elif item.channel == "buscador" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                else:
                    exec "itemlist = channel." + item.action + "(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail == "":
                        if loaded_item.folder:
                            loaded_item.thumbnail = os.path.join(
                                plugintools.get_runtime_path(), "resources",
                                "images", "thumb_folder.png")
                        else:
                            loaded_item.thumbnail = os.path.join(
                                plugintools.get_runtime_path(), "resources",
                                "images", "thumb_nofolder.png")

                if len(itemlist) == 0:
                    itemlist = [
                        Item(title="Nessun Elemento Da Visualizzare",
                             thumbnail=os.path.join(
                                 plugintools.get_runtime_path(), "resources",
                                 "images", "thumb_error.png"))
                    ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items " + traceback.format_exc())
        itemlist = [
            Item(title="Rimozione Effettuata - Riavviare",
                 thumbnail=os.path.join(plugintools.get_runtime_path(),
                                        "resources", "images",
                                        "thumb_error.png"))
        ]

    return itemlist
def buscartrailer(item):
    logger.info("streamondemand.channels.trailertools buscartrailer")

    # Se elimina la opciçon de Buscar Trailer del menú contextual para evitar redundancias
    item.context = item.context.replace("5", "")
    item.text_color = ""
    # Si no se indica el parámetro contextual se entiende que no se ejecuta desde este mení
    if item.contextual == "":
        item.contextual = False

    itemlist = []
    if item.contentTitle != "":
        item.contentTitle = item.contentTitle.strip()
    elif keyboard:
        item.contentTitle = platformtools.dialog_input(
            heading="Introduce el título a buscar")
        if item.contentTitle is None:
            item.contentTitle = item.fulltitle.strip()
        else:
            item.contentTitle = item.contentTitle.strip()
    else:
        item.contentTitle = item.fulltitle.strip()

    item.year = item.infoLabels['year'] if "year" in item.infoLabels else ""
    logger.info("streamondemand.channels.trailertools Búsqueda: %s" %
                item.contentTitle)
    logger.info("streamondemand.channels.trailertools Año: %s" % item.year)

    # Lista de acciones si se ejecuta desde el menú contextual
    if item.action == "manual_search":
        itemlist = manual_search(item)
        item.contentTitle = itemlist[0].contentTitle
    elif item.action == "youtube_search":
        itemlist = youtube_search(item)
    elif item.action == "filmaffinity_search":
        itemlist = filmaffinity_search(item)
    elif item.action == "abandomoviez_search":
        itemlist = abandomoviez_search(item)
    elif item.action == "jayhap_search":
        itemlist = jayhap_search(item)
    else:
        if "trailer" in item.infoLabels and item.infoLabels['trailer'] != "":
            url = item.infoLabels['trailer']
            if "youtube" in url:
                url = url.replace("embed/", "watch?v=")
            titulo, url, server = servertools.findvideos(url)[0]
            title = "Trailer por defecto  [" + server + "]"
            itemlist.append(
                item.clone(title=title, url=url, server=server, action="play"))
        if item.show != "" or ("tvshowtitle" in item.infoLabels
                               and item.infoLabels['tvshowtitle'] != ""):
            type = "tv"
        else:
            type = "movie"
        try:
            itemlist.extend(tmdb_trailers(item, type))
        except:
            import traceback
            logger.error(traceback.format_exc())

        title = "[COLOR green]%s[/COLOR]" if item.contextual else "%s"
        itemlist.append(
            item.clone(title=title % "Búsqueda en Youtube",
                       action="youtube_search",
                       text_color="green"))
        itemlist.append(
            item.clone(title=title % "Búsqueda en Filmaffinity",
                       action="filmaffinity_search",
                       text_color="green"))
        # Si se trata de una serie, no se incluye la opción de buscar en Abandomoviez
        if item.show == "" and ("tvshowtitle" not in item.infoLabels
                                or item.infoLabels['tvshowtitle'] == ""):
            itemlist.append(
                item.clone(title=title % "Búsqueda en Abandomoviez",
                           action="abandomoviez_search",
                           text_color="green"))
        itemlist.append(
            item.clone(title=title %
                       "Búsqueda en Jayhap (Youtube, Vimeo & Dailymotion)",
                       action="jayhap_search",
                       text_color="green"))

    if item.contextual:
        opciones = []
        if itemlist:
            for video_url in itemlist:
                opciones.append(video_url.title)

            seleccion = platformtools.dialog_select(
                "Buscando: " + item.contentTitle, opciones)
            logger.info("seleccion=%d" % seleccion)
            logger.info("seleccion=%s" % opciones[seleccion])

            if seleccion < 0:
                return
            else:
                item = itemlist[seleccion]
                if "search" in item.action:
                    buscartrailer(item)
                else:
                    if item.action == "play":
                        from platformcode import xbmctools
                        xbmctools.play_video(item)
                    return
    else:
        return itemlist
def run():
    logger.info("streamondemand.platformcode.launcher 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(
        "streamondemand.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"
        % (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(params, url, category)

        # Actualizar version
        elif (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 (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" 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(
                "streamondemand.platformcode.launcher regular_channel_path=%s"
                % regular_channel_path)
            logger.info(
                "streamondemand.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(
                "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 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 (action == "strm"):
                    from platformcode import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel." + action + "(params, url, category)"
            else:
                logger.info(
                    "streamondemand.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)
                '''
                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 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(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",
                                                  "Niente da riprodurre")
                    else:
                        logger.info(
                            "streamondemand.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)

                elif action == "strm_detail" or 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
                    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(
                        "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 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('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(
                            "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:
                            import sys
                            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 la 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, 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("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, params, url, category)

                else:
                    logger.info(
                        "streamondemand.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)"
                        # 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)

                        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: %s , 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)
def buscartrailer(item):
    logger.info("fusionse.channels.trailertools buscartrailer")

    # Se elimina la opciçon de Buscar Trailer del menú contextual para evitar redundancias
    item.context = item.context.replace("5", "")
    item.text_color = ""
    # Si no se indica el parámetro contextual se entiende que no se ejecuta desde este mení
    if item.contextual == "":
        item.contextual = False

    itemlist = []
    if item.contentTitle != "":
        item.contentTitle = item.contentTitle.strip()
    elif keyboard:
        item.contentTitle = platformtools.dialog_input(heading="Introduce el título a buscar")
        if item.contentTitle is None:
            item.contentTitle = item.fulltitle.strip()
        else:
            item.contentTitle = item.contentTitle.strip()
    else:
        item.contentTitle = item.fulltitle.strip()
        
    item.year = item.infoLabels['year'] if "year" in item.infoLabels else ""
    logger.info("fusionse.channels.trailertools Búsqueda: %s" % item.contentTitle)
    logger.info("fusionse.channels.trailertools Año: %s" % item.year)

    # Lista de acciones si se ejecuta desde el menú contextual
    if item.action == "manual_search":
        itemlist = manual_search(item)
        item.contentTitle = itemlist[0].contentTitle
    elif item.action == "youtube_search":
        itemlist = youtube_search(item)
    elif item.action == "filmaffinity_search":
        itemlist = filmaffinity_search(item)
    elif item.action == "abandomoviez_search":
        itemlist = abandomoviez_search(item)
    elif item.action == "jayhap_search":
        itemlist = jayhap_search(item)
    else:
        if "trailer" in item.infoLabels and item.infoLabels['trailer'] != "":
            url = item.infoLabels['trailer']
            if "youtube" in url:
                url = url.replace("embed/", "watch?v=")
            titulo, url, server = servertools.findvideos(url)[0]
            title = "Trailer por defecto  [" + server + "]"
            itemlist.append(item.clone(title=title, url=url, server=server, action="play"))
        if item.show != "" or ("tvshowtitle" in item.infoLabels and item.infoLabels['tvshowtitle'] != ""):
            type = "tv"
        else:
            type = "movie"
        try:
            itemlist.extend(tmdb_trailers(item, type))
        except:
            import traceback
            logger.error(traceback.format_exc())
        
        title = "[COLOR green]%s[/COLOR]" if item.contextual else "%s"
        itemlist.append(item.clone(title=title % "Búsqueda en Youtube", action="youtube_search",
                                   text_color="green"))
        itemlist.append(item.clone(title=title % "Búsqueda en Filmaffinity",
                                   action="filmaffinity_search", text_color="green"))
        # Si se trata de una serie, no se incluye la opción de buscar en Abandomoviez
        if item.show == "" and ("tvshowtitle" not in item.infoLabels or item.infoLabels['tvshowtitle'] == ""):
            itemlist.append(item.clone(title=title % "Búsqueda en Abandomoviez",
                                       action="abandomoviez_search", text_color="green"))
        itemlist.append(item.clone(title=title % "Búsqueda en Jayhap (Youtube, Vimeo & Dailymotion)",
                                   action="jayhap_search", text_color="green"))

    if item.contextual:
        opciones = []
        if itemlist:
            for video_url in itemlist:
                opciones.append(video_url.title)

            seleccion = platformtools.dialog_select("Buscando: "+item.contentTitle, opciones)
            logger.info("seleccion=%d" % seleccion)
            logger.info("seleccion=%s" % opciones[seleccion])

            if seleccion < 0:
                return
            else:
                item = itemlist[seleccion]
                if "search" in item.action:
                    buscartrailer(item)
                else:
                    if item.action == "play":
                        from platformcode import xbmctools
                        xbmctools.play_video(item)
                    return
    else:
        return itemlist
Exemplo n.º 20
0
def run():
    logger.info("pelisalacarta.platformcode.launcher run")

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

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

    try:
        # Default action: open channel and launch mainlist function
        if ( action=="selectchannel" ):

            if config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

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

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

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

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

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

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

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

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

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

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

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

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

                if not can_open_channel:
                    return

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

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

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en pelisalacarta
            regular_channel_path = os.path.join( config.get_runtime_path() , 'channels' , channel_name+".py" )
            core_channel_path = os.path.join( config.get_runtime_path(), 'core' , channel_name+".py" )
            logger.info("pelisalacarta.platformcode.launcher regular_channel_path=%s" % regular_channel_path)
            logger.info("pelisalacarta.platformcode.launcher core_channel_path=%s" % core_channel_path)

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

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

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

            if not generico:
                logger.info("pelisalacarta.platformcode.launcher xbmc native channel")
                if (action=="strm"):
                    from platformcode import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel."+action+"(params, url, category)"
            else:            
                logger.info("pelisalacarta.platformcode.launcher multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name, title=title , fulltitle=fulltitle, url=url, thumbnail=thumbnail , plot=plot , server=server, category=category, extra=extra, subtitle=subtitle, viewmode=viewmode, show=show, password=password, fanart=fanart, hasContentDetails=hasContentDetails, contentTitle=contentTitle, contentThumbnail=contentThumbnail, contentPlot=contentPlot)
                
                '''
                if item.subtitle!="":
                    logger.info("pelisalacarta.platformcode.launcher Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("pelisalacarta.platformcode.launcher No subtitle")
                '''
                from platformcode import xbmctools

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

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

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

                    logger.info("item.server=#"+item.server+"#")
                    # Ejecuta find_videos, del canal o común
                    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)    
Exemplo n.º 21
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)    
Exemplo n.º 22
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)
Exemplo n.º 23
0
def get_next_items( item ):

    plugintools.log("navigation.get_next_items item="+item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel=="navigation":

            if item.action=="mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel=="channelselector":

            if item.action=="channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action=="listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(item.category,"bannermenu")

        elif item.channel=="configuracion":
            plugintools.open_settings_dialog()
            return []

        else:

            if item.action=="":
                item.action="mainlist"

            plugintools.log("navigation.get_next_items Channel code ("+item.channel+"."+item.action+")")

            try:
                exec "import channels."+item.channel+" as channel"
            except:
                exec "import core."+item.channel+" as channel"

            from platformcode import xbmctools

            if item.action=="play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log("pelisalacarta.platformcode.launcher Channel has its own 'play' method")
                    itemlist = channel.play(item)
                    if len(itemlist)>0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(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=item.fulltitle, Serie=item.show)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                else:
                    plugintools.log("pelisalacarta.platformcode.launcher No channel 'play' method, executing core method")

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(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=item.fulltitle, Serie=item.show)
                    except:
                        pass


                return []

            elif item.action=="findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log("pelisalacarta.platformcode.launcher Channel has its own 'findvideos' method")
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist)==0:
                    from servers import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist)==0:
                    itemlist = [ Item(title="No se han encontrado vídeos", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]

            else:

                if item.action=="search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado!="":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                elif item.channel=="novedades" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                elif item.channel=="buscador" and item.action=="mainlist":
                    itemlist = channel.mainlist(item,"bannermenu")
                else:
                    exec "itemlist = channel."+item.action+"(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail=="":
                        if loaded_item.folder:
                            loaded_item.thumbnail = os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_folder.png" )
                        else:
                            loaded_item.thumbnail = os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_nofolder.png" )

                if len(itemlist)==0:
                    itemlist = [ Item(title="No hay elementos para mostrar", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items "+traceback.format_exc())
        itemlist = [ Item(title="Se ha producido un error", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]


    return itemlist
Exemplo n.º 24
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)
Exemplo n.º 25
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)
Exemplo n.º 26
0
def get_next_items(item):

    plugintools.log("navigation.get_next_items item=" + item.tostring())

    try:
        # ----------------------------------------------------------------
        #  Main menu
        # ----------------------------------------------------------------
        if item.channel == "navigation":

            if item.action == "mainlist":
                plugintools.log("navigation.get_next_items Main menu")
                itemlist = channelselector.getmainlist("bannermenu")

        elif item.channel == "channelselector":

            if item.action == "channeltypes":
                plugintools.log("navigation.get_next_items Channel types menu")
                itemlist = channelselector.getchanneltypes("bannermenu")

            elif item.action == "listchannels":
                plugintools.log("navigation.get_next_items Channel list menu")
                itemlist = channelselector.filterchannels(
                    item.category, "bannermenu")

        else:

            if item.action == "":
                item.action = "mainlist"

            plugintools.log("navigation.get_next_items Channel code (" +
                            item.channel + "." + item.action + ")")

            try:
                exec "import channels." + item.channel + " as channel"
            except:
                exec "import core." + item.channel + " as channel"

            from platformcode import xbmctools

            if item.action == "play":
                plugintools.log("navigation.get_next_items play")

                # Si el canal tiene una acción "play" tiene prioridad
                if hasattr(channel, 'play'):
                    plugintools.log(
                        "navigation.get_next_items play Channel has its own 'play' method"
                    )
                    itemlist = channel.play(item)
                    if len(itemlist) > 0:
                        item = itemlist[0]

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(item)
                        except:
                            pass

                    else:
                        import xbmcgui
                        ventana_error = xbmcgui.Dialog()
                        ok = ventana_error.ok("plugin",
                                              "No hay nada para reproducir")
                else:
                    plugintools.log(
                        "navigation.get_next_items play No channel 'play' method, executing core method"
                    )

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(item)
                    except:
                        import traceback
                        plugintools.log(traceback.format_exc())
                        pass

                return []

            elif item.action == "findvideos":
                plugintools.log("navigation.get_next_items findvideos")

                # Si el canal tiene una acción "findvideos" tiene prioridad
                if hasattr(channel, 'findvideos'):
                    plugintools.log(
                        "navigation.get_next_items play Channel has its own 'findvideos' method"
                    )
                    itemlist = channel.findvideos(item)
                else:
                    itemlist = []

                if len(itemlist) == 0:
                    from core import servertools
                    itemlist = servertools.find_video_items(item)

                if len(itemlist) == 0:
                    itemlist = [
                        Item(
                            title="No se han encontrado vídeos",
                            thumbnail=
                            "http://media.tvalacarta.info/pelisalacarta/thumb_error.png"
                        )
                    ]

            else:

                if item.action == "search":
                    tecleado = plugintools.keyboard_input()
                    if tecleado != "":
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                elif item.channel == "novedades" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                elif item.channel == "buscador" and item.action == "mainlist":
                    itemlist = channel.mainlist(item, "bannermenu")
                else:
                    exec "itemlist = channel." + item.action + "(item)"

                for loaded_item in itemlist:

                    if loaded_item.thumbnail == "":
                        if loaded_item.folder:
                            loaded_item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_folder.png"
                        else:
                            loaded_item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_nofolder.png"

                if len(itemlist) == 0:
                    itemlist = [
                        Item(
                            title="No hay elementos para mostrar",
                            thumbnail=
                            "http://media.tvalacarta.info/pelisalacarta/thumb_error.png"
                        )
                    ]

    except:
        import traceback
        plugintools.log("navigation.get_next_items " + traceback.format_exc())
        itemlist = [
            Item(title="Se ha producido un error",
                 thumbnail=
                 "http://media.tvalacarta.info/pelisalacarta/thumb_error.png")
        ]

    return itemlist