コード例 #1
0
def start(itemlist, item):
    '''
    Main method from which the links are automatically reproduced
    - In case the option to activate it will use the options defined by the user.
    - Otherwise it will try to reproduce any link that has the preferred language.

    :param itemlist: list (list of items ready to play, ie with action = 'play')
    :param item: item (the main item of the channel)
    :return: try to auto-reproduce, in case of failure it returns the itemlist that it received in the beginning
    '''

    if item.global_search:
        return itemlist
    logger.debug()

    global PLAYED
    PLAYED = False

    base_item = item

    if not config.is_xbmc():
        return itemlist

    if config.get_setting('autoplay'):
        url_list_valid = []
        autoplay_list = []
        autoplay_b = []
        favorite_quality = []
        favorite_servers = []
        blacklisted_servers = config.get_setting("black_list",
                                                 server='servers')
        if not blacklisted_servers: blacklisted_servers = []

        from core import servertools
        servers_list = list(servertools.get_servers_list().items())
        for server, server_parameters in servers_list:
            if config.get_setting('favorites_servers_list', server=server):
                favorite_servers.append(server.lower())

        if not favorite_servers:
            config.set_setting('favorites_servers_list', [], server='servers')
            favorite_servers = []
        else:
            favorite_servers = list(
                set(favorite_servers) - set(blacklisted_servers))

        # Save the current value of "Action and Player Mode" in preferences
        user_config_setting_action = config.get_setting("default_action")
        # user_config_setting_player = config.get_setting("player_mode")

        # Enable the "View in high quality" action (if the server returns more than one quality, eg gdrive)
        if not user_config_setting_action:
            config.set_setting("default_action", 2)

        # if user_config_setting_player != 0: config.set_setting("player_mode", 0)

        # Priorities when ordering itemlist:
        #       0: Servers and qualities
        #       1: Qualities and servers
        #       2: Servers only
        #       3: Only qualities
        #       4: Do not order
        if config.get_setting('favorites_servers'
                              ) and favorite_servers and config.get_setting(
                                  'default_action'):
            priority = 0  # 0: Servers and qualities or 1: Qualities and servers
        elif config.get_setting('favorites_servers') and favorite_servers:
            priority = 2  # Servers only
        elif config.get_setting('default_action'):
            priority = 3  # Only qualities
        else:
            priority = 4  # Do not order

        if config.get_setting('default_action') == 1:
            quality_list.reverse()
        favorite_quality = quality_list

        for item in itemlist:
            autoplay_elem = dict()
            b_dict = dict()

            # We check that it is a video item
            if 'server' not in item:
                continue

            if item.server.lower() in blacklisted_servers:
                continue

            # If it does not have a defined quality, it assigns a 'default' quality.
            if item.quality.lower() not in quality_list:
                item.quality = 'default'
            # The list for custom settings is created

            if priority < 2:  # 0: Servers and qualities or 1: Qualities and servers

                # if the server and the quality are not in the favorites lists or the url is repeated, we discard the item
                if item.server.lower(
                ) not in favorite_servers or item.quality.lower(
                ) not in favorite_quality or item.url in url_list_valid:
                    item.type_b = True
                    item.play_from = base_item.play_from
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_server"] = favorite_servers.index(
                    item.server.lower())
                autoplay_elem["indice_quality"] = favorite_quality.index(
                    item.quality.lower())

            elif priority == 2:  # Servers only

                # if the server is not in the favorites list or the url is repeated, we discard the item
                if item.server.lower(
                ) not in favorite_servers or item.url in url_list_valid:
                    item.type_b = True
                    item.play_from = base_item.play_from
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_server"] = favorite_servers.index(
                    item.server.lower())

            elif priority == 3:  # Only qualities

                # if the quality is not in the favorites list or the url is repeated, we discard the item
                if item.quality.lower(
                ) not in favorite_quality or item.url in url_list_valid:
                    item.type_b = True
                    item.play_from = base_item.play_from
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_quality"] = favorite_quality.index(
                    item.quality.lower())

            else:  # Do not order

                # if the url is repeated, we discard the item
                item.play_from = base_item.play_from
                if item.url in url_list_valid:
                    continue

            # If the item reaches here we add it to the list of valid urls and to autoplay_list
            url_list_valid.append(item.url)
            item.plan_b = True
            item.play_from = base_item.play_from
            autoplay_elem['videoitem'] = item
            autoplay_list.append(autoplay_elem)

        # We order according to priority
        if priority == 0:
            autoplay_list.sort(key=lambda orden: (
                (orden['indice_server'], orden['indice_quality']))
                               )  # Servers and qualities
        elif priority == 1:
            autoplay_list.sort(key=lambda orden:
                               (orden['indice_quality'], orden['indice_server']
                                ))  # Qualities and servers
        elif priority == 2:
            autoplay_list.sort(key=lambda orden:
                               (orden['indice_server']))  # Servers only
        elif priority == 3:
            autoplay_list.sort(key=lambda orden:
                               (orden['indice_quality']))  # Only qualities

        logger.debug('PRIORITY', priority, autoplay_list)

        # if quality priority is active
        if priority == 0 and config.get_setting('quality_priority'):
            max_quality = autoplay_list[0][
                "indice_quality"] if autoplay_list and "indice_quality" in autoplay_list[
                    0] else 0
            for n, item in enumerate(itemlist):
                if 'server' not in item:
                    continue

                if item.server.lower() in blacklisted_servers:
                    continue

                # If it does not have a defined quality, it assigns a 'default' quality.
                if item.quality == '':
                    item.quality = 'default'

                if favorite_quality.index(item.quality.lower()) < max_quality:
                    item.type_b = False
                    autoplay_elem["indice_server"] = n
                    autoplay_elem["indice_quality"] = favorite_quality.index(
                        item.quality.lower())
                    autoplay_elem['videoitem'] = item
                    autoplay_list.append(autoplay_elem)
            autoplay_list.sort(key=lambda orden: (orden['indice_quality'],
                                                  orden['indice_server']))

        # Plan b is prepared, in case it is active the non-favorite elements are added at the end
        # try: plan_b = settings_node['plan_b']
        # except:
        plan_b = True
        text_b = ''
        if plan_b: autoplay_list.extend(autoplay_b)
        # If there are elements in the autoplay list, an attempt is made to reproduce each element, until one is found or all fail.

        if autoplay_list or (plan_b and autoplay_b):

            max_intentos = 5
            max_intentos_servers = {}

            # If something is playing it stops playing
            if platformtools.is_playing():
                platformtools.stop_video()

            for autoplay_elem in autoplay_list:
                play_item = Item
                channel_id = autoplay_elem['videoitem'].channel
                if autoplay_elem['videoitem'].channel == 'videolibrary':
                    channel_id = autoplay_elem['videoitem'].contentChannel

                # If it is not a favorite element if you add the text plan b
                if autoplay_elem['videoitem'].type_b:
                    text_b = '(Plan B)'
                if not platformtools.is_playing() and not PLAYED:
                    videoitem = autoplay_elem['videoitem']
                    if videoitem.server.lower() not in max_intentos_servers:
                        max_intentos_servers[
                            videoitem.server.lower()] = max_intentos

                    # If the maximum number of attempts of this server have been reached, we jump to the next
                    if max_intentos_servers[videoitem.server.lower()] == 0:
                        continue

                    lang = " "
                    if hasattr(videoitem,
                               'language') and videoitem.language != "":
                        lang = " '%s' " % videoitem.language
                    name = servername(videoitem.server)
                    platformtools.dialog_notification(
                        "AutoPlay %s" % text_b,
                        "%s%s%s" % (name, lang, videoitem.quality.upper()),
                        sound=False)

                    # Try to play the links If the channel has its own play method, use it
                    try:
                        channel = __import__('channels.%s' % channel_id, None,
                                             None,
                                             ["channels.%s" % channel_id])
                    except:
                        channel = __import__('specials.%s' % channel_id, None,
                                             None,
                                             ["specials.%s" % channel_id])
                    if hasattr(channel, 'play'):
                        resolved_item = getattr(channel, 'play')(videoitem)
                        if len(resolved_item) > 0:
                            if isinstance(resolved_item[0], list):
                                videoitem.video_urls = resolved_item
                            else:
                                videoitem = resolved_item[0]

                    play_item.autoplay = True
                    # If not directly reproduce and mark as seen
                    # Check if the item comes from the video library
                    try:
                        if base_item.contentChannel == 'videolibrary' or base_item.nfo:
                            # Fill the video with the data of the main item and play
                            play_item = base_item.clone(**videoitem.__dict__)
                            platformtools.play_video(play_item, autoplay=True)
                        else:
                            # If it doesn't come from the video library, just play
                            platformtools.play_video(videoitem, autoplay=True)
                    except:
                        pass
                    sleep(3)
                    try:
                        if platformtools.is_playing():
                            PLAYED = True
                            break
                    except:
                        logger.debug(str(len(autoplay_list)))

                    # If we have come this far, it is because it could not be reproduced
                    max_intentos_servers[videoitem.server.lower()] -= 1

                    # If the maximum number of attempts of this server has been reached, ask if we want to continue testing or ignore it.
                    if max_intentos_servers[videoitem.server.lower()] == 0:
                        text = config.get_localized_string(60072) % name
                        if not platformtools.dialog_yesno(
                                "AutoPlay", text,
                                config.get_localized_string(60073)):
                            max_intentos_servers[
                                videoitem.server.lower()] = max_intentos

                    # If there are no items in the list, it is reported
                    if autoplay_elem == autoplay_list[-1]:
                        platformtools.dialog_notification(
                            'AutoPlay',
                            config.get_localized_string(60072) % name)

        else:
            platformtools.dialog_notification(
                config.get_localized_string(60074),
                config.get_localized_string(60075))

        # Restore if necessary the previous value of "Action and Player Mode" in preferences
        if not user_config_setting_action:
            config.set_setting("default_action", user_config_setting_action)
        # if user_config_setting_player != 0: config.set_setting("player_mode", user_config_setting_player)

    return itemlist
