def get_list_canales():
    logger.info("streamondemand.channels.novedades get_list_canales")

    list_canales = {'peliculas': [], 'infantiles': [], 'series': [], 'anime': [], 'documentales': []}

    # Rellenar listas de canales disponibles
    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    channel_language = config.get_setting("channel_language")

    if channel_language == "":
        channel_language = "all"

    for infile in sorted(glob.glob(channels_path)):
        list_result_canal = []
        channel_id = os.path.basename(infile)[:-4]
        channel_parameters = channeltools.get_channel_parameters(channel_id)

        # No incluir si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue
        # No incluir si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue
        # No incluir si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        # Incluir en cada categoria, si en su configuracion el canal esta activado para mostrar novedades
        for categoria in list_canales:
            include_in_newest = config.get_setting("include_in_newest_" + categoria, channel_id)
            if include_in_newest:
                channels_ID_name[channel_id] = channel_parameters["title"]
                list_canales[categoria].append((channel_id,channel_parameters["title"]))

    return list_canales
示例#2
0
def channel_status(item, dict_values):
    try:
        for v in dict_values:

            if v == "all_channels":
                import channelselector
                from core import channeltools
                logger.info("Todos los canales | Estado seleccionado: %s" %
                            str(dict_values[v]).lower())
                if str(dict_values[v]) != "0":
                    channel_list = channelselector.filterchannels("allchannelstatus")
                    excluded_channels = ['tengourl', 'buscador',
                                         'libreria', 'configuracion',
                                         'novedades', 'personal',
                                         'ayuda', 'descargas']
                    for channel in channel_list:
                        if channel.channel not in excluded_channels:
                            channel_parameters = channeltools.get_channel_parameters(channel.channel)
                            new_status_all_default = None
                            new_status_all = None
                            new_status_all_default = channel_parameters["active"]

                            # Opcion Activar todos
                            if str(dict_values[v]) == "1":
                                new_status_all = "true"

                            # Opcion Desactivar todos
                            if str(dict_values[v]) == "2":
                                new_status_all = "false"

                            # Opcion Recuperar estado por defecto
                            if str(dict_values[v]) == "3":
                                # Si tiene "enabled" en el json es porque el estado no es el del xml
                                if config.get_setting("enabled", channel.channel):
                                    new_status_all = new_status_all_default

                                # Si el canal no tiene "enabled" en el json no se guarda, se pasa al siguiente
                                else:
                                    continue

                            # Se guarda el estado del canal
                            if new_status_all is not None:
                                config.set_setting("enabled", new_status_all, channel.channel)
                    break
                else:
                    continue

            else:
                logger.info("Canal: %s | Estado: %s" %
                            (v, str(dict_values[v]).lower()))
                config.set_setting("enabled", str(dict_values[v]).lower(), v)

        platformtools.itemlist_update(Item(channel=CHANNELNAME, action="mainlist"))

    except:
        import traceback
        logger.info("Detalle del error: %s" % traceback.format_exc())
        platformtools.dialog_notification("Error",
                                          "Se ha producido un error al guardar")
def filterchannels(category,preferred_thumb=""):
    logger.info("channelselector.filterchannels")

    try:
        idioma = config.get_setting("languagefilter")
        logger.info("channelselector.filterchannels idioma=%s" % idioma)
        langlistv = ["","ES","EN","IT","PT"]
        idiomav = langlistv[int(idioma)]
        logger.info("channelselector.filterchannels idiomav=%s" % idiomav)
    except:
        idiomav=""

    activechannels =  []
    channelslist =[]
    category=category.replace("L","latino").replace("M","music").replace("X","adult").replace("T","torrent").replace("VOS","vos").replace("F","movie").replace("S","serie").replace("D","documentary").replace("A","anime").replace("*","all")

    channel_path = os.path.join(config.get_runtime_path(),"channels")
    logger.info("channelselector.filterchannels channel_path="+channel_path)

    for channel in os.listdir(channel_path):
        logger.info("channelselector.filterchannels channel="+channel)
        if channel.endswith(".xml"):
            try:
                ChannelData = channeltools.get_channel_parameters(channel[:-4])
                if not ChannelData["thumbnail"]: 
                    ChannelData["thumbnail"] = get_thumbnail_path(preferred_thumb)+ChannelData["channel"]+".png"
                else:
                    # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea
                    if preferred_thumb=="bannermenu" and "bannermenu" in ChannelData:
                        ChannelData["thumbnail"]=ChannelData["bannermenu"]
        
                if not ChannelData["active"] == "true":  continue #Si no esta activo lo saltamos
                if ChannelData["adult"] == "true" and not config.get_setting("adult_mode") == "true": continue # Si es adulto y no estan activados lo saltamos
                if not category=="all" and not category in ChannelData["category"] and not "all" in ChannelData["category"]: continue #Si no corresponde la categoria lo saltamos
                if not ChannelData["language"]=="" and not idiomav=="" and not idiomav.lower() in ChannelData["language"]: continue #Si no corresponde el idioma lo saltamos
            
                if ChannelData["channel"]=="tengourl":
                    channelslist.append(Item(title=ChannelData["title"], channel=ChannelData["channel"], action="mainlist", thumbnail=ChannelData["thumbnail"] , fanart=ChannelData["fanart"], category=", ".join(ChannelData["category"])[:-2], language=ChannelData["language"], type=ChannelData["type"] ))
                else:
                    activechannels.append(Item(title=ChannelData["title"], channel=ChannelData["channel"], action="mainlist", thumbnail=ChannelData["thumbnail"] , fanart=ChannelData["fanart"] , category=", ".join(ChannelData["category"])[:-2], language=ChannelData["language"], type=ChannelData["type"] ))
            except:
                logger.info("Se ha producido un error al leer los datos del canal " + channel)
                import traceback
                logger.info(traceback.format_exc())

    if config.get_setting("personalchannel")=="true":
        channelslist.append( Item( title=config.get_setting("personalchannelname") ,action="mainlist", channel="personal" ,thumbnail=config.get_setting("personalchannellogo"), language="" , category="F,S,D,A" , type="generic"  ))
    if config.get_setting("personalchannel2")=="true":
        channelslist.append( Item( title=config.get_setting("personalchannelname2") ,action="mainlist", channel="personal2" ,thumbnail=config.get_setting("personalchannellogo2"), language="" , category="F,S,D,A" , type="generic"  ))
    if config.get_setting("personalchannel3")=="true":
        channelslist.append( Item( title=config.get_setting("personalchannelname3") ,action="mainlist", channel="personal3" ,thumbnail=config.get_setting("personalchannellogo3"), language="" , category="F,S,D,A" , type="generic"  ))
    if config.get_setting("personalchannel4")=="true":
        channelslist.append( Item( title=config.get_setting("personalchannelname4") ,action="mainlist", channel="personal4" ,thumbnail=config.get_setting("personalchannellogo4"), language="" , category="F,S,D,A" , type="generic"  ))
    if config.get_setting("personalchannel5")=="true":
        channelslist.append( Item( title=config.get_setting("personalchannelname5") ,action="mainlist", channel="personal5" ,thumbnail=config.get_setting("personalchannellogo5"), language="" , category="F,S,D,A" , type="generic"  ))
           
    activechannels.sort(key=lambda item: item.title.lower().strip())
    channelslist.extend(activechannels)
    return channelslist
def getchanneltypes(preferred_thumb=""):
    logger.info("channelselector getchanneltypes")

    # Lista de categorias
    valid_types = [ "movie","serie","anime","documentary","vos","torrent","latino","adult"]

    # Lee la lista de canales
    channel_path = os.path.join( config.get_runtime_path() , "channels" , '*.xml' )
    logger.info("channelselector.getchanneltypes channel_path="+channel_path)

    channel_files = glob.glob(channel_path)

    channel_language = config.get_setting("channel_language")
    logger.info("channelselector.getchanneltypes channel_language="+channel_language)

    # Construye la lista de tipos
    channel_types = []

    for index, channel in enumerate(channel_files):
        logger.info("channelselector.getchanneltypes channel="+channel)
        if channel.endswith(".xml"):
            try:
                channel_parameters = channeltools.get_channel_parameters(channel[:-4])
                logger.info("channelselector.filterchannels channel_parameters="+repr(channel_parameters))

                # Si es un canal para adultos y el modo adulto está desactivado, se lo salta
                if channel_parameters["adult"]=="true" and config.get_setting("adult_mode")=="false":
                    continue

                # Si el canal está en un idioma filtrado
                if channel_language!="all" and channel_parameters["language"]!=channel_language:
                    continue

                categories = channel_parameters["categories"]
                for category in categories:
                    logger.info("channelselector.filterchannels category="+category)
                    if category not in channel_types and category in valid_types:
                        channel_types.append(category)

            except:
                logger.info("Se ha producido un error al leer los datos del canal " + channel + traceback.format_exc())

    logger.info("channelselector.getchanneltypes Encontrados:")
    for channel_type in channel_types:
        logger.info("channelselector.getchanneltypes channel_type="+channel_type)

    # Ahora construye el itemlist ordenadamente
    itemlist = []
    itemlist.append( Item( title=config.get_localized_string(30121) , channel="channelselector" , action="listchannels" , category="all"         , thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),"thumb_canales_todos.png")))
    logger.info("channelselector.getchanneltypes Ordenados:")
    for channel_type in valid_types:
        logger.info("channelselector.getchanneltypes channel_type="+channel_type)
        if channel_type in channel_types:
            itemlist.append( Item( title=channel_type , channel="channelselector" , action="listchannels" , category=channel_type , thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),"thumb_canales_"+channel_type+".png")))

    return itemlist
示例#5
0
def settingCanal(item):
    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    channel_language = config.get_setting("channel_language")

    if channel_language == "":
        channel_language = "all"

    list_controls = []
    for infile in sorted(glob.glob(channels_path)):
        channel_name = os.path.basename(infile)[:-4]
        channel_parameters = channeltools.get_channel_parameters(channel_name)

        # No incluir si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # No incluir si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "0":
            continue

        # No incluir si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        # No incluir si en la configuracion del canal no existe "include_in_global_search"
        include = channel_parameters["include_in_global_search"]
        if include not in ["", "true"]:
            continue
        else:
            # Se busca en la configuración del canal el valor guardado
            include_in_global_search = config.get_setting("include_in_global_search", channel_name)

        # Si no hay valor en la configuración del canal se coloca como True ya que así estaba por defecto
        if include_in_global_search == "":
            include_in_global_search = True

        control = {'id': channel_name,
                   'type': "bool",
                   'label': channel_parameters["title"],
                   'default': include_in_global_search,
                   'enabled': True,
                   'visible': True}

        list_controls.append(control)

    return platformtools.show_channel_settings(list_controls=list_controls,
                                               caption="Canales incluidos en la búsqueda global",
                                               callback="save_settings", item=item, custom_button={'visible': False})
示例#6
0
def get_list_canales():
    logger.info()

    list_canales = {
        'peliculas': [],
        'infantiles': [],
        'series': [],
        'anime': [],
        'documentales': []
    }

    # Rellenar listas de canales disponibles
    channels_path = os.path.join(config.get_runtime_path(), "channels",
                                 '*.xml')
    channel_language = config.get_setting("channel_language")

    if channel_language == "":
        channel_language = "all"

    for infile in sorted(glob.glob(channels_path)):
        list_result_canal = []
        channel_id = os.path.basename(infile)[:-4]
        channel_parameters = channeltools.get_channel_parameters(channel_id)

        # No incluir si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # No incluir si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting(
                "adult_mode") == "false":
            continue

        # No incluir si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters[
                "language"] != channel_language:
            continue

        # Incluir en cada categoria, si en su configuracion el canal esta activado para mostrar novedades
        for categoria in list_canales:
            include_in_newest = config.get_setting(
                "include_in_newest_" + categoria, channel_id)
            if include_in_newest:
                channels_ID_name[channel_id] = channel_parameters["title"]
                list_canales[categoria].append(
                    (channel_id, channel_parameters["title"]))

    return list_canales
示例#7
0
 def makeItem(self, item):
     logger.debug()
     thumb = item.thumbnail if item.thumbnail else 'Infoplus/' + item.contentType.replace('show','') + 'png'
     logger.info('THUMB', thumb)
     it = xbmcgui.ListItem(item.title)
     it.setProperty('thumb', thumb)
     it.setProperty('fanart', item.fanart)
     it.setProperty('plot', item.plot)
     it.setProperty('verified', item.verified)
     if item.server:
         color = scrapertools.find_single_match(item.alive, r'(FF[^\]]+)')
         it.setProperty('channel', channeltools.get_channel_parameters(item.channel).get('title',''))
         it.setProperty('thumb', "https://raw.githubusercontent.com/kodiondemand/media/master/resources/servers/%s.png" % item.server.lower())
         it.setProperty('servername', servertools.get_server_parameters(item.server.lower()).get('name',item.server))
         it.setProperty('color', color if color else 'FF0082C2')
     return it
示例#8
0
文件: news.py 项目: vguardiola/addon
def get_channels_list():
    logger.info()

    list_canales = {
        'peliculas': [],
        'terror': [],
        'infantiles': [],
        'series': [],
        'anime': [],
        'documentales': []
    }
    any_active = False
    # Rellenar listas de canales disponibles
    channels_path = os.path.join(config.get_runtime_path(), "channels",
                                 '*.json')
    channel_language = config.get_setting("channel_language", default="all")

    for infile in sorted(glob.glob(channels_path)):
        channel_id = os.path.basename(infile)[:-5]
        channel_parameters = channeltools.get_channel_parameters(channel_id)

        # No incluir si es un canal inactivo
        if not channel_parameters["active"]:
            continue

        # No incluir si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] and config.get_setting(
                "adult_mode") == 0:
            continue

        # No incluir si el canal es en un idioma filtrado
        if channel_language != "all" and channel_language not in channel_parameters["language"] \
                and "*" not in channel_parameters["language"]:
            continue

        # Incluir en cada categoria, si en su configuracion el canal esta activado para mostrar novedades

        for categoria in list_canales:
            include_in_newest = config.get_setting(
                "include_in_newest_" + categoria, channel_id)
            if include_in_newest:
                channels_id_name[channel_id] = channel_parameters["title"]
                list_canales[categoria].append(
                    (channel_id, channel_parameters["title"]))
                any_active = True

    return list_canales, any_active
示例#9
0
def settingCanal(item):
    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    channel_language = config.get_setting("channel_language")

    if channel_language == "":
        channel_language = "all"
    
    list_controls = []
    for infile in sorted(glob.glob(channels_path)):
        channel_name = os.path.basename(infile)[:-4]
        channel_parameters = channeltools.get_channel_parameters(channel_name)
        
        # No incluir si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue
        
        # No incluir si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue

        # No incluir si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue
        
        # No incluir si en la configuracion del canal no existe "include_in_global_search"
        include = channel_parameters["include_in_global_search"]
        if include not in ["", "true"]:
            continue
        else:
            # Se busca en la configuración del canal el valor guardado
            include_in_global_search = config.get_setting("include_in_global_search",channel_name)

        # Si no hay valor en la configuración del canal se coloca como True ya que así estaba por defecto
        if include_in_global_search == "":
            include_in_global_search = True

        
        control = {'id': channel_name,
                      'type': "bool",                    
                      'label': channel_parameters["title"],
                      'default': include_in_global_search,
                      'enabled': True,
                      'visible': True}

        list_controls.append(control)
                
    return platformtools.show_channel_settings(list_controls=list_controls, caption= "Canales incluidos en la búsqueda global", callback="save_settings", item=item)
示例#10
0
def alpha_list(item):
    logger.info()
    itemlist = []
    soup = create_soup(item.url)
    matches = soup.find("tbody")
    if not matches:
        return itemlist
    for elem in matches.find_all("tr"):
        info = elem.find("td", class_="MvTbTtl")
        thumb = elem.img["data-src"]
        # thumb = elem.img["src"]
        url = info.a["href"]
        title = info.a.text.strip()
        year = elem.find_all('td')[4].text
        itemlist.append(
            item.clone(action="findvideos",
                       url=url,
                       title=title,
                       contentTitle=title,
                       thumbnail=thumb,
                       infoLabels={"year": year}))

    tmdb.set_infoLabels_itemlist(itemlist, True)

    if not config.get_setting(
            'unify') and not channeltools.get_channel_parameters(
                __channel__)['force_unify']:
        a = len(itemlist) - 1
        for i in itemlist:
            if a >= 0:
                title = itemlist[a].contentTitle
                titulo = itemlist[a].title
                titulo = scrapertools.find_single_match(
                    titulo, '(\\[COLOR[^"]+)')
                title = "%s %s" % (title, titulo)
                itemlist[a].title = title
                a -= 1
    next_page = soup.find('a', class_='current')
    if next_page and next_page.find_next_sibling("a"):
        next_page = next_page.find_next_sibling("a")['href']
        next_page = urlparse.urljoin(item.url, next_page)
        itemlist.append(
            item.clone(action="alpha_list",
                       title="[COLOR blue]Página Siguiente >>[/COLOR]",
                       url=next_page))
    return itemlist
示例#11
0
def findvideos(item):
    logger.info()

    db = trackingtools.TrackingData()

    opciones = []; opciones_row = []
    if item.contentType == 'movie':
        rows = db.get_movie_channels(item.infoLabels['tmdb_id'])
        infolabels = db.get_movie(item.infoLabels['tmdb_id'])
    else:
        rows = db.get_episode_channels(item.infoLabels['tmdb_id'], item.infoLabels['season'], item.infoLabels['episode'])
        infolabels = db.get_episode(item.infoLabels['tmdb_id'], item.infoLabels['season'], item.infoLabels['episode'])

    from core import channeltools
    for channel, url in rows:
        ch_parms = channeltools.get_channel_parameters(channel)
        if ch_parms['active']: # no tener en cuenta canales que ya no existan o estén desactivados
            opciones.append(platformtools.listitem_to_select(ch_parms['name'], '', ch_parms['thumbnail']))
            opciones_row.append([channel, url])

    db.close()

    if len(opciones) == 0:
        platformtools.dialog_ok(config.__addon_name, 'No tienes guardado ningún canal en activo con enlaces.')
        return None

    elif len(opciones) == 1: # Sólo hay un canal, ir a él directamente
        ret = 0
        
    else:
        # TODO? canal preferente preseleccionado u ordenar por updated o último usado ?
        ret = platformtools.dialog_select('¿ De qué canal quieres los enlaces ?', opciones, useDetails=True)
        if ret == -1: 
            return None # pedido cancel

    it_sel = Item().fromurl(opciones_row[ret][1])
    it_sel.infoLabels = infolabels # Añadir infoLabels pq las urls se guardan sin ellos
    logger.debug(it_sel)
    
    canal = __import__('channels.' + opciones_row[ret][0], fromlist=[''])
    if hasattr(canal, 'findvideos'):
        itemlist = canal.findvideos(it_sel)
    else:
        itemlist = servertools.find_video_items(it_sel)

    return itemlist
示例#12
0
文件: news.py 项目: whiplash78/addon
def get_channels_list():
    logger.debug()
    ##    import web_pdb; web_pdb.set_trace()
    ##    list_canales = {'peliculas': [], '4k': [], 'terror': [], 'infantiles': [], 'series': [], 'anime': [],
    ##                    'castellano': [], 'latino':[], 'italiano':[], 'torrent':[], 'documentales': []}
    list_canales = {
        'peliculas': [],
        'series': [],
        'anime': [],
        'documentales': []
    }

    any_active = False
    # Fill available channel lists
    channels_path = os.path.join(config.get_runtime_path(), "channels",
                                 '*.json')
    channel_language = config.get_setting("channel_language", default="all")
    if channel_language == "auto":
        channel_language = auto_filter()

    for infile in sorted(glob.glob(channels_path)):
        channel_id = os.path.basename(infile)[:-5]
        channel_parameters = channeltools.get_channel_parameters(channel_id)

        # Do not include if it is an inactive channel
        if not channel_parameters["active"]:
            continue

        # Do not include if the channel is in a filtered language
        if channel_language != "all" and channel_language not in str(channel_parameters["language"]) \
                and "*" not in channel_parameters["language"]:
            continue

        # Include in each category, if in your configuration the channel is activated to show news

        for categoria in list_canales:
            include_in_newest = config.get_setting(
                "include_in_newest_" + categoria, channel_id)
            if include_in_newest:
                channels_id_name[channel_id] = channel_parameters["title"]
                list_canales[categoria].append(
                    (channel_id, channel_parameters["title"]))
                any_active = True

    return list_canales, any_active
示例#13
0
文件: news.py 项目: roliverosc/addon
def get_channels(category, all=False):
    logger.info()

    valid_channels = list()

    all_channels = channelselector.filterchannels('all')

    for ch in all_channels:
        channel = ch.channel
        ch_param = channeltools.get_channel_parameters(channel)

        if not ch_param.get("active", False):
            continue
        valid = config.get_setting("include_in_newest_" + category, channel)
        if valid or (valid is not None and all):
            valid_channels.append(channel)

    return valid_channels
def search(item, texto):
    logger.info("[searchchannel.py] search texto="+texto)
    itemlist = []
    
    directory = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    files = glob.glob(directory)
    for file in files:
        file = file.replace(".xml", "")
        channel_parameters = channeltools.get_channel_parameters(file)
        if channel_parameters['active'] == "true":
            file = os.path.basename(file)
            if DEBUG: logger.info("File .xml trovato: " + file)
            texto = texto.lower().replace("+", "")
            name = channel_parameters['title'].lower().replace(" ", "")
            if texto in name:
                itemlist.append(Item(title=channel_parameters['title'], action="mainlist", channel=file, thumbnail=channel_parameters["thumbnail"], type="generic", viewmode="movie"))

    return itemlist
示例#15
0
def search(item, texto):
    logger.info("[searchchannel.py] search texto=" + texto)
    itemlist = []

    directory = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    files = glob.glob(directory)
    for file in files:
        file = file.replace(".xml", "")
        channel_parameters = channeltools.get_channel_parameters(file)
        if channel_parameters['active'] == True:
            file = os.path.basename(file)
            texto = texto.lower().replace("+", "")
            name = channel_parameters['title'].lower().replace(" ", "")
            if texto in name:
                itemlist.append(Item(title=channel_parameters['title'], action="mainlist", channel=file,
                                     thumbnail=channel_parameters["thumbnail"], type="generic", viewmode="movie"))

    return itemlist
示例#16
0
def findvideos(item):
    video_urls = []
    headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14',
           'content-type': 'application/json;charset=UTF-8',
           'Referer': 'https://streamingcommunity.net'}
    data = support.match(item, headers=headers).data.replace('"','"').replace('\\','')
    url = support.match(data, patron=r'video_url"\s*:\s*"([^"]+)"').match
    def videourls(res):
        newurl = '{}/{}'.format(url, res)
        if requests.head(newurl, headers=headers).status_code == 200:
            video_urls.append(["m3u8 {} [StreamingCommunity]".format(res), newurl])

    with futures.ThreadPoolExecutor() as executor:
        for res in ['480p', '720p', '1080p']:
            executor.submit(videourls, res) 
    if not video_urls: video_urls = [["m3u8 [StreamingCommunity]", url]]
    else: video_urls.sort(key=lambda url: int(support.match(url[0], patron=r'(\d+)p').match))
    itemlist = [item.clone(title = channeltools.get_channel_parameters(item.channel)['title'], server='directo', video_urls=video_urls, thumbnail=channeltools.get_channel_parameters(item.channel)["thumbnail"], forcethumb=True)]
    return support.server(item, itemlist=itemlist)
示例#17
0
def mainlist(item):
    logger.info()

    itemlist = list()

    if alfa_assistant.is_alfa_installed():

        autoplay.init(item.channel, list_servers, list_quality)

        itemlist.append(Item(channel=item.channel, action="novedades_episodios", title="Últimos episodios",
                             url=HOST+'anime-online.html', thumbnail="https://i.imgur.com/w941jbR.png"))

        itemlist.append(Item(channel=item.channel, action="novedades_anime", title="Últimos animes",
                             url=HOST+'anime-online.html', thumbnail="https://i.imgur.com/hMu5RR7.png"))

        itemlist.append(Item(channel=item.channel, action="listado", title="Animes",
                             url=HOST + "animes/nombre/lista", thumbnail='https://i.imgur.com/50lMcjW.png'))

        itemlist.append(Item(channel=item.channel, action="search_section",
                             title="Géneros", url=HOST + "animes",
                             extra="genre", thumbnail='https://i.imgur.com/Xj49Wa7.png'))

        itemlist.append(Item(channel=item.channel, action="search", title="Buscar...",
                             thumbnail='https://i.imgur.com/4jH5gpT.png'))


        itemlist = renumbertools.show_option(item.channel, itemlist)

        autoplay.show_option(item.channel, itemlist)
    else:
        from lib import generictools
        browser, res = generictools.call_browser('', lookup=True)
        if not browser:
            action = ''
        else:
            action = 'call_browser'
        from channelselector import get_thumb
        from core import channeltools
        channel_name = channeltools.get_channel_parameters(item.channel)["title"]
        itemlist.append(Item(channel=item.channel, action=action, title="Para utilizar {} se requiere Alfa Assistant. [COLOR=yellow]Haz clic para + info[/COLOR] [COLOR=green](https://alfa-addon.com/threads/manual-de-alfa-assistant-herramienta-de-apoyo.3797/)[/COLOR]".format(channel_name),
                             thumbnail=get_thumb("update.png"), url="https://alfa-addon.com/threads/manual-de-alfa-assistant-herramienta-de-apoyo.3797/"))

    return itemlist
示例#18
0
def filterchannels(category,preferred_thumb=""):
    logger.info("channelselector.filterchannels")

    channelslist =[]

    # Lee la lista de canales
    channel_path = os.path.join( config.get_runtime_path() , "channels" , '*.xml' )
    logger.info("channelselector.filterchannels channel_path="+channel_path)

    channel_files = glob.glob(channel_path)
    logger.info("channelselector.filterchannels channel_files encontrados "+str(len(channel_files)))

    for index, channel in enumerate(channel_files):
        logger.info("channelselector.filterchannels channel="+channel)
        if channel.endswith(".xml"):
            try:
                channel_parameters = channeltools.get_channel_parameters(channel[:-4])
                logger.info("channelselector.filterchannels channel_parameters="+repr(channel_parameters))

                # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea
                if preferred_thumb=="bannermenu" and "bannermenu" in channel_parameters:
                    channel_parameters["thumbnail"] = channel_parameters["bannermenu"]

                # Se salta el canal si no está activo
                if not channel_parameters["active"] == "true":
                    continue

                import xbmc
                if xbmc.Player().isPlayingAudio():
                    xbmc.executebuiltin('xbmc.PlayMedia(Stop)')

                # Si ha llegado hasta aquí, lo añade
                channelslist.append(Item(title=channel_parameters["title"], channel=channel_parameters["channel"], action="mainlist", thumbnail=channel_parameters["thumbnail"] , fanart=channel_parameters["fanart"], category=", ".join(channel_parameters["categories"])[:-2], language=channel_parameters["language"], viewmode="list" ))
            
            except:
                logger.info("Se ha producido un error al leer los datos del canal " + channel)
                import traceback
                logger.info(traceback.format_exc())
           
    channelslist.sort(key=lambda item: item.title.lower().strip())

    return channelslist
示例#19
0
def get_channel_results(ch, item):
    max_results = 10
    results = list()

    ch_params = channeltools.get_channel_parameters(ch)

    try:

        module = __import__('channels.%s' % ch_params["channel"],
                            fromlist=["channels.%s" % ch_params["channel"]])
        mainlist = getattr(module,
                           'mainlist')(Item(channel=ch_params["channel"]))

        search_action = [elem for elem in mainlist if elem.action == "search"]

        if search_action:
            for search_ in search_action:
                try:
                    results.extend(module.search(search_, item.text))
                except:
                    pass
        else:
            try:
                results.extend(module.search(item, item.text))
            except:
                pass

        if len(results) < 0 and len(
                results) < max_results and item.mode != 'all':

            if len(results) == 1:
                if not results[0].action or config.get_localized_string(
                        30992).lower() in results[0].title.lower():
                    return [ch, []]

            results = get_info(results)

        return [ch, results]
    except Exception:
        import traceback
        logger.error(traceback.format_exc())
        return [ch, []]