コード例 #2
0
def start(itemlist, item):
    '''
    Metodo principal desde donde se reproduce automaticamente los enlaces
    - En caso la opcion de personalizar activa utilizara las opciones definidas por el usuario.
    - En caso contrario intentara reproducir cualquier enlace que cuente con el idioma preferido.

    :param itemlist: list (lista de items listos para reproducir, o sea con action='play')
    :param item: item (el item principal del canal)
    :return: intenta autoreproducir, en caso de fallar devuelve el itemlist que recibio en un principio
    '''
    logger.info()

    global PLAYED
    global autoplay_node
    PLAYED = False

    base_item = item

    if not config.is_xbmc():
        #platformtools.dialog_notification('AutoPlay ERROR', 'Sólo disponible para XBMC/Kodi')
        return itemlist

    if not autoplay_node:
        # Obtiene el nodo AUTOPLAY desde el json
        autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')

    channel_id = item.channel
    if item.channel == 'videolibrary':
        autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')
        channel_id = item.contentChannel
    try:
        active = autoplay_node['status']
    except:
        active = is_active(item.channel)

    if not channel_id in autoplay_node or not active:
        return itemlist

    # Agrega servidores y calidades que no estaban listados a autoplay_node
    new_options = check_value(channel_id, itemlist)

    # Obtiene el nodo del canal desde autoplay_node
    channel_node = autoplay_node.get(channel_id, {})
    # Obtiene los ajustes des autoplay para este canal
    settings_node = channel_node.get('settings', {})

    if get_setting('autoplay') or settings_node['active']:
        url_list_valid = []
        autoplay_list = []
        autoplay_b = []
        favorite_langs = []
        favorite_servers = []
        favorite_quality = []

        #2nd lang, vemos si se quiere o no filtrar
        status_language = config.get_setting("filter_languages", channel_id)

        # Guarda el valor actual de "Accion y Player Mode" en preferencias
        user_config_setting_action = config.get_setting("default_action")
        user_config_setting_player = config.get_setting("player_mode")
        # Habilita la accion "Ver en calidad alta" (si el servidor devuelve más de una calidad p.e. gdrive)
        if user_config_setting_action != 2:
            config.set_setting("default_action", 2)
        if user_config_setting_player != 0:
            config.set_setting("player_mode", 0)

        # Informa que AutoPlay esta activo
        #platformtools.dialog_notification('AutoPlay Activo', '', sound=False)

        # Prioridades a la hora de ordenar itemlist:
        #       0: Servidores y calidades
        #       1: Calidades y servidores
        #       2: Solo servidores
        #       3: Solo calidades
        #       4: No ordenar
        if (settings_node['custom_servers']
                and settings_node['custom_quality']):
            priority = settings_node[
                'priority']  # 0: Servidores y calidades o 1: Calidades y servidores
        elif settings_node['custom_servers']:
            priority = 2  # Solo servidores
        elif settings_node['custom_quality']:
            priority = 3  # Solo calidades
        else:
            priority = 4  # No ordenar

        # Obtiene las listas servidores, calidades disponibles desde el nodo del json de AutoPlay
        server_list = channel_node.get('servers', [])
        for server in server_list:
            server = server.lower()
        quality_list = channel_node.get('quality', [])

        # Si no se definen calidades la se asigna default como calidad unica
        if len(quality_list) == 0:
            quality_list = ['default']

        # Se guardan los textos de cada servidor y calidad en listas p.e. favorite_servers = ['openload',
        # 'streamcloud']
        for num in range(1, 4):
            favorite_servers.append(
                channel_node['servers'][settings_node['server_%s' %
                                                      num]].lower())
            favorite_quality.append(
                channel_node['quality'][settings_node['quality_%s' % num]])

        # Se filtran los enlaces de itemlist y que se correspondan con los valores de autoplay
        for n, item in enumerate(itemlist):
            autoplay_elem = dict()
            b_dict = dict()

            # Comprobamos q se trata de un item de video
            if 'server' not in item:
                continue
            #2nd lang lista idiomas
            if item.language not in favorite_langs:
                favorite_langs.append(item.language)

            # Agrega la opcion configurar AutoPlay al menu contextual
            if 'context' not in item:
                item.context = list()
            if not [x for x in context if x['action'] == 'autoplay_config']:
                item.context.append({
                    "title": config.get_localized_string(60071),
                    "action": "autoplay_config",
                    "channel": "autoplay",
                    "from_channel": channel_id
                })

            # Si no tiene calidad definida le asigna calidad 'default'
            if item.quality == '':
                item.quality = 'default'

            # Se crea la lista para configuracion personalizada
            if priority < 2:  # 0: Servidores y calidades o 1: Calidades y servidores

                # si el servidor y la calidad no se encuentran en las listas de favoritos o la url esta repetida,
                # descartamos el item
                if item.server.lower() not in favorite_servers or item.quality not in favorite_quality \
                        or item.url in url_list_valid:
                    item.type_b = True
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_lang"] = favorite_langs.index(
                    item.language)
                autoplay_elem["indice_server"] = favorite_servers.index(
                    item.server.lower())
                autoplay_elem["indice_quality"] = favorite_quality.index(
                    item.quality)

            elif priority == 2:  # Solo servidores

                # si el servidor no se encuentra en la lista de favoritos o la url esta repetida,
                # descartamos el item
                if item.server.lower(
                ) not in favorite_servers or item.url in url_list_valid:
                    item.type_b = True
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_lang"] = favorite_langs.index(
                    item.language)
                autoplay_elem["indice_server"] = favorite_servers.index(
                    item.server.lower())

            elif priority == 3:  # Solo calidades

                # si la calidad no se encuentra en la lista de favoritos o la url esta repetida,
                # descartamos el item
                if item.quality not in favorite_quality or item.url in url_list_valid:
                    item.type_b = True
                    b_dict['videoitem'] = item
                    autoplay_b.append(b_dict)
                    continue
                autoplay_elem["indice_lang"] = favorite_langs.index(
                    item.language)
                autoplay_elem["indice_quality"] = favorite_quality.index(
                    item.quality)

            else:  # No ordenar

                # si la url esta repetida, descartamos el item
                if item.url in url_list_valid:
                    continue

            # Si el item llega hasta aqui lo añadimos al listado de urls validas y a autoplay_list
            url_list_valid.append(item.url)
            item.plan_b = True
            autoplay_elem['videoitem'] = item
            # autoplay_elem['server'] = item.server
            # autoplay_elem['quality'] = item.quality
            autoplay_list.append(autoplay_elem)

        # Ordenamos segun la prioridad
        if priority == 0:  # Servidores y calidades
            autoplay_list.sort(key=lambda orden: (orden['indice_lang'], orden[
                'indice_server'], orden['indice_quality']))

        elif priority == 1:  # Calidades y servidores
            autoplay_list.sort(key=lambda orden: (orden['indice_lang'], orden[
                'indice_quality'], orden['indice_server']))

        elif priority == 2:  # Solo servidores
            autoplay_list.sort(key=lambda orden:
                               (orden['indice_lang'], orden['indice_server']))

        elif priority == 3:  # Solo calidades
            autoplay_list.sort(key=lambda orden:
                               (orden['indice_lang'], orden['indice_quality']))

        # Se prepara el plan b, en caso de estar activo se agregan los elementos no favoritos al final
        try:
            plan_b = settings_node['plan_b']
        except:
            plan_b = True
        text_b = ''
        if plan_b:
            autoplay_list.extend(autoplay_b)
        # Si hay elementos en la lista de autoplay se intenta reproducir cada elemento, hasta encontrar uno
        # funcional o fallen todos

        if autoplay_list or (plan_b and autoplay_b):

            #played = False
            max_intentos = 5
            max_intentos_servers = {}

            # Si se esta reproduciendo algo detiene la reproduccion
            if platformtools.is_playing():
                platformtools.stop_video()

            for autoplay_elem in autoplay_list:
                play_item = Item

                # Si no es un elemento favorito si agrega el texto plan b
                if autoplay_elem['videoitem'].type_b:
                    text_b = '(Plan B)'
                if not platformtools.is_playing() and not PLAYED:
                    videoitem = autoplay_elem['videoitem']
                    if videoitem.server.lower() not in max_intentos_servers:
                        max_intentos_servers[
                            videoitem.server.lower()] = max_intentos

                    # Si se han alcanzado el numero maximo de intentos de este servidor saltamos al siguiente
                    if max_intentos_servers[videoitem.server.lower()] == 0:
                        continue

                    lang = " "
                    if hasattr(videoitem,
                               'language') and videoitem.language != "":
                        lang = " '%s' " % videoitem.language

                    platformtools.dialog_notification(
                        "AutoPlay %s" % text_b,
                        "%s%s%s" % (videoitem.server.upper(), lang,
                                    videoitem.quality.upper()),
                        sound=False)
                    # TODO videoitem.server es el id del server, pero podria no ser el nombre!!!

                    # Intenta reproducir los enlaces
                    # Si el canal tiene metodo play propio lo utiliza
                    channel = __import__('channels.%s' % channel_id, None,
                                         None, ["channels.%s" % channel_id])
                    if hasattr(channel, 'play'):
                        resolved_item = getattr(channel, 'play')(videoitem)
                        if len(resolved_item) > 0:
                            if isinstance(resolved_item[0], list):
                                videoitem.video_urls = resolved_item
                            else:
                                videoitem = resolved_item[0]

                    # Si no directamente reproduce y marca como visto

                    # Verifica si el item viene de la videoteca
                    try:
                        if base_item.contentChannel == 'videolibrary':
                            # Marca como visto
                            from platformcode import xbmc_videolibrary
                            xbmc_videolibrary.mark_auto_as_watched(base_item)
                            # Rellena el video con los datos del item principal y reproduce
                            play_item = base_item.clone(url=videoitem)
                            platformtools.play_video(play_item.url,
                                                     autoplay=True)
                        else:
                            # Si no viene de la videoteca solo reproduce
                            platformtools.play_video(videoitem, autoplay=True)
                    except:
                        pass
                    sleep(3)
                    try:
                        if platformtools.is_playing():
                            PLAYED = True
                            break
                    except:
                        logger.debug(str(len(autoplay_list)))

                    # Si hemos llegado hasta aqui es por q no se ha podido reproducir
                    max_intentos_servers[videoitem.server.lower()] -= 1

                    # Si se han alcanzado el numero maximo de intentos de este servidor
                    # preguntar si queremos seguir probando o lo ignoramos
                    if max_intentos_servers[videoitem.server.lower()] == 0:
                        text = config.get_localized_string(
                            60072) % videoitem.server.upper()
                        if not platformtools.dialog_yesno(
                                "AutoPlay", text,
                                config.get_localized_string(60073)):
                            max_intentos_servers[
                                videoitem.server.lower()] = max_intentos

                    # Si no quedan elementos en la lista se informa
                    if autoplay_elem == autoplay_list[-1]:
                        platformtools.dialog_notification(
                            'AutoPlay',
                            config.get_localized_string(60072) %
                            videoitem.server.upper())

        else:
            platformtools.dialog_notification(
                config.get_localized_string(60074),
                config.get_localized_string(60075))
        if new_options:
            platformtools.dialog_notification(
                "AutoPlay", config.get_localized_string(60076), sound=False)

        # Restaura si es necesario el valor previo de "Accion y Player Mode" en preferencias
        if user_config_setting_action != 2:
            config.set_setting("default_action", user_config_setting_action)
        if user_config_setting_player != 0:
            config.set_setting("player_mode", user_config_setting_player)

    return itemlist