示例#20
0
def settingCanal(item):
    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    channel_language = config.get_setting("channel_language")

    if channel_language == "":
        channel_language = "all"

    list_controls = []
    for infile in sorted(glob.glob(channels_path)):
        channel_id = os.path.basename(infile)[:-4]
        channel_parameters = channeltools.get_channel_parameters(channel_id)

        # No incluir si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # No incluir si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue

        # No incluir si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        # No incluir si en su configuracion el canal no existe 'include_in_newest'
        include_in_newest = config.get_setting("include_in_newest_" + item.extra, channel_id)
        if include_in_newest == "":
            continue

        control = {'id': channel_id,
                      'type': "bool",
                      'label': channel_parameters["title"],
                      'default': include_in_newest,
                      'enabled': True,
                      'visible': True}

        list_controls.append(control)

    caption = "Canales incluidos en Novedades " + item.title.replace("Canales incluidos en: ","- ").strip()
    return platformtools.show_channel_settings(list_controls=list_controls, callback="save_settings", item=item,
                                               caption= caption,custom_button={"visible":False})
示例#21
0
def setting_channel(item):
    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    channel_language = config.get_setting("channel_language")

    if channel_language == "":
        channel_language = "all"

    list_controls = []
    for infile in sorted(glob.glob(channels_path)):
        channel_id = os.path.basename(infile)[:-4]
        channel_parameters = channeltools.get_channel_parameters(channel_id)

        # No incluir si es un canal inactivo
        if not channel_parameters["active"]:
            continue

        # No incluir si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] and config.get_setting("adult_mode") == 0:
            continue

        # No incluir si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        # No incluir si en su configuracion el canal no existe 'include_in_newest'
        include_in_newest = config.get_setting("include_in_newest_" + item.extra, channel_id)
        if include_in_newest is None:
            continue

        control = {'id': channel_id,
                   'type': "bool",
                   'label': channel_parameters["title"],
                   'default': include_in_newest,
                   'enabled': True,
                   'visible': True}

        list_controls.append(control)

    caption = "Canales incluidos en Novedades " + item.title.replace("Canales incluidos en: ", "- ").strip()
    return platformtools.show_channel_settings(list_controls=list_controls, callback="save_settings", item=item,
                                               caption=caption, custom_button={"visible": False})
示例#22
0
def get_channels(item):
    logger.info()

    channels_list = list()
    title_list = list()
    all_channels = channelselector.filterchannels('all')

    for ch in all_channels:
        channel = ch.channel
        ch_param = channeltools.get_channel_parameters(channel)

        if not ch_param.get("active", False):
            continue

        if ch_param.get("login_required", False):
            ch_user = config.get_setting("user", channel)
            ch_pass = config.get_setting("pass", channel)

            if not ch_user or not ch_pass:

                ch_user = config.get_setting("hdfulluser", channel)
                ch_pass = config.get_setting("hdfullpassword", channel)

                if not ch_user or not ch_pass:
                    continue

        list_cat = ch_param.get("categories", [])

        if not ch_param.get("include_in_global_search", False):
            continue

        if 'anime' in list_cat:
            n = list_cat.index('anime')
            list_cat[n] = 'tvshow'

        if item.mode == 'all' or (item.mode in list_cat):
            if config.get_setting("include_in_global_search", channel):
                channels_list.append(channel)
                title_list.append(ch_param.get('title', channel))

    return channels_list, title_list
def settingCanal(item):
    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    channel_language = config.get_setting("channel_language")

    if channel_language == "":
        channel_language = "all"

    list_controls = []
    for infile in sorted(glob.glob(channels_path)):
        channel_name = os.path.basename(infile)[:-4]
        channel_parameters = channeltools.get_channel_parameters(channel_name)

        # No incluir si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # No incluir si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue

        # No incluir si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        # No incluir si en la configuracion del canal no existe "include_in_global_search"
        include_in_global_search = config.get_setting("include_in_global_search", channel_name)
        if include_in_global_search == "":
            continue

        control = {'id': channel_name,
                   'type': "bool",
                   'label': channel_parameters["title"],
                   'default': include_in_global_search,
                   'enabled': True,
                   'visible': True}

        list_controls.append(control)

    return platformtools.show_channel_settings(list_controls=list_controls,
                                               caption="Canali inclusi nella ricerca globale",
                                               callback="save_settings", item=item)
示例#24
0
def add_extra_info(item, checks):
    #logger.info()

    if item.from_channel and item.channel not in ["news"]:
        from core import channeltools
        channel_parameters = channeltools.get_channel_parameters(
            item.from_channel)
        item.title = '%s [%s]' % (item.title, channel_parameters['title'])

    if checks:
        if "group" in checks:
            check = "+"
            color_check = "yellow"
        elif "visto" in checks:
            check = u'\u221a'
            color_check = "limegreen"

        item.title = "[COLOR %s][B][%s][/B][/COLOR] %s" % (color_check, check,
                                                           item.title)

    return item
示例#25
0
def menu_channels(item):
    logger.info()
    itemlist = list()

    itemlist.append(Item(channel=CHANNELNAME, title="Activar/desactivar canales",
                         action="conf_tools", folder=False, extra="channels_onoff",
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))

    itemlist.append(Item(channel=CHANNELNAME, title="Ajustes por canales",
                         action="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))

    # Inicio - Canales configurables
    import channelselector
    from core import channeltools

    channel_list = channelselector.filterchannels("all")

    for channel in channel_list:
        channel_parameters = channeltools.get_channel_parameters(channel.channel)

        if channel_parameters["has_settings"]:
            itemlist.append(Item(channel=CHANNELNAME, title="   Configuración del canal '%s'" % channel.title,
                                 action="channel_config", config=channel.channel, folder=False,
                                 thumbnail=channel.thumbnail))
    # Fin - Canales configurables

    itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))

    itemlist.append(Item(channel=CHANNELNAME, title="Herramientas de canales", action="",
                         folder=False, thumbnail=get_thumbnail_path("thumb_canales.png")))
    itemlist.append(Item(channel=CHANNELNAME, title="   Comprobar archivos *_data.json",
                         action="conf_tools", folder=True, extra="lib_check_datajson",
                         thumbnail=get_thumbnail_path("thumb_canales.png")))

    

    return itemlist
示例#26
0
def findvideos(item):
    logger.info()
    itemlist = []

    if alfa_assistant.is_alfa_installed():

        data = httptools.downloadpage(item.url).data
        bloque = scrapertools.find_single_match(data, 'Server</span>(.*?)id="choose_quality"')
        matches = scrapertools.find_multiple_matches(bloque, '<option sv="[^"]+" value="([^"]+)"')
        headers = {"Referer" : item.url}

        for url in matches:
            xserver = scrapertools.find_single_match(url, 's=([a-zA-Z0-9]+)')
            source = HOST + "get_video_info_v2?s=%s" % xserver
            link = get_link(source, url)
            if link:
                itemlist.append(Item(channel=item.channel, action="play", url=link, 
                                title=xserver.capitalize(),plot=item.plot, thumbnail=item.thumbnail,
                                contentTitle=item.title, language='VOSE', server="directo"))
        #~itemlist = servertools.get_servers_itemlist(itemlist, lambda x: x.title % x.server.capitalize())

        # Requerido para AutoPlay
        autoplay.start(itemlist, item)
    else:
        from lib import generictools
        browser, res = generictools.call_browser('', lookup=True)
        if not browser:
            action = ''
        else:
            action = 'call_browser'
        from channelselector import get_thumb
        from core import channeltools
        channel_name = channeltools.get_channel_parameters(item.channel)["title"]
        itemlist.append(Item(channel=item.channel, action=action, title="Para utilizar {} se requiere Alfa Assistant. [COLOR=yellow]Haz clic para + info[/COLOR] [COLOR=green](https://alfa-addon.com/threads/manual-de-alfa-assistant-herramienta-de-apoyo.3797/)[/COLOR]".format(channel_name),
                             thumbnail=get_thumb("update.png"), url="https://alfa-addon.com/threads/manual-de-alfa-assistant-herramienta-de-apoyo.3797/"))

    return itemlist
示例#27
0
def findvideos(item):
    logger.info()
    itemlist = []
    soup = create_soup(item.url)
    matches = soup.find_all('li', class_='OptionBx')
    serv=[]
    for elem in matches:
        num= elem['data-key']
        id= elem['data-id']
        lang= elem.find('p', class_='AAIco-language').text.split()
        server =  elem.find('p', class_='AAIco-dns').text.strip()
        # quality = elem.find('p', class_='AAIco-equalizer').text.split()
        # quality = quality[-1]
        lang = lang[-1]
        lang = IDIOMAS.get(lang, lang)
        server = SERVER.get(server, server)
        url = "%s//?trembed=%s&trid=%s&trtype=1"  %  (host,num,id)
        if not config.get_setting('unify') and not channeltools.get_channel_parameters(__channel__)['force_unify']:
            title = "[%s] [COLOR darkgrey][%s][/COLOR]" %(server,lang)
        else:
            title = server
        if not "gounlimited" in server:
            itemlist.append(item.clone(action="play", title=title, url=url, server=server, language=lang ))

    itemlist.sort(key=lambda it: (it.language))

    # Requerido para FilterTools
    itemlist = filtertools.get_links(itemlist, item, list_language)
    # Requerido para AutoPlay
    autoplay.start(itemlist, item)

    if config.get_videolibrary_support() and len(itemlist) > 0 and item.extra !='findvideos' and not "/episodios/" in item.url :
        itemlist.append(item.clone(action="add_pelicula_to_library", 
                             title='[COLOR yellow]Añadir esta pelicula a la videoteca[/COLOR]', url=item.url,
                             extra="findvideos", contentTitle=item.contentTitle)) 
    return itemlist
示例#28
0
def lista(item):
    logger.info()
    itemlist = []
    soup = create_soup(item.url, referer=host)
    matches = soup.find_all("div", class_='card')
    for elem in matches:
        url = elem.a['href']
        thumbnail = elem.img['src']
        title = elem.find('div', class_='card-title').text.replace("en Castellano", "").strip()
        title = title.split()
        year = title[-2]
        title = " ".join(title[1:-2])
        lang = "esp"
        language = []
        language.append(IDIOMAS.get(lang, lang))
        contentTitle = title
        if year == '':
            year = '-'
            
        if not config.get_setting('unify') and not channeltools.get_channel_parameters(__channel__)['force_unify']:
            if year != "-":
                title = "%s [COLOR cyan](%s)[/COLOR] [COLOR darkgrey]%s[/COLOR]" % (title,year, language)
            else:
                title = "%s [COLOR darkgrey]%s[/COLOR]" % (title, language)
        else:
            title = title
        itemlist.append(Item(channel=item.channel, action = "findvideos", url=url, title=title, contentTitle = contentTitle,
                        thumbnail=thumbnail, language=language, infoLabels={"year": year}) )
    tmdb.set_infoLabels(itemlist, True)

    next_page = soup.find('span', class_='is-inactive')
    if next_page and next_page.find_next_sibling("a"):
        next_page = next_page.find_next_sibling("a")['href']
        next_page = urlparse.urljoin(item.url,next_page)
        itemlist.append(item.clone(action="lista", title="[COLOR blue]Página Siguiente >>[/COLOR]", url=next_page) )
    return itemlist
示例#29
0
def lista(item):
    logger.info()
    itemlist = []
    if item.post:
        soup = get_source(api, soup=True, post=item.post)
        numitem = 0
    else:
        soup = get_source(item.url, soup=True)
    matches= soup.find_all('article')
    for elem in matches:
        if item.post:
            numitem += 1
        url = elem.a['href']
        thumbnail = elem.img['src']
        title = elem.h2.text.strip()
        contentTitle = title
        year = '-'
        if not config.get_setting('unify') and not channeltools.get_channel_parameters(__channel__)['force_unify']:
            if year != "-":
                title = "%s [COLOR cyan](%s)[/COLOR]" % (title,year)
        else:
            title = title
        itemlist.append( Item(channel=item.channel, action = "findvideos", url = url, title=title, contentTitle = contentTitle,
                        thumbnail=thumbnail, infoLabels={"year": year}))
    tmdb.set_infoLabels(itemlist, True)
    next_page = soup.find('a', class_='nextpostslink')
    if next_page:
        next_page = next_page['href']
        next_page = urlparse.urljoin(item.url,next_page)
        itemlist.append(item.clone(action="lista", title="[COLOR blue]Página Siguiente >>[/COLOR]", url=next_page) )
    elif item.post and numitem == 18:
        next_page = scrapertools.find_single_match(item.post, "&paged=(\d+)")
        next_page = int(next_page) + 1
        next_page = re.sub(r"&paged=\d+", "&paged={0}".format(next_page), item.post)
        itemlist.append(item.clone(action="lista", title="[COLOR blue]Página Siguiente >>[/COLOR]", post=next_page) )
    return itemlist
def mainlist(item):
    logger.info()

    itemlist = list()
    itemlist.append(Item(channel=CHANNELNAME, title="Preferenze", action="settings", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion.png")))

    itemlist.append(Item(channel=CHANNELNAME, title="", action="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion.png")))

    itemlist.append(Item(channel=CHANNELNAME, title="Impostazioni speciali", action="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion.png")))
    itemlist.append(Item(channel="novedades", title="   Impostazioni 'Novità'", action="menu_opciones",
                         folder=True, thumbnail=get_thumbnail_path("thumb_novedades.png")))
    itemlist.append(Item(channel="buscador",  title="   Impostazioni della ricerca globale", action="opciones", folder=True,
                         thumbnail=get_thumbnail_path("thumb_buscar.png")))

    if config.get_library_support():
        itemlist.append(Item(channel="biblioteca", title="   Impostazioni libreria",
                             action="channel_config", folder=True,
                             thumbnail=get_thumbnail_path("thumb_biblioteca.png")))
        itemlist.append(Item(channel="biblioteca", action="update_biblio", folder=False,
                             thumbnail=get_thumbnail_path("thumb_biblioteca.png"),
                             title="   Recupera nuovi episodi e aggiorna la libreria"))

    itemlist.append(Item(channel=CHANNELNAME, title="Avvia aggiornamenti", action="check_for_updates", folder=False))

    itemlist.append(Item(channel=item.channel, action="", title="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion.png")))

    itemlist.append(Item(channel=CHANNELNAME, title="Impostazioni canali", action="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion.png")))

    import channelselector
    from core import channeltools
    channel_list = channelselector.filterchannels("all")

    for channel in channel_list:
        try:
          jsonchannel = channeltools.get_channel_json(channel.channel)
        except:
          continue
        if jsonchannel.get("settings"):
            setting = jsonchannel["settings"]
            if type(setting) == list:
                if len([s for s in setting if "id" in s and "include_in_" not in s["id"]]):
                    active_status = None
                    if config.get_setting("enabled", channel.channel):
                        active_status = config.get_setting("enabled", channel.channel)
                    else:
                        channel_parameters = channeltools.get_channel_parameters(channel.channel)
                        active_status = channel_parameters['active']

                    if active_status == "true":
                        itemlist.append(Item(channel=CHANNELNAME,
                                             title="   Configurazione canale '%s'" % channel.title,
                                             action="channel_config", config=channel.channel,
                                             folder=False,
                                             thumbnail=channel.thumbnail))

    return itemlist