コード例 #3
0
def start(itemlist, item):
    '''
    Metodo principal desde donde se reproduce automaticamente los enlaces
    - En caso la opcion de personalizar activa utilizara las opciones definidas por el usuario.
    - En caso contrario intentara reproducir cualquier enlace que cuente con el idioma preferido.

    :param itemlist: list (lista de items listos para reproducir, o sea con action='play')
    :param item: item (el item principal del canal)
    :return: intenta autoreproducir, en caso de fallar devuelve el itemlist que recibio en un principio
    '''
    logger.info()
    global autoplay_node

    if not config.is_xbmc():
        platformtools.dialog_notification('AutoPlay ERROR',
                                          'Sólo disponible para XBMC/Kodi')
        return itemlist
    else:
        if not autoplay_node:
            # Obtiene el nodo AUTOPLAY desde el json
            autoplay_node = jsontools.get_node_from_data_json(
                'autoplay', 'AUTOPLAY')

        # Agrega servidores y calidades que no estaban listados a autoplay_node
        new_options = check_value(item.channel, itemlist)

        # Obtiene el nodo del canal desde autoplay_node
        channel_node = autoplay_node.get(item.channel, {})
        # Obtiene los ajustes des autoplay para este canal
        settings_node = channel_node.get('settings', {})

        if settings_node['active']:
            url_list_valid = []
            autoplay_list = []
            favorite_servers = []
            favorite_quality = []

            # Guarda el valor actual de "Accion al seleccionar vídeo:" en preferencias
            user_config_setting = config.get_setting("default_action")
            # Habilita la accion "Ver en calidad alta" (si el servidor devuelve más de una calidad p.e. gdrive)
            if user_config_setting != 2:
                config.set_setting("default_action", 2)

            # Informa que AutoPlay esta activo
            platformtools.dialog_notification('AutoPlay Activo',
                                              '',
                                              sound=False)

            # Prioridades a la hora de ordenar itemlist:
            #       0: Servidores y calidades
            #       1: Calidades y servidores
            #       2: Solo servidores
            #       3: Solo calidades
            #       4: No ordenar
            if settings_node['custom_servers'] and settings_node[
                    'custom_quality']:
                priority = settings_node[
                    'priority']  # 0: Servidores y calidades o 1: Calidades y servidores
            elif settings_node['custom_servers']:
                priority = 2  # Solo servidores
            elif settings_node['custom_quality']:
                priority = 3  # Solo calidades
            else:
                priority = 4  # No ordenar

            # Obtiene las listas servidores, calidades disponibles desde el nodo del json de AutoPlay
            server_list = channel_node.get('servers', [])
            quality_list = channel_node.get('quality', [])

            # Se guardan los textos de cada servidor y calidad en listas p.e. favorite_servers = ['openload',
            # 'streamcloud']
            for num in range(1, 4):
                favorite_servers.append(
                    channel_node['servers'][settings_node['server_%s' % num]])
                favorite_quality.append(
                    channel_node['quality'][settings_node['quality_%s' % num]])

            # Se filtran los enlaces de itemlist y que se correspondan con los valores de autoplay
            for item in itemlist:
                autoplay_elem = dict()

                # Comprobamos q se trata de un item de video
                if 'server' not in item:
                    continue

                # Agrega la opcion configurar AutoPlay al menu contextual
                if 'context' not in item:
                    item.context = list()
                if not filter(lambda x: x['action'] == 'autoplay_config',
                              context):
                    item.context.append({
                        "title": "Configurar AutoPlay",
                        "action": "autoplay_config",
                        "channel": "autoplay",
                        "from_channel": item.channel
                    })

                # Si no tiene calidad definida le asigna calidad 'default'
                if item.quality == '':
                    item.quality = 'default'

                # Se crea la lista para configuracion personalizada
                if priority < 2:  # 0: Servidores y calidades o 1: Calidades y servidores

                    # si el servidor y la calidad no se encuentran en las listas de favoritos o la url esta repetida,
                    # descartamos el item
                    if item.server not in favorite_servers or item.quality not in favorite_quality \
                            or item.url in url_list_valid:
                        continue
                    autoplay_elem["indice_server"] = favorite_servers.index(
                        item.server)
                    autoplay_elem["indice_quality"] = favorite_quality.index(
                        item.quality)

                elif priority == 2:  # Solo servidores

                    # si el servidor no se encuentra en la lista de favoritos o la url esta repetida,
                    # descartamos el item
                    if item.server not in favorite_servers or item.url in url_list_valid:
                        continue
                    autoplay_elem["indice_server"] = favorite_servers.index(
                        item.server)

                elif priority == 3:  # Solo calidades

                    # si la calidad no se encuentra en la lista de favoritos o la url esta repetida,
                    # descartamos el item
                    if item.quality not in favorite_quality or item.url in url_list_valid:
                        continue
                    autoplay_elem["indice_quality"] = favorite_quality.index(
                        item.quality)

                else:  # No ordenar

                    # si la url esta repetida, descartamos el item
                    if item.url in url_list_valid:
                        continue

                # Si el item llega hasta aqui lo añadimos al listado de urls validas y a autoplay_list
                url_list_valid.append(item.url)
                autoplay_elem['videoitem'] = item
                #autoplay_elem['server'] = item.server
                #autoplay_elem['quality'] = item.quality
                autoplay_list.append(autoplay_elem)

            # Ordenamos segun la prioridad
            if priority == 0:  # Servidores y calidades
                autoplay_list.sort(key=lambda orden: (orden['indice_server'],
                                                      orden['indice_quality']))

            elif priority == 1:  # Calidades y servidores
                autoplay_list.sort(key=lambda orden: (orden['indice_quality'],
                                                      orden['indice_server']))

            elif priority == 2:  # Solo servidores
                autoplay_list.sort(key=lambda orden: orden['indice_server'])

            elif priority == 3:  # Solo calidades
                autoplay_list.sort(key=lambda orden: orden['indice_quality'])

            # Si hay elementos en la lista de autoplay se intenta reproducir cada elemento, hasta encontrar uno
            # funcional o fallen todos
            if autoplay_list:
                played = False
                max_intentos = 5
                max_intentos_servers = {}

                # Si se esta reproduciendo algo detiene la reproduccion
                if platformtools.is_playing():
                    platformtools.stop_video()

                for autoplay_elem in autoplay_list:
                    if not platformtools.is_playing() and not played:
                        videoitem = autoplay_elem['videoitem']

                        if videoitem.server not in max_intentos_servers:
                            max_intentos_servers[
                                videoitem.server] = max_intentos

                        # Si se han alcanzado el numero maximo de intentos de este servidor saltamos al siguiente
                        if max_intentos_servers[videoitem.server] == 0:
                            continue

                        lang = " "
                        if hasattr(videoitem,
                                   'language') and videoitem.language != "":
                            lang = " '%s' " % videoitem.language

                        platformtools.dialog_notification(
                            "AutoPlay",
                            "%s%s%s" % (videoitem.server.upper(), lang,
                                        videoitem.quality.upper()),
                            sound=False)
                        #TODO videoitem.server es el id del server, pero podria no ser el nombre!!!

                        # Intenta reproducir los enlaces
                        # Si el canal tiene metodo play propio lo utiliza
                        channel = __import__('channels.%s' % item.channel,
                                             None, None,
                                             ["channels.%s" % item.channel])
                        if hasattr(channel, 'play'):
                            resolved_item = getattr(channel, 'play')(videoitem)
                            if len(resolved_item) > 0:
                                if isinstance(resolved_item[0], list):
                                    videoitem.video_urls = resolved_item
                                else:
                                    videoitem = resolved_item[0]

                        # si no directamente reproduce
                        platformtools.play_video(videoitem)

                        try:
                            if platformtools.is_playing():
                                played = True
                                break
                        except:  # TODO evitar el informe de que el conector fallo o el video no se encuentra
                            logger.debug(str(len(autoplay_list)))

                        # Si hemos llegado hasta aqui es por q no se ha podido reproducir
                        max_intentos_servers[videoitem.server] -= 1

                        # Si se han alcanzado el numero maximo de intentos de este servidor
                        # preguntar si queremos seguir probando o lo ignoramos
                        if max_intentos_servers[videoitem.server] == 0:
                            text = "Parece que los enlaces de %s no estan funcionando." % videoitem.server.upper(
                            )
                            if not platformtools.dialog_yesno(
                                    "AutoPlay", text,
                                    "¿Desea ignorar todos los enlaces de este servidor?"
                            ):
                                max_intentos_servers[
                                    videoitem.server] = max_intentos

            else:
                platformtools.dialog_notification('AutoPlay No Fue Posible',
                                                  'No Hubo Coincidencias')
            if new_options:
                platformtools.dialog_notification(
                    "AutoPlay", "Nueva Calidad/Servidor disponible en la "
                    "configuracion",
                    sound=False)

            # Restaura si es necesario el valor previo de "Accion al seleccionar vídeo:" en preferencias
            if user_config_setting != 2:
                config.set_setting("default_action", user_config_setting)

        # devuelve la lista de enlaces para la eleccion manual
        return itemlist