示例#31
0
def do_search(item, categories=[]):
    multithread = config.get_setting("multithread","buscador")
    result_mode = config.get_setting("result_mode","buscador")
    logger.info("pelisalacarta.channels.buscador do_search")

    tecleado = item.extra

    itemlist = []

    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    logger.info("pelisalacarta.channels.buscador channels_path="+channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info("pelisalacarta.channels.buscador channel_language="+channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info("pelisalacarta.channels.buscador channel_language="+channel_language)

    #Para Kodi es necesario esperar antes de cargar el progreso, de lo contrario
    #el cuadro de progreso queda "detras" del cuadro "cargando..." y no se le puede dar a cancelar
    time.sleep(0.5)
    progreso = platformtools.dialog_progress("Buscando " + tecleado,"")
    channel_files = glob.glob(channels_path)
    number_of_channels = len(channel_files)
    
    searches = []
    search_results = {}
    start_time = time.time()
    
    if multithread:
      progreso.update(0, "Buscando %s..." % (tecleado))
      
    for index, infile in enumerate(channel_files):
        percentage = index*100/number_of_channels

        basename = os.path.basename(infile)
        basename_without_extension = basename[:-4]

        channel_parameters = channeltools.get_channel_parameters(basename_without_extension)

        # No busca si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue
        
        # En caso de busqueda por categorias
        if categories:
            if not any(cat in channel_parameters["categories"] for cat in categories):
                continue
                
        # No busca si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue

        # No busca si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue
        
        # No busca si es un canal excluido de la busqueda global
        include_in_global_search = channel_parameters["include_in_global_search"]
        if include_in_global_search == "":
            #Buscar en la configuracion del canal
            include_in_global_search = str(config.get_setting("include_in_global_search",basename_without_extension))
        if include_in_global_search.lower() != "true":
            continue
            
        if progreso.iscanceled(): break
        
        #Modo Multi Thread            
        if multithread:
          t = Thread(target=channel_search,args=[search_results, channel_parameters, tecleado])
          t.setDaemon(True) 
          t.start()
          searches.append(t)
        
        #Modo single Thread
        else:
          logger.info("pelisalacarta.channels.buscador Intentado busqueda en " + basename_without_extension + " de " + tecleado)

          progreso.update(percentage, "Buscando %s en %s..." % (tecleado, channel_parameters["title"]))
          channel_search(search_results, channel_parameters, tecleado)
    

    #Modo Multi Thread
    if multithread :
      pendent =  len([a for a in searches if a.is_alive()])
      while pendent:
        pendent =  len([a for a in searches if a.is_alive()])
        percentage =  (len(searches) - pendent) * 100 / len(searches)
        progreso.update(percentage, "Buscando %s en %d canales..." % (tecleado, len(searches)))
        if progreso.iscanceled(): break
        time.sleep(0.5)
          
    total = 0 
    
    for channel in sorted(search_results.keys()):
      for search in search_results[channel]:
        total+= len(search["itemlist"])
        if result_mode ==0:
            title = channel
            if len(search_results[channel]) > 1:
              title += " [" + search["item"].title.strip() + "]"
            title +=" (" + str(len(search["itemlist"])) + ")"
            
            title = re.sub("\[COLOR [^\]]+\]","",title)
            title = re.sub("\[/COLOR]","",title)
            
            extra = search["item"].extra + "{}" + search["item"].channel + "{}" + tecleado
            itemlist.append(Item(title=title, channel="buscador",action="channel_result", url=search["item"].url, extra = extra, folder=True))
        else:
          itemlist.extend(search["itemlist"])
  
  
  
    title="Buscando: '%s' | Encontrado: %d vídeos | Tiempo: %2.f segundos" % (tecleado,total, time.time()-start_time)
    itemlist.insert(0,Item(title=title, color='yellow'))

    progreso.close()

    return itemlist
示例#32
0
from core.item import Item


# Configuracion del canal
__modo_grafico__ = config.get_setting('modo_grafico', "oranline")
__perfil__ = int(config.get_setting('perfil', "oranline"))

# Fijar perfil de color            
perfil = [['0xFFFFE6CC', '0xFFFFCE9C', '0xFF994D00'],
          ['0xFFA5F6AF', '0xFF5FDA6D', '0xFF11811E'],
          ['0xFF58D3F7', '0xFF2E9AFE', '0xFF2E64FE']]
color1, color2, color3 = perfil[__perfil__]

DEBUG = config.get_setting("debug")
host = "http://www.oranline.com/"
parameters = channeltools.get_channel_parameters("oranline")
viewmode_options = {0: 'movie_with_plot', 1: 'movie', 2: 'list'}
viewmode = viewmode_options[config.get_setting('viewmode', "oranline")]


def mainlist(item):
    logger.info("pelisalacarta.channels.oranline mainlist")
    itemlist = []
    item.viewmode = viewmode

    itemlist.append(item.clone(title="Películas", text_color=color2, action="",
                               text_blod=True))
    itemlist.append(item.clone(action="peliculas", title="      Novedades", text_color=color1,
                               url=urlparse.urljoin(host, "ultimas-peliculas-online/"),
                               thumbnail="https://raw.githubusercontent.com/master-1970/resources/master/images/genres/"
                                         "0/Directors%20Chair.png"))
示例#33
0
def config_item(item):
    """
    displays a filtered series for your setup

    @param item: item
    @type item: Item
    """
    logger.info()
    logger.info("item %s" % item.tostring())

    # WE GET THE JSON DATA
    dict_series = jsontools.get_node_from_file(item.from_channel, TAG_TVSHOW_FILTER)

    tvshow = item.show.lower().strip()
    default_lang = ''

    channel_parameters = channeltools.get_channel_parameters(item.from_channel)
    list_language = channel_parameters["filter_languages"]
    try:
        if channel_parameters["filter_languages"] != '' and len(list_language) > 0:
            default_lang = list_language[1]
    except:
        pass

    if default_lang == '':
        platformtools.dialog_notification("FilterTools", "There are no defined languages")
        return
    else:
        lang_selected = dict_series.get(tvshow, {}).get(TAG_LANGUAGE, default_lang)
        list_quality = dict_series.get(tvshow, {}).get(TAG_QUALITY_ALLOWED, [x.lower() for x in item.list_quality])
        # logger.info("lang selected {}".format(lang_selected))
        # logger.info("list quality {}".format(list_quality))

        active = True
        custom_button = {'visible': False}
        allow_option = False
        if item.show.lower().strip() in dict_series:
            allow_option = True
            active = dict_series.get(item.show.lower().strip(), {}).get(TAG_ACTIVE, False)
            custom_button = {'label': config.get_localized_string(60437), 'function': 'delete', 'visible': True, 'close': True}

        list_controls = []

        if allow_option:
            active_control = {
                "id": "active",
                "type": "bool",
                "label": config.get_localized_string(60438),
                "color": "",
                "default": active,
                "enabled": allow_option,
                "visible": allow_option,
            }
            list_controls.append(active_control)

        language_option = {
            "id": "language",
            "type": "list",
            "label": config.get_localized_string(60439),
            # "color": "0xFFee66CC",
            "default": item.list_language.index(lang_selected),
            "enabled": True,
            "visible": True,
            "lvalues": item.list_language
        }
        list_controls.append(language_option)

        if item.list_quality:
            list_controls_calidad = [
                {
                    "id": "textoCalidad",
                    "type": "label",
                    "label": "Calidad permitida",
                    "color": "0xffC6C384",
                    "enabled": True,
                    "visible": True,
                },
            ]
            for element in sorted(item.list_quality, key=str.lower):
                list_controls_calidad.append({
                    "id": element,
                    "type": "bool",
                    "label": element,
                    "default": (False, True)[element.lower() in list_quality],
                    "enabled": True,
                    "visible": True,
                })

            # we concatenate list_controls with list_controls_quality
            list_controls.extend(list_controls_calidad)

        title = config.get_localized_string(60441) % (COLOR.get("selected", "auto"), item.show)

        platformtools.show_channel_settings(list_controls=list_controls, callback='save', item=item,
                                            caption=title, custom_button=custom_button)
def getchanneltypes(preferred_thumb=""):
    logger.info("channelselector getchanneltypes")

    # Lista de categorias
    valid_types = ["vos", "torrent"]
    dict_cat_lang = {'vos': config.get_localized_string(30136), 'torrent': 'Torrent'}

    # Lee la lista de canales
    channel_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    logger.info("channelselector.getchanneltypes channel_path=" + channel_path)

    channel_files = glob.glob(channel_path)

    channel_language = config.get_setting("channel_language")
    logger.info("channelselector.getchanneltypes channel_language=" + channel_language)

    # Construye la lista de tipos
    channel_types = []

    for index, channel in enumerate(channel_files):
        logger.info("channelselector.getchanneltypes channel=" + channel)
        if channel.endswith(".xml"):
            try:
                channel_parameters = channeltools.get_channel_parameters(channel[:-4])
                logger.info("channelselector.filterchannels channel_parameters=" + repr(channel_parameters))

                # Si es un canal para adultos y el modo adulto está desactivado, se lo salta
                if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
                    continue

                # Si el canal está en un idioma filtrado
                if channel_language != "all" and channel_parameters["language"] != channel_language:
                    continue

                categories = channel_parameters["categories"]
                for category in categories:
                    logger.info("channelselector.filterchannels category=" + category)
                    if category not in channel_types and category in valid_types:
                        channel_types.append(category)

            except:
                logger.info("Se ha producido un error al leer los datos del canal " + channel + traceback.format_exc())

    logger.info("channelselector.getchanneltypes Encontrados:")
    for channel_type in channel_types:
        logger.info("channelselector.getchanneltypes channel_type=" + channel_type)

    # Ahora construye el itemlist ordenadamente
    itemlist = list()

    itemlist.append(Item(title="Top Channels", channel="channelselector", action="filterchannels",
                         category="top channels", channel_type="top channels", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_topchannels.png"),
                         viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30122), channel="channelselector", action="filterchannels",
                         category="movie", channel_type="movie", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_film.png"), viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30123), channel="channelselector", action="filterchannels",
                         category="serie", channel_type="serie", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_series.png"), viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30124), channel="channelselector", action="filterchannels",
                         category="anime", channel_type="anime", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_anime.png"), viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30125), channel="channelselector", action="filterchannels",
                         category="documentary", channel_type="documentary", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_documentales.png"),
                         viewmode="movie"))
    itemlist.append(Item(title="Cult", channel="channelselector", action="filterchannels",
                         category="cult", channel_type="cult", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "main_menu_filmontv.png"),
                         viewmode="movie"))
    itemlist.append(Item(title="Saghe", channel="saghe", action="mainlist",
                         category="saghe", channel_type="saghe", thumbnail = os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_saghe.png")))
    logger.info("channelselector.getchanneltypes Ordenados:")
    for channel_type in valid_types:
        logger.info("channelselector.getchanneltypes channel_type="+channel_type)
        if channel_type in channel_types:
            title = dict_cat_lang.get(channel_type, channel_type)
            itemlist.append(Item(title=title, channel="channelselector", action="filterchannels", category=title,
                                 channel_type= channel_type, viewmode="thumbnails",
                                 thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                            "thumb_canales_"+channel_type+".png")))

    return itemlist
def filterchannels(category,preferred_thumb=""):
    logger.info("channelselector.filterchannels")

    channelslist =[]

    # Lee la lista de canales
    channel_path = os.path.join( config.get_runtime_path() , "channels" , '*.xml' )
    logger.info("channelselector.filterchannels channel_path="+channel_path)

    channel_files = glob.glob(channel_path)
    logger.info("channelselector.filterchannels channel_files encontrados "+str(len(channel_files)))

    channel_language = config.get_setting("channel_language")
    logger.info("channelselector.filterchannels channel_language="+channel_language)
    if channel_language=="":
        channel_language = "all"
        logger.info("channelselector.filterchannels channel_language="+channel_language)

    for index, channel in enumerate(channel_files):
        logger.info("channelselector.filterchannels channel="+channel)
        if channel.endswith(".xml"):

            try:
                channel_parameters = channeltools.get_channel_parameters(channel[:-4])
                logger.info("channelselector.filterchannels channel_parameters="+repr(channel_parameters))

                # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea
                if preferred_thumb=="bannermenu" and "bannermenu" in channel_parameters:
                    channel_parameters["thumbnail"] = channel_parameters["bannermenu"]

                # Se salta el canal si no está activo
                if not channel_parameters["active"] == "true":
                    continue

                # Se salta el canal para adultos si el modo adultos está desactivado
                if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") != "true": 
                    continue

                # Se salta el canal si está en un idioma filtrado
                if channel_language!="all" and channel_parameters["language"]!=config.get_setting("channel_language"):
                    continue

                # Se salta el canal si está en una categoria filtrado
                if category!="all" and category not in channel_parameters["categories"]:
                    continue
                #Salta canales de deportes en listado all
                if category == "all" and  "deportes" in channel_parameters["categories"]:
                   continue
                #Detiene la muúsica al entrar en Deportes
                if category == "deportes":
                    import xbmc
                    xbmc.executebuiltin('xbmc.PlayMedia(Stop)')
                    print "si o que?"
                # Si ha llegado hasta aquí, lo añade
                channelslist.append(Item(title=channel_parameters["title"], channel=channel_parameters["channel"], action="mainlist", thumbnail=channel_parameters["thumbnail"] , fanart=channel_parameters["fanart"], category=", ".join(channel_parameters["categories"])[:-2], language=channel_parameters["language"], type=channel_parameters["type"] ))
            
            except:
                logger.info("Se ha producido un error al leer los datos del canal " + channel)
                import traceback
                logger.info(traceback.format_exc())
           
    channelslist.sort(key=lambda item: item.title.lower().strip())

    if category=="all":
        if config.get_setting("personalchannel5")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname5") ,action="mainlist", channel="personal5" ,thumbnail=config.get_setting("personalchannellogo5") , type="generic"  ))
        if config.get_setting("personalchannel4")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname4") ,action="mainlist", channel="personal4" ,thumbnail=config.get_setting("personalchannellogo4") , type="generic"  ))
        if config.get_setting("personalchannel3")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname3") ,action="mainlist", channel="personal3" ,thumbnail=config.get_setting("personalchannellogo3") , type="generic"  ))
        if config.get_setting("personalchannel2")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname2") ,action="mainlist", channel="personal2" ,thumbnail=config.get_setting("personalchannellogo2") , type="generic"  ))
        if config.get_setting("personalchannel")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname")  ,action="mainlist", channel="personal"  ,thumbnail=config.get_setting("personalchannellogo") , type="generic"  ))

        channel_parameters = channeltools.get_channel_parameters("tengourl")
        # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea
        if preferred_thumb=="bannermenu" and "bannermenu" in channel_parameters:
            channel_parameters["thumbnail"] = channel_parameters["bannermenu"]

        channelslist.insert( 0 , Item( title="Tengo una URL"  ,action="mainlist", channel="tengourl" , thumbnail=channel_parameters["thumbnail"], type="generic"  ))

    return channelslist
示例#36
0
def do_channels_search(item):
    logger.info("streamondemand.channels.buscadorall do_channels_search")

    tecleado, category, title_year = item.extra.split('{}')

    try:
        title_year = int(title_year)
    except:
        title_year = 0

    itemlist = []

    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    logger.info("streamondemand.channels.buscador channels_path=" + channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info("streamondemand.channels.buscador channel_language=" + channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info("streamondemand.channels.buscador channel_language=" + channel_language)

    progreso = platformtools.dialog_progress_bg(NLS_Looking_For % tecleado)

    channel_files = glob.glob(channels_path)

    search_results = Queue.Queue()
    number_of_channels = 0

    for infile in channel_files:

        basename_without_extension = os.path.basename(infile)[:-4]

        channel_parameters = channeltools.get_channel_parameters(basename_without_extension)

        # No busca si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # En caso de busqueda por categorias
        if category and category not in channel_parameters["categories"]:
            continue

        # No busca si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue

        # No busca si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        # No busca si es un canal excluido de la busqueda global
        include_in_global_search = channel_parameters["include_in_global_search"]
        if include_in_global_search == "":
            # Buscar en la configuracion del canal
            include_in_global_search = str(config.get_setting("include_in_global_search", basename_without_extension))
        if include_in_global_search.lower() != "true":
            continue

        t = Thread(target=channel_search, args=[search_results, channel_parameters, category, title_year, tecleado])
        t.setDaemon(True)
        t.start()
        number_of_channels += 1

    start_time = int(time.time())

    completed_channels = 0
    while completed_channels < number_of_channels:

        delta_time = int(time.time()) - start_time
        if len(itemlist) <= 0:
            timeout = None  # No result so far,lets the thread to continue working until a result is returned
        elif delta_time >= TIMEOUT_TOTAL:
            break  # At least a result matching the searched title has been found, lets stop the search
        else:
            timeout = TIMEOUT_TOTAL - delta_time  # Still time to gather other results

        progreso.update(completed_channels * 100 / number_of_channels)

        try:
            itemlist.extend(search_results.get(timeout=timeout))
            completed_channels += 1
        except:
            # Expired timeout raise an exception
            break

    progreso.close()

    itemlist = sorted(itemlist, key=lambda item: item.fulltitle)

    return itemlist
示例#37
0
import re
import sys
import urlparse

from channelselector import get_thumb
from core import channeltools
from core import config
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item

from channels import filtertools


channel_xml = channeltools.get_channel_parameters("seriesblanco")
HOST = "http://seriesblanco.com/"
IDIOMAS = {'es': 'Español', 'en': 'Inglés', 'la': 'Latino', 'vo': 'VO', 'vos': 'VOS', 'vosi': 'VOSI', 'otro': 'OVOS'}
list_idiomas = [v for v in IDIOMAS.values()]
CALIDADES = ['SD', 'HDiTunes', 'Micro-HD-720p', 'Micro-HD-1080p', '1080p', '720p']

CAPITULOS_DE_ESTRENO_STR = "Capítulos de Estreno"

def mainlist(item):
    logger.info()

    thumb_series    = get_thumb("squares", "thumb_canales_series.png")
    thumb_series_az = get_thumb("squares", "thumb_canales_series_az.png")
    thumb_buscar    = get_thumb("squares", "thumb_buscar.png")

    itemlist = []
示例#38
0
def do_search(item):
    logger.info("pelisalacarta.channels.buscador do_search")

    tecleado = item.extra

    itemlist = []

    import os
    import glob
    import imp

    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    logger.info("pelisalacarta.channels.buscador channels_path="+channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info("pelisalacarta.channels.buscador channel_language="+channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info("pelisalacarta.channels.buscador channel_language="+channel_language)

    show_dialog = False
    progreso = None
    if config.is_xbmc():
        show_dialog = True

    try:
        import xbmcgui
        progreso = xbmcgui.DialogProgressBG()
        progreso.create("Buscando " + tecleado.title())
    except ImportError:
        xbmcgui = None
        show_dialog = False

    channel_files = glob.glob(channels_path)
    number_of_channels = len(channel_files)

    for index, infile in enumerate(channel_files):
        percentage = index*100/number_of_channels

        basename = os.path.basename(infile)
        basename_without_extension = basename[:-4]

        channel_parameters = channeltools.get_channel_parameters(basename_without_extension)

        # No busca si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # No busca si es un canal excluido de la busqueda global
        if channel_parameters["include_in_global_search"] != "true":
            continue

        # No busca si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue

        # No busca si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        if show_dialog:
            progreso.update(percentage, ' Buscando "' + tecleado + '"', basename_without_extension)

        logger.info("pelisalacarta.channels.buscador Intentado busqueda en " + basename_without_extension + " de " +
                    tecleado)
        try:

            # http://docs.python.org/library/imp.html?highlight=imp#module-imp
            obj = imp.load_source(basename_without_extension, infile[:-4]+".py")
            logger.info("pelisalacarta.channels.buscador cargado " + basename_without_extension + " de " + infile)
            channel_result_itemlist = obj.search(Item(), tecleado)
            for item in channel_result_itemlist:
                item.title = item.title + "[" + basename_without_extension + "]"
                item.viewmode = "list"

            itemlist.extend(channel_result_itemlist)
        except:
            import traceback
            logger.error(traceback.format_exc())

    itemlist = sorted(itemlist, key=lambda Item: Item.title) 

    if show_dialog:
        progreso.close()

    return itemlist
def do_channels_search(item):
    logger.info("streamondemand-pureita-master.channels.biblioteca do_channels_search")

    try:
        title_year = int(item.extra[0:4])
    except:
        title_year = 0
    mostra = item.extra[4:]
    tecleado = urllib.quote_plus(mostra)

    itemlist = []

    channels_path = os.path.join(config.get_runtime_path(), "channels", "*.xml")
    logger.info("streamondemand-pureita-master.channels.buscador channels_path=" + channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info("streamondemand-pureita-master.channels.buscador channel_language=" + channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info("streamondemand-pureita-master.channels.buscador channel_language=" + channel_language)

    if config.is_xbmc():
        show_dialog = True

    try:
        import xbmcgui

        progreso = xbmcgui.DialogProgressBG()
        progreso.create(NLS_Looking_For % mostra)
    except:
        show_dialog = False

    def worker(infile, queue):
        channel_result_itemlist = []
        try:
            basename_without_extension = os.path.basename(infile)[:-4]
            # http://docs.python.org/library/imp.html?highlight=imp#module-imp
            obj = imp.load_source(basename_without_extension, infile[:-4] + ".py")
            logger.info(
                "streamondemand-pureita-master.channels.buscador cargado "
                + basename_without_extension
                + " de "
                + infile
            )
            # item.url contains search type: serie, anime, etc...
            channel_result_itemlist.extend(obj.search(Item(extra=item.url), tecleado))
            for local_item in channel_result_itemlist:
                local_item.title = (
                    " [COLOR azure] "
                    + local_item.title
                    + " [/COLOR] [COLOR orange]su[/COLOR] [COLOR green]"
                    + basename_without_extension
                    + "[/COLOR]"
                )
                local_item.viewmode = "list"
        except:
            import traceback

            logger.error(traceback.format_exc())
        queue.put(channel_result_itemlist)

    channel_files = glob.glob(channels_path)

    channel_files_tmp = []
    for infile in channel_files:

        basename_without_extension = os.path.basename(infile)[:-4]

        channel_parameters = channeltools.get_channel_parameters(basename_without_extension)

        # No busca si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # No busca si es un canal excluido de la busqueda global
        if channel_parameters["include_in_global_search"] != "true":
            continue

        # No busca si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue

        # No busca si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        channel_files_tmp.append(infile)

    channel_files = channel_files_tmp

    result = Queue.Queue()
    threads = [threading.Thread(target=worker, args=(infile, result)) for infile in channel_files]

    start_time = int(time.time())

    for t in threads:
        t.daemon = (
            True
        )  # NOTE: setting dameon to True allows the main thread to exit even if there are threads still running
        t.start()

    number_of_channels = len(channel_files)
    completed_channels = 0
    while completed_channels < number_of_channels:

        delta_time = int(time.time()) - start_time
        if len(itemlist) <= 0:
            timeout = None  # No result so far,lets the thread to continue working until a result is returned
        elif delta_time >= TIMEOUT_TOTAL:
            break  # At least a result matching the searched title has been found, lets stop the search
        else:
            timeout = TIMEOUT_TOTAL - delta_time  # Still time to gather other results

        if show_dialog:
            progreso.update(completed_channels * 100 / number_of_channels)

        try:
            result_itemlist = result.get(timeout=timeout)
            completed_channels += 1
        except:
            # Expired timeout raise an exception
            break

        for item in result_itemlist:
            title = item.fulltitle

            # If the release year is known, check if it matches the year found in the title
            if title_year > 0:
                year_match = re.search("\(.*(\d{4}).*\)", title)
                if year_match and abs(int(year_match.group(1)) - title_year) > 1:
                    continue

            # Clean up a bit the returned title to improve the fuzzy matching
            title = re.sub(r"\(.*\)", "", title)  # Anything within ()
            title = re.sub(r"\[.*\]", "", title)  # Anything within []

            # Check if the found title fuzzy matches the searched one
            if fuzz.token_sort_ratio(mostra, title) > 85:
                itemlist.append(item)

    if show_dialog:
        progreso.close()

    itemlist = sorted(itemlist, key=lambda item: item.fulltitle)

    return itemlist
def filterchannels(category,preferred_thumb=""):
    logger.info("channelselector.filterchannels")

    channelslist =[]

    # Si category = "allchannelstatus" es que estamos activando/desactivando canales
    appenddisabledchannels = "false"
    if category == "allchannelstatus":
        category = "all"
        appenddisabledchannels = "true"

    # Lee la lista de canales
    channel_path = os.path.join( config.get_runtime_path() , "channels" , '*.xml' )
    logger.info("channelselector.filterchannels channel_path="+channel_path)

    channel_files = glob.glob(channel_path)
    logger.info("channelselector.filterchannels channel_files encontrados "+str(len(channel_files)))

    channel_language = config.get_setting("channel_language")
    logger.info("channelselector.filterchannels channel_language="+channel_language)
    if channel_language=="":
        channel_language = "all"
        logger.info("channelselector.filterchannels channel_language="+channel_language)

    for index, channel in enumerate(channel_files):
        logger.info("channelselector.filterchannels channel="+channel)
        if channel.endswith(".xml"):

            try:
                channel_parameters = channeltools.get_channel_parameters(channel[:-4])
                logger.info("channelselector.filterchannels channel_parameters="+repr(channel_parameters))

                # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea
                if preferred_thumb=="bannermenu" and "bannermenu" in channel_parameters:
                    channel_parameters["thumbnail"] = channel_parameters["bannermenu"]

                # Se salta el canal si no está activo y no estamos activando/desactivando los canales
                channel_status = None
                if config.get_setting("enabled", channel_parameters["channel"]):
                    channel_status = config.get_setting("enabled", channel_parameters["channel"])
                else:
                    channel_status = channel_parameters["active"]

                if channel_status != "true":
                    if appenddisabledchannels != "true":
                        continue

                # Se salta el canal para adultos si el modo adultos está desactivado
                if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") != "true": 
                    continue

                # Se salta el canal si está en un idioma filtrado
                if channel_language!="all" and channel_parameters["language"]!=config.get_setting("channel_language"):
                    continue

                # Se salta el canal si está en una categoria filtrado
                if category!="all" and category not in channel_parameters["categories"]:
                    continue

                # Si ha llegado hasta aquí, lo añade
                channelslist.append(Item(title=channel_parameters["title"], channel=channel_parameters["channel"],
                                         action="mainlist", thumbnail=channel_parameters["thumbnail"] ,
                                         fanart=channel_parameters["fanart"],
                                         category=channel_parameters["title"],
                                         language=channel_parameters["language"], viewmode="list" ))

            
            except:
                logger.info("Se ha producido un error al leer los datos del canal " + channel)
                import traceback
                logger.info(traceback.format_exc())
           
    channelslist.sort(key=lambda item: item.title.lower().strip())

    if category=="all":
        if config.get_setting("personalchannel5")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname5") ,action="mainlist", channel="personal5" ,thumbnail=config.get_setting("personalchannellogo5") , type="generic" ,viewmode="list" ))
        if config.get_setting("personalchannel4")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname4") ,action="mainlist", channel="personal4" ,thumbnail=config.get_setting("personalchannellogo4") , type="generic" ,viewmode="list" ))
        if config.get_setting("personalchannel3")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname3") ,action="mainlist", channel="personal3" ,thumbnail=config.get_setting("personalchannellogo3") , type="generic" ,viewmode="list" ))
        if config.get_setting("personalchannel2")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname2") ,action="mainlist", channel="personal2" ,thumbnail=config.get_setting("personalchannellogo2") , type="generic" ,viewmode="list" ))
        if config.get_setting("personalchannel")=="true":
            channelslist.insert( 0 , Item( title=config.get_setting("personalchannelname")  ,action="mainlist", channel="personal"  ,thumbnail=config.get_setting("personalchannellogo") , type="generic" ,viewmode="list" ))

        channel_parameters = channeltools.get_channel_parameters("tengourl")
        # Si prefiere el bannermenu y el canal lo tiene, cambia ahora de idea
        if preferred_thumb=="bannermenu" and "bannermenu" in channel_parameters:
            channel_parameters["thumbnail"] = channel_parameters["bannermenu"]

        channelslist.insert( 0 , Item( title="[COLOR gray]Inserisci un URL[/COLOR]"  ,action="mainlist", channel="tengourl" , thumbnail=channel_parameters["thumbnail"], type="generic" ,viewmode="movie" ))

    return channelslist
示例#41
0
# Canal para yaske
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re, urllib, urlparse

from core import config
from core import logger
from core import httptools
from core import scrapertools
from core import servertools
from core import channeltools
from core import tmdb
from core.item import Item

HOST = 'http://estrenosli.org/'
parameters= channeltools.get_channel_parameters('estrenosgo')
fanart_host= parameters['fanart']
thumbnail_host= parameters['thumbnail']
color1, color2, color3 = ['0xFF58D3F7','0xFF2E64FE','0xFF0404B4']

def mainlist(item):
    logger.info()
    itemlist = []
    item.url = HOST
    item.text_color = color2
    item.fanart = fanart_host

    item.thumbnail = "https://github.com/master-1970/resources/raw/master/images/genres/0/Directors%20Chair.png"
    itemlist.append(item.clone(title="Películas:", folder=False, text_color = color3, text_blod= True))
    itemlist.append(item.clone(title="    Cartelera", action="listado", url= HOST + "descarga-0-58126-0-0-fx-1-1-.fx"))
    itemlist.append(item.clone(title="    DVD-RIP", action="listado", url=HOST + "descarga-0-581210-0-0-fx-1-1.fx"))
示例#42
0
def filterchannels(category, view="thumb_"):
    logger.info()

    channelslist = []

    # Si category = "allchannelstatus" es que estamos activando/desactivando canales
    appenddisabledchannels = False
    if category == "allchannelstatus":
        category = "all"
        appenddisabledchannels = True

    # Lee la lista de canales
    channel_path = os.path.join(config.get_runtime_path(), "channels",
                                '*.json')
    logger.info("channel_path=%s" % channel_path)

    channel_files = glob.glob(channel_path)
    logger.info("channel_files encontrados %s" % (len(channel_files)))

    # channel_language = config.get_setting("channel_language", default="all")
    channel_language = auto_filter()
    logger.info("channel_language=%s" % channel_language)

    for channel_path in channel_files:
        logger.info("channel=%s" % channel_path)

        channel = os.path.basename(channel_path).replace(".json", "")

        try:
            channel_parameters = channeltools.get_channel_parameters(channel)

            if channel_parameters["channel"] == 'community':
                continue

            # si el canal no es compatible, no se muestra
            if not channel_parameters["compatible"]:
                continue

            # Si no es un canal lo saltamos
            if not channel_parameters["channel"]:
                continue
            logger.info("channel_parameters=%s" % repr(channel_parameters))

            # Si prefiere el banner y el canal lo tiene, cambia ahora de idea
            if view == "banner_" and "banner" in channel_parameters:
                channel_parameters["thumbnail"] = channel_parameters["banner"]

            # si el canal está desactivado no se muestra el canal en la lista
            if not channel_parameters["active"]:
                continue

            # Se salta el canal si no está activo y no estamos activando/desactivando los canales
            channel_status = config.get_setting("enabled",
                                                channel_parameters["channel"])

            if channel_status is None:
                # si channel_status no existe es que NO HAY valor en _data.json.
                # como hemos llegado hasta aquí (el canal está activo en channel.json), se devuelve True
                channel_status = True

            if not channel_status:
                # si obtenemos el listado de canales desde "activar/desactivar canales", y el canal está desactivado
                # lo mostramos, si estamos listando todos los canales desde el listado general y está desactivado,
                # no se muestra
                if not appenddisabledchannels:
                    continue

            # Se salta el canal para adultos si el modo adultos está desactivado
            if channel_parameters["adult"] and config.get_setting(
                    "adult_mode") == 0:
                continue

            # Se salta el canal si está en un idioma filtrado
            # Se muestran todos los canales si se elige "all" en el filtrado de idioma
            # Se muestran sólo los idiomas filtrados, cast o lat
            # Los canales de adultos se mostrarán siempre que estén activos
            if channel_language != "all" and channel_language not in channel_parameters["language"] \
                    and "*" not in channel_parameters["language"]:
                continue

            # Se salta el canal si está en una categoria filtrado
            if category != "all" and category not in channel_parameters[
                    "categories"]:
                continue

            # Si tiene configuración añadimos un item en el contexto
            context = []
            if channel_parameters["has_settings"]:
                context.append({
                    "title": config.get_localized_string(70525),
                    "channel": "setting",
                    "action": "channel_config",
                    "config": channel_parameters["channel"]
                })

            channel_info = set_channel_info(channel_parameters)
            # Si ha llegado hasta aquí, lo añade
            channelslist.append(
                Item(title=channel_parameters["title"],
                     channel=channel_parameters["channel"],
                     action="mainlist",
                     thumbnail=channel_parameters["thumbnail"],
                     fanart=channel_parameters["fanart"],
                     plot=channel_info,
                     category=channel_parameters["title"],
                     language=channel_parameters["language"],
                     viewmode="list",
                     context=context))

        except:
            logger.error(
                "Se ha producido un error al leer los datos del canal '%s'" %
                channel)
            import traceback
            logger.error(traceback.format_exc())

    channelslist.sort(key=lambda item: item.title.lower().strip())

    if category == "all":
        channel_parameters = channeltools.get_channel_parameters('url')
        # Si prefiere el banner y el canal lo tiene, cambia ahora de idea
        if view == "banner_" and "banner" in channel_parameters:
            channel_parameters["thumbnail"] = channel_parameters["banner"]

        channelslist.insert(
            0,
            Item(title=config.get_localized_string(60088),
                 action="mainlist",
                 channel="url",
                 thumbnail=channel_parameters["thumbnail"],
                 type="generic",
                 viewmode="list"))

    if category in ['movie', 'tvshow']:
        titles = [
            config.get_localized_string(70028),
            config.get_localized_string(30985),
            config.get_localized_string(70559),
            config.get_localized_string(60264),
            config.get_localized_string(70560)
        ]
        ids = ['popular', 'top_rated', 'now_playing', 'on_the_air']
        for x in range(0, 3):
            if x == 2 and category != 'movie':
                title = titles[x + 1]
                id = ids[x + 1]
            else:
                title = titles[x]
                id = ids[x]
            channelslist.insert(
                x,
                Item(channel='search',
                     action='discover_list',
                     title=title,
                     search_type='list',
                     list_type='%s/%s' % (category.replace('show', ''), id),
                     thumbnail=get_thumb(id + ".png")))

        channelslist.insert(
            3,
            Item(channel='search',
                 action='genres_menu',
                 title=config.get_localized_string(30987),
                 type=category.replace('show', ''),
                 thumbnail=get_thumb("genres.png")))

    return channelslist
示例#43
0
from core import channeltools
from core import logger
from core import config
from core import scrapertools
from core.item import Item
from servers import servertools
from channelselector import get_thumbnail_path

__channel__ = "seriesblanco"
__category__ = "F"
__type__ = "generic"
__title__ = "Series Blanco"
__language__ = "ES"

channel_xml = channeltools.get_channel_parameters(__channel__)
HOST = "http://seriesblanco.com/"
IDIOMAS = {'es': 'Español', 'la': 'Latino', 'vos': 'VOS', 'vo': 'VO', 'japovose': 'VOSE', 'jp-sub': 'VOSE'}


DEBUG = config.get_setting("debug")


def isGeneric():
    return True


def mainlist(item):
    logger.info("pelisalacarta.seriesblanco mainlist")

    thumb_series = get_thumbnail("thumb_canales_series.png")
示例#44
0
def do_search(item, categories=[]):
    multithread = config.get_setting("multithread", "buscador")
    result_mode = "result_mode_%s" % config.get_setting("result_mode", "buscador")
    logger.info()

    tecleado = item.extra

    itemlist = []

    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    logger.info("channels_path=%s" % channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info("channel_language=%s" % channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info("channel_language=%s" % channel_language)

    # Para Kodi es necesario esperar antes de cargar el progreso, de lo contrario
    # el cuadro de progreso queda "detras" del cuadro "cargando..." y no se le puede dar a cancelar
    time.sleep(0.5)
    progreso = platformtools.dialog_progress("Buscando '%s'..." % tecleado, "")
    channel_files = sorted(glob.glob(channels_path), key=lambda x: os.path.basename(x))
    number_of_channels = len(channel_files)

    searches = []
    search_results = {}
    start_time = time.time()

    if multithread:
        progreso.update(0, "Buscando '%s'..." % tecleado)

    for index, infile in enumerate(channel_files):
        try:
            percentage = (index * 100) / number_of_channels

            basename = os.path.basename(infile)
            basename_without_extension = basename[:-4]
            logger.info("%s..." % basename_without_extension)

            channel_parameters = channeltools.get_channel_parameters(basename_without_extension)

            # No busca si es un canal inactivo
            if channel_parameters["active"] != True:
                logger.info("%s no incluido" % basename_without_extension)
                continue

            # En caso de busqueda por categorias
            if categories:
                if not any(cat in channel_parameters["categories"] for cat in categories):
                    logger.info("%s no incluido" % basename_without_extension)
                    continue

            # No busca si es un canal para adultos, y el modo adulto está desactivado
            if channel_parameters["adult"] == True and config.get_setting("adult_mode") == 0:
                logger.info("%s no incluido" % basename_without_extension)
                continue

            # No busca si el canal es en un idioma filtrado
            if channel_language != "all" and channel_parameters["language"] != channel_language:
                logger.info("%s no incluido" % basename_without_extension)
                continue

            # No busca si es un canal excluido de la busqueda global
            include_in_global_search = channel_parameters["include_in_global_search"]
            if include_in_global_search == True:
                # Buscar en la configuracion del canal
                include_in_global_search = config.get_setting("include_in_global_search", basename_without_extension)

            if include_in_global_search != True:
                logger.info("%s no incluido" % basename_without_extension)
                continue

            if progreso.iscanceled():
                progreso.close()
                logger.info("Busqueda cancelada")
                return itemlist

            # Modo Multi Thread
            if multithread:
                t = Thread(target=channel_search, args=[search_results, channel_parameters, tecleado],
                           name=channel_parameters["title"])
                t.setDaemon(True)
                t.start()
                searches.append(t)

            # Modo single Thread
            else:
                logger.info("Intentado busqueda en " + basename_without_extension + " de " + tecleado)
                channel_search(search_results, channel_parameters, tecleado)

            logger.info("%s incluido en la busqueda" % basename_without_extension)
            progreso.update(percentage / 2, "Iniciada busqueda de '%s' en %s..." % (tecleado, channel_parameters["title"]))

        except:
            logger.error("No se puede buscar en: %s" % channel_parameters["title"])
            import traceback
            logger.error(traceback.format_exc())
            continue

    # Modo Multi Thread
    # Usando isAlive() no es necesario try-except,
    # ya que esta funcion (a diferencia de is_alive())
    # es compatible tanto con versiones antiguas de python como nuevas
    if multithread:
        pendent = [a for a in searches if a.isAlive()]
        while pendent:
            percentage = (len(searches) - len(pendent)) * 100 / len(searches)
            completed = len(searches) - len(pendent)

            if len(pendent) > 5:
                progreso.update(percentage, "Busqueda terminada en %d de %d canales..." % (completed, len(searches)))
            else:
                list_pendent_names = [a.getName() for a in pendent]
                mensaje = "Buscando en %s" % (", ".join(list_pendent_names))
                progreso.update(percentage, mensaje)
                logger.debug(mensaje)

            if progreso.iscanceled():
                logger.info("Busqueda cancelada")
                break

            time.sleep(0.5)
            pendent = [a for a in searches if a.isAlive()]

    total = 0

    for channel in sorted(search_results.keys()):
        for search in search_results[channel]:
            total += len(search["itemlist"])
            title = channel
            if result_mode == "result_mode_0":
                if len(search_results[channel]) > 1:
                    title += " [" + search["item"].title.strip() + "]"
                title += " (" + str(len(search["itemlist"])) + ")"

                title = re.sub("\[COLOR [^\]]+\]", "", title)
                title = re.sub("\[/COLOR]", "", title)

                #extra = search["item"].extra + "{}" + search["item"].channel + "{}" + tecleado
                itemlist.append(Item(title=title, channel="buscador", action="show_result", url=search["item"].url,
                                     extra=search["item"].extra, folder=True, adult=search["adult"],from_action="search",
                                     from_channel=search["item"].channel, tecleado=tecleado))
            else:
                title = ">> Resultados del canal %s:" % title
                itemlist.append(Item(title=title, channel="buscador", action="",
                                     folder=False, text_color="yellow"))
                #itemlist.extend(search["itemlist"])
                for i in search["itemlist"]:
                    if i.action:
                        itemlist.append(i.clone(from_action=i.action, from_channel=i.channel, channel="buscador",
                                        action="show_result", adult=search["adult"]))

    title = "Buscando: '%s' | Encontrado: %d vídeos | Tiempo: %2.f segundos" % (tecleado, total, time.time()-start_time)
    itemlist.insert(0, Item(title=title, text_color='yellow'))

    progreso.close()

    return itemlist
def getchanneltypes(preferred_thumb=""):
    logger.info("channelselector getchanneltypes")

    # Lista de categorias
    valid_types = ""
    dict_cat_lang = ""

    # Lee la lista de canales
    channel_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    logger.info("channelselector.getchanneltypes channel_path=" + channel_path)

    channel_files = glob.glob(channel_path)

    channel_language = config.get_setting("channel_language")
    logger.info("channelselector.getchanneltypes channel_language=" + channel_language)

    # Construye la lista de tipos
    channel_types = []

    for index, channel in enumerate(channel_files):
        logger.info("channelselector.getchanneltypes channel=" + channel)
        if channel.endswith(".xml"):
            try:
                channel_parameters = channeltools.get_channel_parameters(channel[:-4])
                logger.info("channelselector.filterchannels channel_parameters=" + repr(channel_parameters))

                # Si es un canal para adultos y el modo adulto está desactivado, se lo salta
                if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
                    continue

                # Si el canal está en un idioma filtrado
                if channel_language != "all" and channel_parameters["language"] != channel_language:
                    continue

                categories = channel_parameters["categories"]
                for category in categories:
                    logger.info("channelselector.filterchannels category=" + category)
                    if category not in channel_types and category in valid_types:
                        channel_types.append(category)

            except:
                logger.info("Se ha producido un error al leer los datos del canal " + channel + traceback.format_exc())

    logger.info("channelselector.getchanneltypes Encontrados:")
    for channel_type in channel_types:
        logger.info("channelselector.getchanneltypes channel_type=" + channel_type)

    # Ahora construye el itemlist ordenadamente
    itemlist = list()

    itemlist.append(Item(title="Top Channels", channel="channelselector", action="filterchannels",
                         category="top channels", channel_type="top channels", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_topchannels.png"),
                         viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30122), channel="channelselector", action="filterchannels",
                         category="movie", channel_type="movie", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_film.png"), viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30123), channel="channelselector", action="filterchannels",
                         category="serie", channel_type="serie", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_series.png"), viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30124), channel="channelselector", action="filterchannels",
                         category="anime", channel_type="anime", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_anime.png"), viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30125), channel="channelselector", action="filterchannels",
                         category="documentary", channel_type="documentary", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_documentales.png"),
                         viewmode="movie"))
    itemlist.append(Item(title="Cult", channel="channelselector", action="filterchannels",
                         category="cult", channel_type="cult", thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "main_menu_filmontv.png"),
                         viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(50000), channel="saghe", action="mainlist",
                         category="saghe", channel_type="saghe", thumbnail = os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_saghe.png")))
    itemlist.append( Item(title=config.get_localized_string(50001) , channel="filmontv" , action="mainlist" , thumbnail = os.path.join(config.get_runtime_path() , "resources" , "images", "main_menu_filmontv.png"),viewmode="movie") )
    itemlist.append( Item(title=config.get_localized_string(50003) , channel="netflixsrc" , action="mainlist" , thumbnail = os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_series.png"),viewmode="movie") )
    itemlist.append( Item( title=config.get_localized_string(30136) , channel="channelselector" , action="filterchannels" , channel_type="vos", category="vos" , thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_vos.png"),viewmode="movie") )
    #itemlist.append( Item( title="Torrent" , channel="channelselector" , action="filterchannels" , channel_type="torrent", category="torrent" , thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "cat_menu_torrent.png"),viewmode="movie") )
    itemlist.append( Item( title="[COLOR yellow]" + config.get_localized_string(30121) + "[/COLOR]" , channel="channelselector" , action="filterchannels" , channel_type="all", category="all" , thumbnail= os.path.join(config.get_runtime_path() , "resources" , "images", "main_menu_all.png"),viewmode="movie") )

    logger.info("channelselector.getchanneltypes Ordenados:")
    for channel_type in valid_types:
        logger.info("channelselector.getchanneltypes channel_type="+channel_type)
        if channel_type in channel_types:
            title = dict_cat_lang.get(channel_type, channel_type)
            itemlist.append(Item(title=title, channel="channelselector", action="filterchannels", category=title,
                                 channel_type= channel_type, viewmode="thumbnails",
                                 thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                            "thumb_canales_"+channel_type+".png")))

    return itemlist
def do_search(item):
    logger.info("streamondemand.channels.saghe do_search")

    tecleado = item.extra
    mostra = item.fulltitle

    itemlist = []

    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    logger.info("streamondemand.channels.buscador channels_path=" + channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info("streamondemand.channels.buscador channel_language=" + channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info("streamondemand.channels.buscador channel_language=" + channel_language)

    if config.is_xbmc():
        show_dialog = True

    try:
        import xbmcgui
        progreso = xbmcgui.DialogProgressBG()
        progreso.create("Ricerca di " + mostra)
    except:
        show_dialog = False

    def worker(infile, queue):
        channel_result_itemlist = []
        try:
            basename_without_extension = os.path.basename(infile)[:-4]
            # http://docs.python.org/library/imp.html?highlight=imp#module-imp
            obj = imp.load_source(basename_without_extension, infile[:-4]+".py")
            logger.info("streamondemand.channels.buscador cargado " + basename_without_extension + " de " + infile)
            channel_result_itemlist.extend(obj.search(Item(), tecleado))
            for item in channel_result_itemlist:
                item.title = " [COLOR azure] " + item.title + " [/COLOR] [COLOR orange]su[/COLOR] [COLOR green]" + basename_without_extension + "[/COLOR]"
                item.viewmode = "list"
        except:
            import traceback
            logger.error(traceback.format_exc())
        queue.put(channel_result_itemlist)

    channel_files = glob.glob(channels_path)

    channel_files_tmp = []
    for infile in channel_files:

        basename_without_extension = os.path.basename(infile)[:-4]

        channel_parameters = channeltools.get_channel_parameters(basename_without_extension)

        # No busca si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # No busca si es un canal excluido de la busqueda global
        if channel_parameters["include_in_global_search"] != "true":
            continue

        # No busca si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "false":
            continue

        # No busca si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters["language"] != channel_language:
            continue

        channel_files_tmp.append(infile)

    channel_files = channel_files_tmp

    result = Queue.Queue()
    threads = [threading.Thread(target=worker, args=(infile, result)) for infile in channel_files]

    for t in threads:
        t.start()

    number_of_channels = len(channel_files)

    for index, t in enumerate(threads):
        percentage = index * 100 / number_of_channels
        if show_dialog:
            progreso.update(percentage, ' Sto cercando "' + mostra + '"')
        t.join()
        itemlist.extend(result.get())

    itemlist = sorted([item for item in itemlist if fuzz.WRatio(mostra, item.fulltitle) > 85],
                      key=lambda Item: Item.title)

    if show_dialog:
        progreso.close()

    return itemlist
示例#47
0
def do_search(item, categories=[]):
    multithread = config.get_setting("multithread", "buscador")
    result_mode = config.get_setting("result_mode", "buscador")
    logger.info()

    tecleado = item.extra

    itemlist = []

    channels_path = os.path.join(config.get_runtime_path(), "channels", '*.xml')
    logger.info("channels_path=%s" % channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info("channel_language=%s" % channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info("channel_language=%s" % channel_language)

    # Para Kodi es necesario esperar antes de cargar el progreso, de lo contrario
    # el cuadro de progreso queda "detras" del cuadro "cargando..." y no se le puede dar a cancelar
    time.sleep(0.5)
    progreso = platformtools.dialog_progress("Buscando '%s'..." % tecleado, "")
    channel_files = sorted(glob.glob(channels_path), key=lambda x: os.path.basename(x))
    number_of_channels = len(channel_files)

    searches = []
    search_results = {}
    start_time = time.time()

    if multithread:
        progreso.update(0, "Buscando '%s'..." % tecleado)

    for index, infile in enumerate(channel_files):
        try:
            percentage = (index * 100) / number_of_channels

            basename = os.path.basename(infile)
            basename_without_extension = basename[:-4]
            logger.info("%s..." % basename_without_extension)

            channel_parameters = channeltools.get_channel_parameters(basename_without_extension)

            # No busca si es un canal inactivo
            if channel_parameters["active"] != "true":
                logger.info("%s no incluido" % basename_without_extension)
                continue

            # En caso de busqueda por categorias
            if categories:
                if not any(cat in channel_parameters["categories"] for cat in categories):
                    logger.info("%s no incluido" % basename_without_extension)
                    continue

            # No busca si es un canal para adultos, y el modo adulto está desactivado
            if channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "0":
                logger.info("%s no incluido" % basename_without_extension)
                continue

            # No busca si el canal es en un idioma filtrado
            if channel_language != "all" and channel_parameters["language"] != channel_language:
                logger.info("%s no incluido" % basename_without_extension)
                continue

            # No busca si es un canal excluido de la busqueda global
            include_in_global_search = channel_parameters["include_in_global_search"]
            if include_in_global_search in ["", "true"]:
                # Buscar en la configuracion del canal
                include_in_global_search = str(config.get_setting("include_in_global_search", basename_without_extension))
                # Si no hay valor en la configuración del canal se incluye ya que así estaba por defecto
                '''if include_in_global_search == "":
                    include_in_global_search = "true"'''

            if include_in_global_search.lower() != "true":
                logger.info("%s no incluido" % basename_without_extension)
                continue

            if progreso.iscanceled():
                progreso.close()
                logger.info("Busqueda cancelada")
                return itemlist

            # Modo Multi Thread
            if multithread:
                t = Thread(target=channel_search, args=[search_results, channel_parameters, tecleado],
                           name=channel_parameters["title"])
                t.setDaemon(True)
                t.start()
                searches.append(t)

            # Modo single Thread
            else:
                logger.info("Intentado busqueda en " + basename_without_extension + " de " + tecleado)
                channel_search(search_results, channel_parameters, tecleado)

            logger.info("%s incluido en la busqueda" % basename_without_extension)
            progreso.update(percentage / 2, "Iniciada busqueda de '%s' en %s..." % (tecleado, channel_parameters["title"]))

        except:
            continue
            logger.error("No se puede buscar en: %s" % channel_parameters["title"])
            import traceback
            logger.error(traceback.format_exc())

    # Modo Multi Thread
    # Usando isAlive() no es necesario try-except,
    # ya que esta funcion (a diferencia de is_alive())
    # es compatible tanto con versiones antiguas de python como nuevas
    if multithread:
        pendent = [a for a in searches if a.isAlive()]
        while pendent:
            percentage = (len(searches) - len(pendent)) * 100 / len(searches)
            completed = len(searches) - len(pendent)

            if len(pendent) > 5:
                progreso.update(percentage, "Busqueda terminada en %d de %d canales..." % (completed, len(searches)))
            else:
                list_pendent_names = [a.getName() for a in pendent]
                mensaje = "Buscando en %s" % (", ".join(list_pendent_names))
                progreso.update(percentage, mensaje)
                logger.debug(mensaje)

            if progreso.iscanceled():
                logger.info("Busqueda cancelada")
                break

            time.sleep(0.5)
            pendent = [a for a in searches if a.isAlive()]

    total = 0

    for channel in sorted(search_results.keys()):
        for search in search_results[channel]:
            total += len(search["itemlist"])
            title = channel
            if result_mode == 0:
                if len(search_results[channel]) > 1:
                    title += " [" + search["item"].title.strip() + "]"
                title += " (" + str(len(search["itemlist"])) + ")"

                title = re.sub("\[COLOR [^\]]+\]", "", title)
                title = re.sub("\[/COLOR]", "", title)

                extra = search["item"].extra + "{}" + search["item"].channel + "{}" + tecleado
                itemlist.append(Item(title=title, channel="buscador", action="channel_result", url=search["item"].url,
                                     extra=extra, folder=True))
            else:
                title = ">> Resultados del canal %s:" % title
                itemlist.append(Item(title=title, channel="buscador", action="",
                                     folder=False, text_color="yellow"))
                itemlist.extend(search["itemlist"])
                # itemlist.append(Item(title="", channel="buscador", action="", folder=False))

    title = "Buscando: '%s' | Encontrado: %d vídeos | Tiempo: %2.f segundos" % (tecleado, total, time.time()-start_time)
    itemlist.insert(0, Item(title=title, text_color='yellow'))

    progreso.close()

    return itemlist
def do_search(item):
    logger.info("streamondemand.channels.buscador do_search")

    tecleado = item.extra
    mostra = item.fulltitle

    itemlist = []

    channels_path = os.path.join(config.get_runtime_path(), "channels",
                                 '*.xml')
    logger.info("streamondemand.channels.buscador channels_path=" +
                channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info("streamondemand.channels.buscador channel_language=" +
                channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info("streamondemand.channels.buscador channel_language=" +
                    channel_language)

    if config.is_xbmc():
        show_dialog = True

    try:
        import xbmcgui
        progreso = xbmcgui.DialogProgressBG()
        progreso.create("Ricerca di " + mostra)
    except:
        show_dialog = False

    def worker(infile, queue):
        channel_result_itemlist = []
        try:
            basename_without_extension = os.path.basename(infile)[:-4]
            # http://docs.python.org/library/imp.html?highlight=imp#module-imp
            obj = imp.load_source(basename_without_extension,
                                  infile[:-4] + ".py")
            logger.info("streamondemand.channels.buscador cargado " +
                        basename_without_extension + " de " + infile)
            channel_result_itemlist.extend(
                obj.search(Item(extra='movie'), tecleado))
            for item in channel_result_itemlist:
                item.title = " [COLOR azure] " + item.title + " [/COLOR] [COLOR orange]su[/COLOR] [COLOR orange]" + basename_without_extension + "[/COLOR]"
                item.viewmode = "list"
        except:
            import traceback
            logger.error(traceback.format_exc())
        queue.put(channel_result_itemlist)

    channel_files = glob.glob(channels_path)

    channel_files_tmp = []
    for infile in channel_files:

        basename_without_extension = os.path.basename(infile)[:-4]

        channel_parameters = channeltools.get_channel_parameters(
            basename_without_extension)

        # Non cercare se il canale e inattivo
        if channel_parameters["active"] != "true":
            continue

        # Non Cercare se in canale e escluso dalla ricerca globale
        if channel_parameters["include_in_global_search"] != "true":
            continue

        # Non cercare se il canale e per adulti e se la modalita adulti e disabilitata
        if channel_parameters["adult"] == "true" and config.get_setting(
                "adult_mode") == "false":
            continue

        # Non cercare se il canale e in una lingua filtrata
        if channel_language != "all" and channel_parameters[
                "language"] != channel_language:
            continue

        channel_files_tmp.append(infile)

    channel_files = channel_files_tmp

    result = Queue.Queue()
    threads = [
        threading.Thread(target=worker, args=(infile, result))
        for infile in channel_files
    ]

    start_time = int(time.time())

    for t in threads:
        t.daemon = True  # NOTE: setting dameon to True allows the main thread to exit even if there are threads still running
        t.start()

    number_of_channels = len(channel_files)
    completed_channels = 0
    while completed_channels < number_of_channels:

        delta_time = int(time.time()) - start_time
        if len(itemlist) <= 0:
            timeout = None  # No result so far,lets the thread to continue working until a result is returned
        elif delta_time >= TIMEOUT_TOTAL:
            break  # At least a result matching the searched title has been found, lets stop the search
        else:
            timeout = TIMEOUT_TOTAL - delta_time  # Still time to gather other results

        if show_dialog:
            progreso.update(completed_channels * 100 / number_of_channels)

        try:
            result_itemlist = result.get(timeout=timeout)
            completed_channels += 1
        except:
            # Expired timeout raise an exception
            break

        for item in result_itemlist:
            title = item.fulltitle

            # Clean up a bit the returned title to improve the fuzzy matching
            title = re.sub(r'\(.*\)', '', title)  # Anything within ()
            title = re.sub(r'\[.*\]', '', title)  # Anything within []

            # Check if the found title fuzzy matches the searched one
            if fuzz.WRatio(mostra, title) > 85: itemlist.append(item)

    if show_dialog:
        progreso.close()

    itemlist = sorted(itemlist, key=lambda item: item.fulltitle)

    return itemlist
示例#49
0
def conf_tools(item):
    logger.info()

    # Activar o desactivar canales
    if item.extra == "channels_onoff":
        import channelselector
        from core import channeltools

        channel_list = channelselector.filterchannels("allchannelstatus")

        channel_language = config.get_setting("channel_language")
        if channel_language == "":
            channel_language = "all"

        excluded_channels = ['tengourl',
                             'buscador',
                             'libreria',
                             'configuracion',
                             'novedades',
                             'personal',
                             'ayuda',
                             'descargas']

        list_controls = []
        try:
            list_controls.append({'id': "all_channels",
                                  'type': "list",
                                  'label': "Todos los canales",
                                  'default': 0,
                                  'enabled': True,
                                  'visible': True,
                                  'lvalues': ['',
                                              'Activar todos',
                                              'Desactivar todos',
                                              'Establecer estado por defecto']})

            for channel in channel_list:
                # Si el canal esta en la lista de exclusiones lo saltamos
                if channel.channel not in excluded_channels:
                    # Se cargan los ajustes del archivo json del canal
                    jsonchannel = channeltools.get_channel_json(channel.channel)
                    if jsonchannel.get("settings") or jsonchannel.get("active"):
                        channel_parameters = channeltools.get_channel_parameters(channel.channel)

                        # No incluir si es un canal para adultos, y el modo adulto está desactivado
                        if (channel_parameters["adult"] == "true" and
                                config.get_setting("adult_mode") == "0"):
                            continue

                        # No incluir si el canal es en un idioma filtrado
                        if (channel_language != "all" and
                                channel_parameters["language"] != channel_language):
                            continue

                        status = None
                        xml_status = channel_parameters["active"].replace("t", "T").replace("f", "F")
                        xml_status = eval(xml_status)

                        if config.get_setting("enabled", channel.channel):
                            status = config.get_setting("enabled", channel.channel)
                            status = status.replace("t", "T").replace("f", "F")
                            status = eval(status)
                            # logger.info(channel.channel + " | Status: " + str(status))
                        else:
                            status = xml_status
                            # logger.info(channel.channel + " | Status (XML): " + str(status))

                        status_control = ""
                        if not xml_status:
                            status_control = " [COLOR grey](Desactivado por defecto)[/COLOR]"

                        if status is not None:
                            control = {'id': channel.channel,
                                       'type': "bool",
                                       'label': channel_parameters["title"] + status_control,
                                       'default': status,
                                       'enabled': True,
                                       'visible': True}
                            list_controls.append(control)

                    else:
                        logger.info("Algo va mal con el canal " + channel.channel)
                else:
                    continue

            return platformtools.show_channel_settings(list_controls=list_controls,
                                                       caption="Canales",
                                                       callback="channel_status",
                                                       custom_button={"visible": False})
        except:
            import traceback
            logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc())
            platformtools.dialog_notification("Error",
                                              "Se ha producido un error con el canal %s" %
                                              channel.title)

    # Comprobacion de archivos channel_data.json
    elif item.extra == "lib_check_datajson":
        itemlist = []
        import channelselector
        from core import channeltools
        channel_list = channelselector.filterchannels("allchannelstatus")

        # Tener una lista de exclusion no tiene mucho sentido por que se comprueba si
        # el xml tiene "settings", pero por si acaso se deja
        excluded_channels = ['tengourl',
                             'configuracion',
                             'personal',
                             'ayuda']

        try:
            import os
            from core import jsontools
            for channel in channel_list:

                needsfix = None
                list_status = None
                list_controls = None
                default_settings = None
                channeljson_exists = None

                # Se convierte el "channel.channel" del canal biblioteca para que no de error
                if channel.channel == "libreria":
                    channel.channel = "biblioteca"

                # Se comprueba si el canal esta en la lista de exclusiones
                if channel.channel not in excluded_channels:
                    # Se comprueba que tenga "settings", sino se salta
                    jsonchannel = channeltools.get_channel_json(channel.channel)
                    if not jsonchannel.get("settings"):
                        itemlist.append(Item(channel=CHANNELNAME,
                                             title=channel.title + " - No tiene ajustes por defecto",
                                             action="", folder=False,
                                             thumbnail=channel.thumbnail))
                        continue
                        # logger.info(channel.channel + " SALTADO!")

                    # Se cargan los ajustes del archivo json del canal
                    file_settings = os.path.join(config.get_data_path(), "settings_channels",
                                                 channel.channel + "_data.json")
                    dict_settings = {}
                    dict_file = {}
                    if filetools.exists(file_settings):
                        # logger.info(channel.channel + " Tiene archivo _data.json")
                        channeljson_exists = "true"
                        # Obtenemos configuracion guardada de ../settings/channel_data.json
                        try:
                            dict_file = jsontools.load_json(open(file_settings, "rb").read())
                            if isinstance(dict_file, dict) and 'settings' in dict_file:
                                dict_settings = dict_file['settings']
                        except EnvironmentError:
                            logger.info("ERROR al leer el archivo: %s" % file_settings)
                    else:
                        # logger.info(channel.channel + " No tiene archivo _data.json")
                        channeljson_exists = "false"

                    if channeljson_exists == "true":
                        try:
                            datajson_size = filetools.getsize(file_settings)
                        except:
                            import traceback
                            logger.info(channel.title +
                                        " | Detalle del error: %s" % traceback.format_exc())
                    else:
                        datajson_size = None

                    # Si el _data.json esta vacio o no existe...
                    if (len(dict_settings) and datajson_size) == 0 or channeljson_exists == "false":
                        # Obtenemos controles del archivo ../channels/channel.xml
                        needsfix = "true"
                        try:
                            # Se cargan los ajustes por defecto
                            list_controls, default_settings = channeltools.get_channel_controls_settings(channel.channel)
                            # logger.info(channel.title + " | Default: %s" % default_settings)
                        except:
                            import traceback
                            logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc())
                            # default_settings = {}

                        # Si _data.json necesita ser reparado o no existe...
                        if needsfix == "true" or channeljson_exists == "false":
                            if default_settings is not None:
                                # Creamos el channel_data.json
                                default_settings.update(dict_settings)
                                dict_settings = default_settings
                                dict_file['settings'] = dict_settings
                                # Creamos el archivo ../settings/channel_data.json
                                json_data = jsontools.dump_json(dict_file)
                                try:
                                    open(file_settings, "wb").write(json_data)
                                    # logger.info(channel.channel + " - Archivo _data.json GUARDADO!")
                                    # El channel_data.json se ha creado/modificado
                                    list_status = " - [COLOR red] CORREGIDO!![/COLOR]"
                                except EnvironmentError:
                                    logger.info("ERROR al salvar el archivo: %s" % file_settings)
                            else:
                                if default_settings is None:
                                    list_status = " - [COLOR red] Imposible cargar los ajustes por defecto![/COLOR]"

                    else:
                        # logger.info(channel.channel + " - NO necesita correccion!")
                        needsfix = "false"

                    # Si se ha establecido el estado del canal se añade a la lista
                    if needsfix is not None:
                        if needsfix == "true":
                            if channeljson_exists == "false":
                                list_status = " - Ajustes creados"
                                list_colour = "red"
                            else:
                                list_status = " - No necesita correccion"
                                list_colour = "green"
                        else:
                            # Si "needsfix" es "false" y "datjson_size" es None habra
                            # ocurrido algun error
                            if datajson_size is None:
                                list_status = " - Ha ocurrido algun error"
                                list_colour = "red"
                            else:
                                list_status = " - No necesita correccion"
                                list_colour = "green"

                    if list_status is not None:
                        itemlist.append(Item(channel=CHANNELNAME,
                                             title=channel.title + list_status,
                                             action="", folder=False,
                                             thumbnail=channel.thumbnail,
                                             text_color=list_colour))
                    else:
                        logger.info("Algo va mal con el canal %s" % channel.channel)

                # Si el canal esta en la lista de exclusiones lo saltamos
                else:
                    continue
        except:
            import traceback
            logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc())
            platformtools.dialog_notification("Error",
                                              "Se ha producido un error con el canal %s" %
                                              channel.title)
        return itemlist

    else:
        platformtools.dialog_notification("pelisalacarta", "Error!")
        platformtools.itemlist_update(Item(channel=CHANNELNAME, action="submenu_tools"))
示例#50
0
import sys
import urlparse
from time import sleep

from core import channeltools
from core import httptools
from core import jsontools
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
from platformcode import platformtools

host = 'https://www.megadede.com'
__channel__ = 'megadede'
parameters = channeltools.get_channel_parameters(__channel__)
fanart_host = parameters['fanart']
thumbnail_host = parameters['thumbnail']
color1, color2, color3 = ['0xFFB10021', '0xFFB10021', '0xFFB10004']


def login():
    url_origen = host + "/login?popup=1"
    try:
        data = httptools.downloadpage(url_origen).data
    except:
        data = httptools.downloadpage(url_origen, follow_redirects=False).data
    if '<span class="username">' in data:
        return True
    token = scrapertools.find_single_match(
        data, '<input name="_token" type="hidden" value="([^"]+)"')
示例#51
0
def mainlist(item):
    logger.info()

    itemlist = list()
    itemlist.append(Item(channel=CHANNELNAME, title="Preferencias", action="settings", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))

    if config.get_setting("plugin_updates_available") == "0":
        nuevas = ""
    elif config.get_setting("plugin_updates_available") == "1":
        nuevas = " (1 nueva)"
    else:
        nuevas = " (" + config.get_setting("plugin_updates_available") + " nuevas)"

    thumb_configuracion = "thumb_configuracion_" + config.get_setting("plugin_updates_available") + ".png"

    itemlist.append(Item(channel=CHANNELNAME, title="Descargar e instalar otras versiones" + nuevas,
                         action="get_all_versions", folder=True,
                         thumbnail=get_thumbnail_path(thumb_configuracion)))

    itemlist.append(Item(channel=CHANNELNAME, title="", action="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))

    itemlist.append(Item(channel=CHANNELNAME, title="Ajustes especiales", action="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))
    itemlist.append(Item(channel="novedades", title="   Ajustes de la sección 'Novedades'", action="menu_opciones",
                         folder=True, thumbnail=get_thumbnail_path("thumb_novedades.png")))
    itemlist.append(Item(channel="buscador", title="   Ajustes del buscador global", action="opciones", folder=True,
                         thumbnail=get_thumbnail_path("thumb_buscar.png")))
    itemlist.append(Item(channel=CHANNELNAME, title="   Ajustes de descargas", action="channel_config", config="descargas", folder=True,
                         thumbnail=get_thumbnail_path("thumb_descargas.png")))
                         
    if config.get_library_support():
        itemlist.append(Item(channel="biblioteca", title="   Ajustes de la biblioteca",
                             action="channel_config", folder=True,
                             thumbnail=get_thumbnail_path("thumb_biblioteca.png")))
        itemlist.append(Item(channel="biblioteca", action="update_biblio", folder=False,
                             thumbnail=get_thumbnail_path("thumb_biblioteca.png"),
                             title="   Buscar nuevos episodios y actualizar biblioteca"))

    itemlist.append(Item(channel=CHANNELNAME, title="   Añadir o Actualizar canal/conector desde una URL",
                         action="menu_addchannels"))
    itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))

    itemlist.append(Item(channel=CHANNELNAME, title="Activar/desactivar canales",
                         action="conf_tools", folder=False, extra="channels_onoff",
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))
    itemlist.append(Item(channel=CHANNELNAME, title="Ajustes por canales",
                         action="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))

    # Inicio - Canales configurables
    import channelselector
    from core import channeltools
    channel_list = channelselector.filterchannels("all")

    for channel in channel_list:
        channel_parameters = channeltools.get_channel_parameters(channel.channel)

        if channel_parameters["has_settings"]:
            itemlist.append(Item(channel=CHANNELNAME, title="   Configuración del canal '%s'" % channel.title,
                                 action="channel_config", config=channel.channel, folder=False,
                                 thumbnail=channel.thumbnail))
    # Fin - Canales configurables

    itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False,
                         thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))
    itemlist.append(Item(channel=CHANNELNAME, title="Otras herramientas", action="submenu_tools",
                         folder=True, thumbnail=get_thumbnail_path("thumb_configuracion_0.png")))

    return itemlist