コード例 #4
0
ファイル: autoplay.py プロジェクト: aandroide/addon
def start(itemlist, item):
    '''
    Main method from which the links are automatically reproduced
    - In case the option to activate it will use the options defined by the user.
    - Otherwise it will try to reproduce any link that has the preferred language.

    :param itemlist: list (list of items ready to play, ie with action = 'play')
    :param item: item (the main item of the channel)
    :return: try to auto-reproduce, in case of failure it returns the itemlist that it received in the beginning
    '''

    if item.global_search or item.from_action or item.contentAction:  # from_action means that's a special function calling this (ex: add to videolibrary)
        return itemlist
    if len([s for s in itemlist if s.server]) == 1:
        return itemlist
    logger.debug()

    global PLAYED
    PLAYED = False

    base_item = item

    if not config.is_xbmc():
        return itemlist

    import xbmc
    control_info = xbmc.getInfoLabel('Container.FolderPath')
    if control_info:
        control_item = Item().fromurl(control_info)
        if control_item.action == item.action:
            return itemlist

    if config.get_setting('autoplay') or item.autoplay:
        # Save the current value of "Action and Player Mode" in preferences
        user_config_setting_action = config.get_setting("default_action")
        # user_config_setting_player = config.get_setting("player_mode")

        # Enable the "View in high quality" action (if the server returns more than one quality, eg gdrive)
        if not user_config_setting_action:
            config.set_setting("default_action", 2)

        from core.servertools import sort_servers
        autoplay_list = sort_servers(itemlist)

        if autoplay_list:
            max_intents = 5
            max_intents_servers = {}

            # If something is playing it stops playing
            if platformtools.is_playing():
                platformtools.stop_video()

            for autoplay_elem in autoplay_list:
                play_item = Item
                channel_id = autoplay_elem.channel
                if autoplay_elem.channel == 'videolibrary':
                    channel_id = autoplay_elem.contentChannel

                if not platformtools.is_playing() and not PLAYED:
                    videoitem = autoplay_elem
                    if videoitem.server.lower() not in max_intents_servers:
                        max_intents_servers[
                            videoitem.server.lower()] = max_intents

                    # If the maximum number of attempts of this server have been reached, we jump to the next
                    if max_intents_servers[videoitem.server.lower()] == 0:
                        continue

                    lang = " [{}]".format(
                        videoitem.language) if videoitem.language else ''
                    quality = ' [{}]'.format(
                        videoitem.quality
                    ) if videoitem.quality and videoitem.quality != 'default' else ''
                    name = servername(videoitem.server)
                    platformtools.dialog_notification('AutoPlay',
                                                      '{}{}{}'.format(
                                                          name, lang, quality),
                                                      sound=False)

                    # Try to play the links If the channel has its own play method, use it
                    try:
                        channel = __import__('channels.%s' % channel_id, None,
                                             None,
                                             ["channels.%s" % channel_id])
                    except:
                        channel = __import__('specials.%s' % channel_id, None,
                                             None,
                                             ["specials.%s" % channel_id])
                    if hasattr(channel, 'play'):
                        resolved_item = getattr(channel, 'play')(videoitem)
                        if len(resolved_item) > 0:
                            if isinstance(resolved_item[0], list):
                                videoitem.video_urls = resolved_item
                            else:
                                videoitem = resolved_item[0]

                    play_item.autoplay = True
                    # If not directly reproduce and mark as seen
                    # Check if the item comes from the video library
                    try:
                        if base_item.contentChannel == 'videolibrary' or base_item.nfo:
                            # Fill the video with the data of the main item and play
                            play_item = base_item.clone(**videoitem.__dict__)
                            platformtools.play_video(play_item, autoplay=True)
                        else:
                            videoitem.window = base_item.window
                            # If it doesn't come from the video library, just play
                            platformtools.play_video(videoitem, autoplay=True)
                    except:
                        pass
                    # sleep(3)
                    try:
                        if platformtools.is_playing():
                            PLAYED = True
                            break
                    except:
                        logger.debug(str(len(autoplay_list)))

                    # If we have come this far, it is because it could not be reproduced
                    max_intents_servers[videoitem.server.lower()] -= 1

                    # If the maximum number of attempts of this server has been reached, ask if we want to continue testing or ignore it.
                    if max_intents_servers[videoitem.server.lower()] == 0:
                        text = config.get_localized_string(60072) % name
                        if not platformtools.dialog_yesno(
                                "AutoPlay", text,
                                config.get_localized_string(60073)):
                            max_intents_servers[
                                videoitem.server.lower()] = max_intents

                    # If there are no items in the list, it is reported
                    if autoplay_elem == autoplay_list[
                            -1] and autoplay_elem.server != 'torrent':
                        platformtools.dialog_notification(
                            'AutoPlay',
                            config.get_localized_string(60072) % name)

        else:
            platformtools.dialog_notification(
                config.get_localized_string(60074),
                config.get_localized_string(60075))

        # Restore if necessary the previous value of "Action and Player Mode" in preferences
        if not user_config_setting_action:
            config.set_setting("default_action", user_config_setting_action)
        # if user_config_setting_player != 0: config.set_setting("player_mode", user_config_setting_player)

    return itemlist