Пример #1
0
def new_search(item):
    logger.info()

    itemlist = []

    last_search = channeltools.get_channel_setting('Last_searched', 'search',
                                                   '')
    searched_text = platformtools.dialog_input(default=last_search,
                                               heading='Alfa (Busqueda)')

    if not searched_text:
        return

    channeltools.set_channel_setting('Last_searched', searched_text, 'search')
    searched_text = searched_text.replace("+", " ")

    if item.mode == 'person':
        item.searched_text = searched_text
        return actor_list(item)

    if item.mode != 'all':
        tmdb_info = tmdb.Tmdb(texto_buscado=searched_text,
                              tipo=item.mode.replace('show', ''))
        results = tmdb_info.results
        for result in results:
            result = tmdb_info.get_infoLabels(result, origen=result)
            if item.mode == 'movie':
                title = result['title']
            else:
                title = result['name']
                item.mode = 'tvshow'

            thumbnail = result.get('thumbnail', '')
            fanart = result.get('fanart', '')

            new_item = Item(channel=item.channel,
                            action='channel_search',
                            title=title,
                            text=searched_text,
                            thumbnail=thumbnail,
                            fanart=fanart,
                            mode=item.mode,
                            infoLabels=result)

            if item.mode == 'movie':
                new_item.contentTitle = result['title']
            else:
                new_item.contentSerieName = result['name']

            itemlist.append(new_item)

    if item.mode == 'all' or not itemlist:
        itemlist = channel_search(
            Item(channel=item.channel,
                 title=searched_text,
                 text=searched_text,
                 mode='all',
                 infoLabels={}))

    return itemlist
Пример #2
0
    def lastSearch(self):
        logger.debug()
        if not self.item.text:
            if self.item.contentTitle:
                self.item.text = self.item.contentTitle
            elif self.item.contentSerieName:
                self.item.text = self.item.contentSerieName

            if not self.item.text:
                if config.get_setting('last_search'):
                    last_search = channeltools.get_channel_setting(
                        'Last_searched', 'search', '')
                else:
                    last_search = ''
                if not self.item.text:
                    self.item.text = platformtools.dialog_input(
                        default=last_search, heading='')
                if self.item.text:
                    channeltools.set_channel_setting('Last_searched',
                                                     self.item.text, 'search')
                    if self.item.mode == 'all':
                        save_search(self.item.text)
        else:
            if self.item.context:
                del self.item.context  # needed for preventing same content twice in saved search
            save_search(self.item.__dict__)
Пример #3
0
 def lastSearch(self):
     logger.debug()
     if not self.item.text:
         if config.get_setting('last_search'): last_search = channeltools.get_channel_setting('Last_searched', 'search', '')
         else: last_search = ''
         if not self.item.text: self.item.text = platformtools.dialog_input(default=last_search, heading='')
         if self.item.text: channeltools.set_channel_setting('Last_searched', self.item.text, 'search')
Пример #4
0
def config(item):
    from platformcode import platformtools
    from core import channeltools
    dialog = platformtools.dialog_yesno("Configuración Info Partido", "       Selecciona el modo de inicio", yeslabel="Ventana", nolabel="Pantalla Completa")
    if dialog == 1:
        channeltools.set_channel_setting("modo", False, "futbol_window")
    elif dialog == 0:
        channeltools.set_channel_setting("modo", True, "futbol_window")
Пример #5
0
def get_video_url(page_url, premium=False, video_password=""):
    logger.info("pelisalacarta.servers.realdebrid get_video_url( page_url='%s' , video_password=%s)"
                % (page_url, video_password))
    
    # Se comprueba si existe un token guardado y sino se ejecuta el proceso de autentificación
    token_auth = channeltools.get_channel_setting("realdebrid_token", "realdebrid")
    if token_auth is None or token_auth == "":
        if config.is_xbmc():
            token_auth = authentication()
            if token_auth == "":
                return [["REAL-DEBRID: No se ha completado el proceso de autentificación", ""]]
        else:
            return [["Es necesario activar la cuenta. Accede al menú de ayuda", ""]]

    post_link = urllib.urlencode([("link", page_url), ("password", video_password)])
    headers["Authorization"] = "Bearer %s" % token_auth
    url = "https://api.real-debrid.com/rest/1.0/unrestrict/link"
    data = scrapertools.downloadpage(url, post=post_link, headers=headers.items())
    data = jsontools.load_json(data)
    
    # Si el token es erróneo o ha caducado, se solicita uno nuevo
    if "error" in data and data["error"] == "bad_token":
        debrid_id = channeltools.get_channel_setting("realdebrid_id", "realdebrid")
        secret = channeltools.get_channel_setting("realdebrid_secret", "realdebrid")
        refresh = channeltools.get_channel_setting("realdebrid_refresh", "realdebrid")

        post_token = urllib.urlencode({"client_id": debrid_id, "client_secret": secret, "code": refresh,
                                       "grant_type": "http://oauth.net/grant_type/device/1.0"})
        renew_token = scrapertools.downloadpage("https://api.real-debrid.com/oauth/v2/token", post=post_token,
                                                headers=headers.items())
        renew_token = jsontools.load_json(renew_token)
        if not "error" in renew_token:
            token_auth = renew_token["access_token"]
            channeltools.set_channel_setting("realdebrid_token", token_auth, "realdebrid")
            headers["Authorization"] = "Bearer %s" % token_auth
            data = scrapertools.downloadpage(url, post=post_link, headers=headers.items())
            data = jsontools.load_json(data)

    if "download" in data:
        return get_enlaces(data)
    else:
        if "error" in data:
            msg = data["error"].decode("utf-8","ignore")
            msg = msg.replace("hoster_unavailable", "Servidor no disponible") \
                     .replace("unavailable_file", "Archivo no disponible") \
                     .replace("hoster_not_free", "Servidor no gratuito") \
                     .replace("bad_token", "Error en el token")
            return [["REAL-DEBRID: " + msg, ""]]
        else:
            return [["REAL-DEBRID: No se ha generado ningún enlace", ""]]
Пример #6
0
def set_setting(name, value, channel=""):
    """Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.
    
    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.fusionse\settings_channels el archivo channel_data.json
    y establece el parametro 'name' al valor indicado por 'value'. Si el archivo channel_data.json no existe busca en la carpeta channels el archivo 
    channel.xml y crea un archivo channel_data.json antes de modificar el parametro 'name'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.
    
    
    Parametros:
    name -- nombre del parametro
    value -- valor del parametro
    channel [opcional] -- nombre del canal
    
    Retorna:
    'value' en caso de que se haya podido fijar el valor y None en caso contrario
        
    """
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    else:
        try:
            __settings__.setSetting(name, value)
        except:
            # xbmc.log("[config.py] ERROR al fijar el parametro global {0}= {1}".format(name, value))
            return None

        return value
Пример #7
0
def set_setting(name, value, channel=""):
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
    canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
    channel_data.json no existe busca en la carpeta channels el archivo channel.xml y crea un archivo channel_data.json
    antes de modificar el parametro 'name'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.


    Parametros:
    name -- nombre del parametro
    value -- valor del parametro
    channel [opcional] -- nombre del canal

    Retorna:
    'value' en caso de que se haya podido fijar el valor y None en caso contrario

    """
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    else:
        try:
            __settings__.setSetting(name, value)
        except:
            # xbmc.log("[config.py] ERROR al fijar el parametro global {0}= {1}".format(name, value))
            return None

        return value
Пример #8
0
def set_setting(name, value, channel="", server=""):
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
    canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.alfa\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
    channel_data.json no existe busca en la carpeta channels el archivo channel.json y crea un archivo channel_data.json
    antes de modificar el parametro 'name'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.


    Parametros:
    name -- nombre del parametro
    value -- valor del parametro
    channel [opcional] -- nombre del canal

    Retorna:
    'value' en caso de que se haya podido fijar el valor y None en caso contrario

    """
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    elif server:
        from core import servertools
        return servertools.set_server_setting(name, value, server)
    else:
        try:
            settings_types = get_settings_types()

            if settings_types.get(name) == 'bool':
                if value:
                    new_value = "true"
                else:
                    new_value = "false"

            elif settings_types.get(name):
                new_value = str(value)

            else:
                if isinstance(value, basestring):
                    new_value = "(%s, %s)" % (type(value).__name__,
                                              repr(value))

                else:
                    new_value = "(%s, %s)" % (type(value).__name__, value)

            __settings__.setSetting(name, new_value)

        except Exception, ex:
            from core import logger
            logger.error("Error al convertir '%s' no se guarda el valor \n%s" %
                         (name, ex))
            return None

        return value
Пример #9
0
def get_video_url(page_url, premium=False, video_password=""):
    logger.info("streamondemand.servers.realdebrid get_video_url( page_url='%s' , video_password=%s)"
                % (page_url, video_password))
    
    # Se comprueba si existe un token guardado y sino se ejecuta el proceso de autentificación
    token_auth = channeltools.get_channel_setting("realdebrid_token", "realdebrid")
    if token_auth is None or token_auth == "":
        token_auth = authentication()
        if token_auth == "":
            return [["REAL-DEBRID: No se ha completado el proceso de autentificación", ""]]

    post_link = urllib.urlencode([("link", page_url), ("password", video_password)])
    headers["Authorization"] = "Bearer %s" % token_auth
    url = "https://api.real-debrid.com/rest/1.0/unrestrict/link"
    data = scrapertools.downloadpage(url, post=post_link, headers=headers.items())
    data = jsontools.load_json(data)
    
    # Si el token es erróneo o ha caducado, se solicita uno nuevo
    if "error" in data and data["error"] == "bad_token":
        debrid_id = channeltools.get_channel_setting("realdebrid_id", "realdebrid")
        secret = channeltools.get_channel_setting("realdebrid_secret", "realdebrid")
        refresh = channeltools.get_channel_setting("realdebrid_refresh", "realdebrid")

        post_token = urllib.urlencode({"client_id": debrid_id, "client_secret": secret, "code": refresh,
                                       "grant_type": "http://oauth.net/grant_type/device/1.0"})
        renew_token = scrapertools.downloadpage("https://api.real-debrid.com/oauth/v2/token", post=post_token,
                                                headers=headers.items())
        renew_token = jsontools.load_json(renew_token)
        if not "error" in renew_token:
            token_auth = renew_token["access_token"]
            channeltools.set_channel_setting("realdebrid_token", token_auth, "realdebrid")
            headers["Authorization"] = "Bearer %s" % token_auth
            data = scrapertools.downloadpage(url, post=post_link, headers=headers.items())
            data = jsontools.load_json(data)

    if "download" in data:
        return get_enlaces(data)
    else:
        if "error" in data:
            msg = data["error"].decode("utf-8","ignore")
            msg = msg.replace("hoster_unavailable", "Servidor no disponible") \
                     .replace("unavailable_file", "Archivo no disponible") \
                     .replace("hoster_not_free", "Servidor no gratuito") \
                     .replace("bad_token", "Error en el token")
            return [["REAL-DEBRID: " + msg, ""]]
        else:
            return [["REAL-DEBRID: No se ha generado ningún enlace", ""]]
Пример #10
0
def set_setting(name, value, channel="", server=""):
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
    canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.alfa\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
    channel_data.json no existe busca en la carpeta channels el archivo channel.xml y crea un archivo channel_data.json
    antes de modificar el parametro 'name'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.


    Parametros:
    name -- nombre del parametro
    value -- valor del parametro
    channel [opcional] -- nombre del canal

    Retorna:
    'value' en caso de que se haya podido fijar el valor y None en caso contrario

    """
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    elif server:
        from core import servertools
        return servertools.set_server_setting(name, value, server)
    else:
        global settings_dic

        if isinstance(value, bool):
            if value:
                value = "true"
            else:
                value = "false"
        elif isinstance(value, (int, long)):
            value = str(value)

        settings_dic[name] = value
        from xml.dom import minidom
        # Crea un Nuevo XML vacio
        new_settings = minidom.getDOMImplementation().createDocument(
            None, "settings", None)
        new_settings_root = new_settings.documentElement

        for key in settings_dic:
            nodo = new_settings.createElement("setting")
            nodo.setAttribute("value", settings_dic[key])
            nodo.setAttribute("id", key)
            new_settings_root.appendChild(nodo)

        fichero = open(configfilepath, "w")
        fichero.write(new_settings.toprettyxml(encoding='utf-8'))
        fichero.close()
        return value
Пример #11
0
def search(item):
    channel = importChannel(item)
    from core import channeltools

    if config.get_setting('last_search'):
        last_search = channeltools.get_channel_setting('Last_searched', 'search', '')
    else:
        last_search = ''

    search_text = platformtools.dialog_input(last_search)

    if search_text is not None:
        channeltools.set_channel_setting('Last_searched', search_text, 'search')
        itemlist = new_search(item.clone(text=search_text), channel)
    else:
        return

    platformtools.render_items(itemlist, item)
Пример #12
0
    def lastSearch(self):
        logger.debug()
        if not self.item.text:
            if self.item.contentTitle:
                self.item.text = self.item.contentTitle
            elif self.item.contentSerieName:
                self.item.text = self.item.contentSerieName

            if not self.item.text:
                if config.get_setting('last_search'):
                    last_search = channeltools.get_channel_setting(
                        'Last_searched', 'search', '')
                else:
                    last_search = ''
                if not self.item.text:
                    self.item.text = platformtools.dialog_input(
                        default=last_search, heading='')
                if self.item.text:
                    channeltools.set_channel_setting('Last_searched',
                                                     self.item.text, 'search')
                    from specials.search import save_search
                    save_search(self.item.text)
Пример #13
0
def authentication(item):
    logger.info("pelisalacarta.channels.ayuda authentication")
    import urllib
    from core import channeltools
    from core import jsontools
    from core import scrapertools

    itemlist = []
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'}
    client_id = "YTWNFBIJEEBP6"
    device_code = item.extra
    token = ""
    try:
        url = "https://api.real-debrid.com/oauth/v2/device/credentials?client_id=%s&code=%s" \
              % (client_id, device_code)
        data = scrapertools.downloadpage(url, headers=headers.items())
        data = jsontools.load_json(data)

        debrid_id = data["client_id"]
        secret = data["client_secret"] 

        # Se solicita el token de acceso y el de actualización para cuando el primero caduque
        post = urllib.urlencode({"client_id": debrid_id, "client_secret": secret, "code": device_code,
                                 "grant_type": "http://oauth.net/grant_type/device/1.0"})
        data = scrapertools.downloadpage("https://api.real-debrid.com/oauth/v2/token", post=post,
                                         headers=headers.items())
        data = jsontools.load_json(data)

        token = data["access_token"]
        refresh = data["refresh_token"]

        channeltools.set_channel_setting("realdebrid_id", debrid_id, "realdebrid")
        channeltools.set_channel_setting("realdebrid_secret", secret, "realdebrid")
        channeltools.set_channel_setting("realdebrid_token", token, "realdebrid")
        channeltools.set_channel_setting("realdebrid_refresh", refresh, "realdebrid")
        
    except:
        import traceback
        logger.error(traceback.format_exc())

    if token:
        itemlist.append(Item(channel=item.channel, action="", title="Cuenta activada correctamente"))
    else:
        itemlist.append(Item(channel=item.channel, action="", title="Error en el proceso de activación, vuelve a intentarlo"))

    return itemlist
Пример #14
0
def set_setting(name, value, channel="", server=""):
    """
    Sets the configuration value of the indicated parameter.

    Set 'value' as the value of the parameter 'name' in the global configuration or in the own configuration of the channel 'channel'.
    Returns the changed value or None if the assignment could not be completed.

    If the name of the channel is specified, search in the path \ addon_data \ plugin.video.kod \ settings_channels the
    channel_data.json file and set the parameter 'name' to the value indicated by 'value'. If the file
    channel_data.json does not exist look in the channels folder for the channel.json file and create a channel_data.json file before modifying the 'name' parameter.
    If the parameter 'name' does not exist, it adds it, with its value, to the corresponding file.


    Parameters:
    name - name of the parameter
    value - value of the parameter
    channel [optional] - channel name

    Returns:
    'value' if the value could be set and None otherwise

    """
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    elif server:
        from core import servertools
        return servertools.set_server_setting(name, value, server)
    else:
        try:
            if isinstance(value, bool):
                if value:
                    value = "true"
                else:
                    value = "false"

            elif isinstance(value, (int, long)):
                value = str(value)

            __settings__.setSetting(name, value)

        except Exception as ex:
            from platformcode import logger
            logger.error("Error converting '%s' value is not saved \n%s" %
                         (name, ex))
            return None

        return value
Пример #15
0
def set_setting(name, value, channel="", server=""):
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
    canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
    channel_data.json no existe busca en la carpeta channels el archivo channel.xml y crea un archivo channel_data.json
    antes de modificar el parametro 'name'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.


    Parametros:
    name -- nombre del parametro
    value -- valor del parametro
    channel [opcional] -- nombre del canal

    Retorna:
    'value' en caso de que se haya podido fijar el valor y None en caso contrario

    """
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    elif server:
        from core import servertools
        return servertools.set_server_setting(name, value, server)
    else:
        try:
            if isinstance(value, bool):
                if value:
                    value = "true"
                else:
                    value = "false"
            elif isinstance(value, (int, long)):
                value = str(value)

            import xbmcplugin
            xbmcplugin.setSetting(name, value)
        except:
            return None

        return value
Пример #16
0
def set_setting(name, value, channel=""):
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
    canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
    channel_data.json no existe busca en la carpeta channels el archivo channel.xml y crea un archivo channel_data.json
    antes de modificar el parametro 'name'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.


    Parametros:
    name -- nombre del parametro
    value -- valor del parametro
    channel [opcional] -- nombre del canal

    Retorna:
    'value' en caso de que se haya podido fijar el valor y None en caso contrario

    """
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    else:
        global settings_dic
        settings_dic[name]=value
        from xml.dom import minidom
        #Crea un Nuevo XML vacio
        new_settings = minidom.getDOMImplementation().createDocument(None, "settings", None)
        new_settings_root = new_settings.documentElement
      
        for key in settings_dic:
          nodo = new_settings.createElement("setting")
          nodo.setAttribute("value",settings_dic[key])
          nodo.setAttribute("id",key)    
          new_settings_root.appendChild(nodo)
        
        fichero = open(configfilepath, "w")
        fichero.write(new_settings.toprettyxml(encoding='utf-8'))
        fichero.close()
        return value
Пример #17
0
def set_setting(name,value,channel=""):
    if channel:
      from core import channeltools
      return channeltools.set_channel_setting(name,value, channel)
      
    else:     
      settings_dic[name]=value
      from xml.dom import minidom
      #Crea un Nuevo XML vacio
      new_settings = minidom.getDOMImplementation().createDocument(None, "settings", None)
      new_settings_root = new_settings.documentElement
      
      for key in settings_dic:
        nodo = new_settings.createElement("setting")
        nodo.setAttribute("value",settings_dic[key])
        nodo.setAttribute("id",key)    
        new_settings_root.appendChild(nodo)
        
      fichero = open(configfilepath, "w")
      fichero.write(new_settings.toprettyxml(encoding='utf-8'))
      fichero.close()
Пример #18
0
def set_setting(name, value, channel=""):
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)

    else:
        settings_dic[name] = value
        from xml.dom import minidom
        #Crea un Nuevo XML vacio
        new_settings = minidom.getDOMImplementation().createDocument(
            None, "settings", None)
        new_settings_root = new_settings.documentElement

        for key in settings_dic:
            nodo = new_settings.createElement("setting")
            nodo.setAttribute("value", settings_dic[key])
            nodo.setAttribute("id", key)
            new_settings_root.appendChild(nodo)

        fichero = open(configfilepath, "w")
        fichero.write(new_settings.toprettyxml(encoding='utf-8'))
        fichero.close()
Пример #19
0
def set_setting(name,value, channel=""):
    if channel:
      from core import channeltools
      return channeltools.set_channel_setting(name,value, channel)
    else:
        encontrado = False
        try:
            # Leer el archivo user_preferences
            sep = os.path.sep
            user_preferences = get_data_path().replace(sep + "Data" + sep, sep + "Preferences" + sep) + ".xml"
            data = open(user_preferences, "rb").readlines()

            # Eliminar el parametro name si existe
            for line in data:
                if re.match("<%s/?>" % name, line.strip()):
                    data.remove(line)
                    encontrado = True

            if encontrado:
                # Añadir al final del listado el parametro con su nuevo valor
                if value:
                    data.insert(-1, "  <{0}>{1}</{0}>\n".format(name, value))
                else:
                    data.insert(-1, "  <{0}/>\n".format(name))

                # Guardar el archivo de nuevo
                out_file = open(user_preferences, "wb")
                for line in data:
                    out_file.write(line)
            else:
                # Añadir el nuevo parametro con su valor en dict_global
                bridge.dict_global[name] = value

            return value

        except:
            return ""
Пример #20
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_servers = []
        favorite_quality = []

        # 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 item in itemlist:
            autoplay_elem = dict()
            b_dict = 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": 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_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_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_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_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'])

        # 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
                            old_frequency = channeltools.get_channel_setting("frequency", channel_id, 0)
                            channeltools.set_channel_setting('frequency', old_frequency + 1, channel_id)
                            logger.debug('autoplay sumar frecuencia')
                            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
Пример #21
0
def run(item=None):
    # from core.support import dbg;dbg()
    logger.debug()
    if not item:
        # Extract item from sys.argv
        if sys.argv[2]:
            sp = sys.argv[2].split('&')
            url = sp[0]
            item = Item().fromurl(url)
            if len(sp) > 1:
                for e in sp[1:]:
                    key, val = e.split('=')
                    item.__setattr__(key, val)
        # If no item, this is mainlist
        else:
            item = Item(channel="channelselector",
                        action="getmainlist",
                        viewmode="movie")
        if not config.get_setting('show_once'):
            if not config.get_all_settings_addon():
                logger.error('corrupted settings.xml!!')
                settings_xml = os.path.join(config.get_data_path(),
                                            "settings.xml")
                settings_bak = os.path.join(config.get_data_path(),
                                            "settings.bak")
                if filetools.exists(settings_bak):
                    filetools.copy(settings_bak, settings_xml, True)
                    logger.info('restored settings.xml from backup')
                else:
                    filetools.write(settings_xml,
                                    '<settings version="2">\n</settings>'
                                    )  # resetted settings
            else:
                from platformcode import xbmc_videolibrary
                xbmc_videolibrary.ask_set_content(silent=False)
                config.set_setting('show_once', True)

    logger.info(item.tostring())

    try:
        if not config.get_setting('tmdb_active'):
            config.set_setting('tmdb_active', True)

        # If item has no action, stops here
        if item.action == "":
            logger.debug("Item without action")
            return

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

            itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

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

            platformtools.render_items(itemlist, item)

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

            platformtools.render_items(itemlist, item)

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

        elif item.action == "keymap":
            from platformcode import keymaptools
            if item.open:
                return keymaptools.open_shortcut_menu()
            else:
                return keymaptools.set_key()

        elif item.channel == "infoplus":
            from platformcode import infoplus
            return infoplus.Main(item)

        elif item.channel == "backup":
            from platformcode import backup
            return getattr(backup, item.action)(item)

        elif item.channel == "elementum_download":
            from platformcode import elementum_download
            return getattr(elementum_download, item.action)(item)

        elif item.channel == "shortcuts":
            from platformcode import shortcuts
            return getattr(shortcuts, item.action)(item)

        elif item.channel == "autorenumber":
            from platformcode import autorenumber
            return getattr(autorenumber, item.action)(item)

        elif item.action == "delete_key":
            from platformcode import keymaptools
            return keymaptools.delete_key()

        elif item.action == "script":
            from core import tmdb
            if tmdb.drop_bd():
                platformtools.dialog_notification(
                    config.get_localized_string(20000),
                    config.get_localized_string(60011),
                    time=2000,
                    sound=False)
        elif item.action == "itemInfo":
            platformtools.dialog_textviewer('Item info', item.parent)
        elif item.action == "open_browser":
            import webbrowser
            if not webbrowser.open(item.url):
                import xbmc
                if xbmc.getCondVisibility(
                        'system.platform.linux') and xbmc.getCondVisibility(
                            'system.platform.android'):  # android
                    xbmc.executebuiltin(
                        'StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")'
                        % (item.url))
                else:
                    try:
                        import urllib.request as urllib
                    except ImportError:
                        import urllib
                    short = urllib.urlopen(
                        'https://u.nu/api.php?action=shorturl&format=simple&url='
                        + item.url).read().decode('utf-8')
                    platformtools.dialog_ok(
                        config.get_localized_string(20000),
                        config.get_localized_string(70740) % short)
        # Action in certain channel specified in "action" and "channel" parameters
        elif item.action == "check_channels":
            from platformcode import checkhost
            checkhost.check_channels()
        else:
            # Checks if channel exists
            if os.path.isfile(
                    os.path.join(config.get_runtime_path(), 'channels',
                                 item.channel + ".py")):
                CHANNELS = 'channels'
            else:
                CHANNELS = 'specials'

            channel_file = os.path.join(config.get_runtime_path(), CHANNELS,
                                        item.channel + ".py")

            logger.debug("channel_file= " + channel_file + ' - ' + CHANNELS +
                         ' - ' + item.channel)

            channel = None

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

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

            # Special play action
            if item.action == "play":
                # define la info para trakt
                try:
                    from core import trakt_tools
                    trakt_tools.set_trakt_info(item)
                except:
                    pass
                logger.debug("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

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

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

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok(
                            config.get_localized_string(20000),
                            config.get_localized_string(60339))

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

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

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

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

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

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                from core import videolibrarytools
                videolibrarytools.add_movie(item)

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

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

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                # from core.support import dbg;dbg()
                if filetools.isfile(temp_search_file) and config.get_setting(
                        'videolibrary_kodi'):
                    itemlist = []
                    f = filetools.read(temp_search_file)
                    strList = f.split(',')
                    if strList[0] == '[V]' and strList[1] == item.channel:
                        for it in strList:
                            if it and it not in ['[V]', item.channel]:
                                itemlist.append(Item().fromurl(it))
                        filetools.write(temp_search_file, f[4:])
                        return platformtools.render_items(itemlist, item)
                    else:
                        filetools.remove(temp_search_file)

                logger.debug("item.action=%s" % item.action.upper())
                from core import channeltools

                if config.get_setting('last_search'):
                    last_search = channeltools.get_channel_setting(
                        'Last_searched', 'search', '')
                else:
                    last_search = ''

                search_text = platformtools.dialog_input(last_search)

                if search_text is not None:
                    channeltools.set_channel_setting('Last_searched',
                                                     search_text, 'search')
                    itemlist = new_search(item.clone(text=search_text),
                                          channel)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                # import web_pdb; web_pdb.set_trace()
                logger.debug("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                if config.get_setting('trakt_sync'):
                    from core import trakt_tools
                    token_auth = config.get_setting("token_trakt", "trakt")
                    if not token_auth:
                        trakt_tools.auth_trakt()
                    else:
                        import xbmc
                        if not xbmc.getCondVisibility(
                                'System.HasAddon(script.trakt)'
                        ) and config.get_setting('install_trakt'):
                            trakt_tools.ask_install_script()
                    itemlist = trakt_tools.trakt_check(itemlist)
                else:
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

    except WebErrorException as e:
        import traceback
        from core import scrapertools

        logger.error(traceback.format_exc())

        platformtools.dialog_ok(
            config.get_localized_string(59985) % e.channel,
            config.get_localized_string(60013) % e.url)
    except Exception as e:
        import traceback
        from core import scrapertools

        logger.error(traceback.format_exc())

        patron = 'File "' + os.path.join(config.get_runtime_path(), "channels",
                                         "").replace("\\",
                                                     "\\\\") + r'([^.]+)\.py"'
        Channel = scrapertools.find_single_match(traceback.format_exc(),
                                                 patron)

        if Channel or e.__class__ == logger.ChannelScraperException:
            if item.url:
                if platformtools.dialog_yesno(
                        config.get_localized_string(60087) % Channel,
                        config.get_localized_string(60014),
                        nolabel='ok',
                        yeslabel=config.get_localized_string(70739)):
                    run(Item(action="open_browser", url=item.url))
            else:
                platformtools.dialog_ok(
                    config.get_localized_string(60087) % Channel,
                    config.get_localized_string(60014))
        else:
            if platformtools.dialog_yesno(config.get_localized_string(60038),
                                          config.get_localized_string(60015)):
                run(Item(channel="setting", action="report_menu"))
Пример #22
0
def set_setting(name, value, channel="", server=""):
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
    canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
    channel_data.json no existe busca en la carpeta channels el archivo channel.xml y crea un archivo channel_data.json
    antes de modificar el parametro 'name'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.


    Parametros:
    name -- nombre del parametro
    value -- valor del parametro
    channel [opcional] -- nombre del canal

    Retorna:
    'value' en caso de que se haya podido fijar el valor y None en caso contrario

    """
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    elif server:
        from core import servertools
        return servertools.set_server_setting(name, value, server)
    else:
        try:
            settings_types = get_settings_types()

            if settings_types.has_key(name):
                # El parametro esta en Preferences: lo abrimos y eliminamos la linea
                sep = os.path.sep
                user_preferences = get_data_path().replace(
                    sep + "Data" + sep, sep + "Preferences" + sep) + ".xml"
                data = open(user_preferences, "rb").readlines()

                for line in data:
                    if re.match("<%s/?>" % name, line.strip()):
                        data.remove(line)

                # Añadir al final del listado el parametro con su nuevo valor
                if value:
                    data.insert(-1, "  <{0}>{1}</{0}>\n".format(name, value))
                else:
                    data.insert(-1, "  <{0}/>\n".format(name))

                # Guardar el archivo de nuevo
                out_file = open(user_preferences, "wb")
                for line in data:
                    out_file.write(line)

            else:
                # El parametro no esta en Preferences: Lo añadimos a dict_global
                bridge.dict_global[name] = value

        except:
            return None

    return value
Пример #23
0
def set_setting(name,value, channel=""):
    if channel:
      from core import channeltools
      return channeltools.set_channel_setting(name,value, channel)
    else:   
      return ""
Пример #24
0
def set_setting(name, value, channel=""):
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    else:
        return ""
Пример #25
0
def run(item=None):
    logger.info()

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

        # If no item, this is mainlist
        else:
            if config.get_setting("start_page"):

                if not config.get_setting("custom_start"):
                    category = config.get_setting("category").lower()
                    item = Item(channel="news",
                                action="novedades",
                                extra=category,
                                mode='silent')
                else:
                    from channels import side_menu
                    item = Item()
                    item = side_menu.check_user_home(item)
                    item.start = True
            else:
                item = Item(channel="channelselector",
                            action="getmainlist",
                            viewmode="movie")
        if not config.get_setting('show_once'):
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.ask_set_content(1)
            config.set_setting('show_once', True)

    logger.info(item.tostring())

    try:
        if not config.get_setting('tmdb_active'):
            config.set_setting('tmdb_active', True)

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

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

            itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

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

            platformtools.render_items(itemlist, item)

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

            platformtools.render_items(itemlist, item)

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

        elif item.action == "keymap":
            from platformcode import keymaptools
            if item.open:
                return keymaptools.open_shortcut_menu()
            else:
                return keymaptools.set_key()

        elif item.action == "script":
            from core import tmdb
            if tmdb.drop_bd():
                platformtools.dialog_notification(
                    config.get_localized_string(20000),
                    config.get_localized_string(60011),
                    time=2000,
                    sound=False)

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

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

                # Parental control
                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(item.channel) and config.get_setting(
                        "adult_request_password"):
                    tecleado = platformtools.dialog_input(
                        "", config.get_localized_string(60334), True)
                    if tecleado is None or tecleado != config.get_setting(
                            "adult_password"):
                        return

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

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

            channel = None

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

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

            # Special play action
            if item.action == "play":
                #define la info para trakt
                try:
                    trakt_tools.set_trakt_info(item)
                except:
                    pass
                logger.info("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

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

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

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok(
                            config.get_localized_string(20000),
                            config.get_localized_string(60339))

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

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

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

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

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

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

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

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

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

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

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

                last_search = channeltools.get_channel_setting(
                    'Last_searched', 'search', '')

                tecleado = platformtools.dialog_input(last_search)

                if tecleado is not None:
                    channeltools.set_channel_setting('Last_searched', tecleado,
                                                     'search')
                    itemlist = channel.search(item, tecleado)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                if config.get_setting('trakt_sync'):
                    token_auth = config.get_setting("token_trakt", "trakt")
                    if not token_auth:
                        trakt_tools.auth_trakt()
                    else:
                        import xbmc
                        if not xbmc.getCondVisibility(
                                'System.HasAddon(script.trakt)'
                        ) and config.get_setting('install_trakt'):
                            trakt_tools.ask_install_script()
                    itemlist = trakt_tools.trakt_check(itemlist)
                else:
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

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

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

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.error("Codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok(
                "alfa",
                config.get_localized_string(30051) % e.code)
    except WebErrorException as e:
        import traceback
        logger.error(traceback.format_exc())

        patron = 'File "' + os.path.join(config.get_runtime_path(), "channels",
                                         "").replace("\\",
                                                     "\\\\") + '([^.]+)\.py"'
        canal = scrapertools.find_single_match(traceback.format_exc(), patron)

        platformtools.dialog_ok(
            config.get_localized_string(59985) + canal,
            config.get_localized_string(60013) % (e))
    except:
        import traceback
        logger.error(traceback.format_exc())

        patron = 'File "' + os.path.join(config.get_runtime_path(), "channels",
                                         "").replace("\\",
                                                     "\\\\") + '([^.]+)\.py"'
        canal = scrapertools.find_single_match(traceback.format_exc(), patron)

        try:
            import xbmc
            if config.get_platform(True)['num_version'] < 14:
                log_name = "xbmc.log"
            else:
                log_name = "kodi.log"
            log_message = config.get_localized_string(
                50004) + xbmc.translatePath("special://logpath") + log_name
        except:
            log_message = ""

        if canal:
            platformtools.dialog_ok(
                config.get_localized_string(60087) % canal,
                config.get_localized_string(60014), log_message)
        else:
            platformtools.dialog_ok(config.get_localized_string(60038),
                                    config.get_localized_string(60015),
                                    log_message)
Пример #26
0
def authentication():
    logger.info("pelisalacarta.servers.realdebrid authentication")
    try:
        client_id = "YTWNFBIJEEBP6"
        
        # Se solicita url y código de verificación para conceder permiso a la app
        url = "http://api.real-debrid.com/oauth/v2/device/code?client_id=%s&new_credentials=yes" % (client_id)
        data = scrapertools.downloadpage(url, headers=headers.items())
        data = jsontools.load_json(data)
        verify_url = data["verification_url"]
        user_code = data["user_code"]
        device_code = data["device_code"]
        intervalo = data["interval"]
        
        
        dialog_auth = platformtools.dialog_progress("Autentificación. No cierres esta ventana!!",
                                                    "1. Entra en la siguiente url: %s" % verify_url,
                                                    "2. Ingresa este código en la página y presiona Allow:  %s" % user_code,
                                                    "3. Espera a que se cierre esta ventana")
        
        # Generalmente cada 5 segundos se intenta comprobar si el usuario ha introducido el código
        while True:
            time.sleep(intervalo)
            try:
                if dialog_auth.iscanceled():
                    return ""

                url = "https://api.real-debrid.com/oauth/v2/device/credentials?client_id=%s&code=%s" \
                      % (client_id, device_code)
                data = scrapertools.downloadpage(url, headers=headers.items())
                data = jsontools.load_json(data)
                if "client_secret" in data:
                    # Código introducido, salimos del bucle
                    break
            except:
                pass

        try:
            dialog_auth.close()
        except:
            pass
        
        debrid_id = data["client_id"]
        secret = data["client_secret"] 

        # Se solicita el token de acceso y el de actualización para cuando el primero caduque
        post = urllib.urlencode({"client_id": debrid_id, "client_secret": secret, "code": device_code,
                                 "grant_type": "http://oauth.net/grant_type/device/1.0"})
        data = scrapertools.downloadpage("https://api.real-debrid.com/oauth/v2/token", post=post,
                                         headers=headers.items())
        data = jsontools.load_json(data)

        token = data["access_token"]
        refresh = data["refresh_token"]

        channeltools.set_channel_setting("realdebrid_id", debrid_id, "realdebrid")
        channeltools.set_channel_setting("realdebrid_secret", secret, "realdebrid")
        channeltools.set_channel_setting("realdebrid_token", token, "realdebrid")
        channeltools.set_channel_setting("realdebrid_refresh", refresh, "realdebrid")
        
        return token
    except:
        import traceback
        logger.error(traceback.format_exc())
        return ""
Пример #27
0
def run(item=None):
    logger.info()
    if not item:
        # Extract item from sys.argv
        if sys.argv[2]:
            sp = sys.argv[2].split('&')
            url = sp[0]
            item = Item().fromurl(url)
            if len(sp) > 1:
                for e in sp[1:]:
                    key, val = e.split('=')
                    item.__setattr__(key, val)
        # If no item, this is mainlist
        else:
            if config.get_setting("start_page"):

                if not config.get_setting("custom_start"):
                    dictCategory = {
                        config.get_localized_string(70137): 'peliculas',
                        config.get_localized_string(30123): 'series',
                        config.get_localized_string(30124): 'anime',
                        config.get_localized_string(70018): 'infantiles',
                        config.get_localized_string(60513): 'documentales',
                        config.get_localized_string(70013): 'terror',
                        config.get_localized_string(70014): 'castellano',
                        config.get_localized_string(59976): 'latino',
                        config.get_localized_string(70171): 'torrent',
                    }
                    if not config.get_setting(
                            "category") in dictCategory.keys():
                        config.set_setting('category',
                                           config.get_localized_string(70137))
                    category = dictCategory[config.get_setting("category")]
                    item = Item(channel="news",
                                action="novedades",
                                extra=category,
                                mode='silent')
                else:
                    from specials import side_menu
                    item = Item()
                    item = side_menu.check_user_home(item)
                    item.start = True
            else:
                item = Item(channel="channelselector",
                            action="getmainlist",
                            viewmode="movie")
        if not config.get_setting('show_once'):
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.ask_set_content(silent=False)
            config.set_setting('show_once', True)

    logger.info(item.tostring())

    try:
        if not config.get_setting('tmdb_active'):
            config.set_setting('tmdb_active', True)

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

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

            itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

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

            platformtools.render_items(itemlist, item)

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

            platformtools.render_items(itemlist, item)

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

        elif item.action == "keymap":
            from platformcode import keymaptools
            if item.open:
                return keymaptools.open_shortcut_menu()
            else:
                return keymaptools.set_key()

        elif item.action == "delete_key":
            from platformcode import keymaptools
            return keymaptools.delete_key()

        elif item.action == "script":
            from core import tmdb
            if tmdb.drop_bd():
                platformtools.dialog_notification(
                    config.get_localized_string(20000),
                    config.get_localized_string(60011),
                    time=2000,
                    sound=False)
        elif item.action == "itemInfo":
            import base64
            platformtools.dialog_textviewer('Item info', item.parent)
        elif item.action == "open_browser":
            import webbrowser
            if not webbrowser.open(item.url):
                import xbmc
                if xbmc.getCondVisibility(
                        'system.platform.linux') and xbmc.getCondVisibility(
                            'system.platform.android'):  # android
                    xbmc.executebuiltin(
                        'StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")'
                        % (item.url))
                else:
                    try:
                        import urllib.request as urllib
                    except ImportError:
                        import urllib
                    short = urllib.urlopen(
                        'https://u.nu/api.php?action=shorturl&format=simple&url='
                        + item.url).read().decode('utf-8')
                    platformtools.dialog_ok(
                        config.get_localized_string(20000),
                        config.get_localized_string(70740) % short)
        # Action in certain channel specified in "action" and "channel" parameters
        else:
            # Entry point for a channel is the "mainlist" action, so here we check parental control
            if item.action == "mainlist":
                from core import channeltools
                #updater.checkforupdates() beta version checking for update, still disabled

                # Parental control
                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(item.channel) and config.get_setting(
                        "adult_request_password"):
                    tecleado = platformtools.dialog_input(
                        "", config.get_localized_string(60334), True)
                    if tecleado is None or tecleado != config.get_setting(
                            "adult_password"):
                        return
            # # Actualiza el canal individual
            # if (item.action == "mainlist" and item.channel != "channelselector" and
            #             config.get_setting("check_for_channel_updates") == True):
            #     from core import updater
            #     updater.update_channel(item.channel)

            # Checks if channel exists
            if os.path.isfile(
                    os.path.join(config.get_runtime_path(), 'channels',
                                 item.channel + ".py")):
                CHANNELS = 'channels'
            elif os.path.isfile(
                    os.path.join(config.get_runtime_path(), 'channels', 'p**n',
                                 item.channel + ".py")):
                CHANNELS = 'channels.p**n'
            else:
                CHANNELS = 'specials'

            if CHANNELS != 'channels.p**n':
                channel_file = os.path.join(config.get_runtime_path(),
                                            CHANNELS, item.channel + ".py")
            else:
                channel_file = os.path.join(config.get_runtime_path(),
                                            'channels', 'p**n',
                                            item.channel + ".py")

            logger.info("channel_file= " + channel_file + ' - ' + CHANNELS +
                        ' - ' + item.channel)

            channel = None

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

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

            # Special play action
            if item.action == "play":
                #define la info para trakt
                try:
                    from core import trakt_tools
                    trakt_tools.set_trakt_info(item)
                except:
                    pass
                logger.info("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

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

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

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok(
                            config.get_localized_string(20000),
                            config.get_localized_string(60339))

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

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

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

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

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

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                from core import videolibrarytools
                videolibrarytools.add_movie(item)

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

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

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

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

                # last_search = channeltools.get_channel_setting('Last_searched', 'search', '')
                if channeltools.get_channel_setting('last_search', 'search'):
                    last_search = channeltools.get_channel_setting(
                        'Last_searched', 'search', '')
                else:
                    last_search = ''

                tecleado = platformtools.dialog_input(last_search)

                if tecleado is not None:
                    channeltools.set_channel_setting('Last_searched', tecleado,
                                                     'search')
                    if 'search' in dir(channel):
                        itemlist = channel.search(item, tecleado)
                    else:
                        from core import support
                        itemlist = support.search(channel, item, tecleado)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                # import web_pdb; web_pdb.set_trace()
                logger.info("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                if config.get_setting('trakt_sync'):
                    from core import trakt_tools
                    token_auth = config.get_setting("token_trakt", "trakt")
                    if not token_auth:
                        trakt_tools.auth_trakt()
                    else:
                        import xbmc
                        if not xbmc.getCondVisibility(
                                'System.HasAddon(script.trakt)'
                        ) and config.get_setting('install_trakt'):
                            trakt_tools.ask_install_script()
                    itemlist = trakt_tools.trakt_check(itemlist)
                else:
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

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

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

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.error("HTTP error code: %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok(
                config.get_localized_string(20000),
                config.get_localized_string(30051) % e.code)
    except WebErrorException as e:
        import traceback
        from core import scrapertools

        logger.error(traceback.format_exc())

        patron = 'File "' + os.path.join(config.get_runtime_path(), "channels",
                                         "").replace("\\",
                                                     "\\\\") + '([^.]+)\.py"'
        canal = scrapertools.find_single_match(traceback.format_exc(), patron)

        platformtools.dialog_ok(
            config.get_localized_string(59985) + canal,
            config.get_localized_string(60013) % (e))
    except:
        import traceback
        from core import scrapertools

        logger.error(traceback.format_exc())

        patron = 'File "' + os.path.join(config.get_runtime_path(), "channels",
                                         "").replace("\\",
                                                     "\\\\") + '([^.]+)\.py"'
        canal = scrapertools.find_single_match(traceback.format_exc(), patron)

        try:
            import xbmc
            if config.get_platform(True)['num_version'] < 14:
                log_name = "xbmc.log"
            else:
                log_name = "kodi.log"
            log_message = config.get_localized_string(
                50004) + xbmc.translatePath("special://logpath") + log_name
        except:
            log_message = ""

        if canal:
            if item.url:
                if platformtools.dialog_yesno(
                        config.get_localized_string(60087) % canal,
                        config.get_localized_string(60014),
                        log_message,
                        nolabel='ok',
                        yeslabel=config.get_localized_string(70739)):
                    run(Item(action="open_browser", url=item.url))
            else:
                platformtools.dialog_ok(
                    config.get_localized_string(60087) % canal,
                    config.get_localized_string(60014), log_message)
        else:
            platformtools.dialog_ok(config.get_localized_string(60038),
                                    config.get_localized_string(60015),
                                    log_message)
Пример #28
0
def set_setting(name, value, channel="", server=""):
    global alfa_settings
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
    canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.alfa\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
    channel_data.json no existe busca en la carpeta channels el archivo channel.json y crea un archivo channel_data.json
    antes de modificar el parametro 'name'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.


    Parametros:
    name -- nombre del parametro
    value -- valor del parametro
    channel [opcional] -- nombre del canal

    Retorna:
    'value' en caso de que se haya podido fijar el valor y None en caso contrario

    """
    value_init = value
    if channel:
        from core import channeltools
        return channeltools.set_channel_setting(name, value, channel)
    elif server:
        from core import servertools
        return servertools.set_server_setting(name, value, server)
    else:
        try:
            alfa_caching = bool(window.getProperty("alfa_caching"))
            if alfa_caching:
                alfa_settings = json.loads(window.getProperty("alfa_settings"))
                # Si el alfa_caching está activo, se usa la variable cargada.  Si no, se cargan por el método tradicional
                if not alfa_settings:
                    get_all_settings_addon()

            if isinstance(value, bool):
                if value:
                    value = "true"
                else:
                    value = "false"

            elif isinstance(value, (int, long)):
                value = str(value)

            __settings__.setSetting(name, value)

            if name == 'caching':
                if value_init:
                    window.setProperty("alfa_caching", str(True))
                    alfa_caching = True
                else:
                    window.setProperty("alfa_caching", '')
                    alfa_caching = False
                if not alfa_caching:
                    alfa_settings = {}
                    window.setProperty("alfa_settings", json.dumps(alfa_settings))
            if alfa_caching and alfa_settings and alfa_settings.get(name, '') != value_init:
                alfa_settings[name] = value_init
                window.setProperty("alfa_settings", json.dumps(alfa_settings))

        except Exception as ex:
            alfa_settings = {}
            window.setProperty("alfa_settings", json.dumps(alfa_settings))
            from platformcode import logger
            logger.error("Error al convertir '%s' no se guarda el valor \n%s" % (name, ex))
            return None

        return value
Пример #29
0
def new_search(item):
    logger.debug()

    temp_search_file = config.get_temp_file('temp-search')
    if filetools.isfile(temp_search_file):
        filetools.remove(temp_search_file)

    itemlist = []
    if config.get_setting('last_search'):
        last_search = channeltools.get_channel_setting('Last_searched',
                                                       'search', '')
    else:
        last_search = ''

    if item.search_text:
        searched_text = item.search_text
    else:
        searched_text = platformtools.dialog_input(default=last_search,
                                                   heading='')

    save_search(searched_text)
    if not searched_text:
        return

    channeltools.set_channel_setting('Last_searched', searched_text, 'search')
    searched_text = searched_text.replace("+", " ")

    if item.mode == 'person':
        item.searched_text = searched_text
        return actor_list(item)

    if item.mode != 'all':
        tmdb_info = tmdb.Tmdb(searched_text=searched_text,
                              search_type=item.mode.replace('show', ''))
        results = tmdb_info.results
        for result in results:
            result = tmdb_info.get_infoLabels(result, origen=result)
            if item.mode == 'movie':
                title = result['title']
            else:
                title = result['name']
                item.mode = 'tvshow'

            thumbnail = result.get('thumbnail', '')
            fanart = result.get('fanart', '')

            new_item = Item(channel=item.channel,
                            action='channel_search',
                            title=title,
                            text=searched_text,
                            thumbnail=thumbnail,
                            fanart=fanart,
                            mode=item.mode,
                            contentType=item.mode,
                            infoLabels=result)

            if item.mode == 'movie':
                new_item.contentTitle = result['title']
            else:
                new_item.contentSerieName = result['name']

            itemlist.append(new_item)

    if item.mode == 'all' or not itemlist:
        return channel_search(
            Item(channel=item.channel,
                 title=searched_text,
                 text=searched_text,
                 mode='all',
                 infoLabels={}))

    return itemlist
Пример #30
0
def authentication():
    logger.info("deportesalacarta.servers.realdebrid authentication")
    try:
        client_id = "YTWNFBIJEEBP6"

        # Se solicita url y código de verificación para conceder permiso a la app
        url = "http://api.real-debrid.com/oauth/v2/device/code?client_id=%s&new_credentials=yes" % (
            client_id)
        data = scrapertools.downloadpage(url, headers=headers.items())
        data = jsontools.load_json(data)
        verify_url = data["verification_url"]
        user_code = data["user_code"]
        device_code = data["device_code"]
        intervalo = data["interval"]

        dialog_auth = platformtools.dialog_progress(
            "Autentificación. No cierres esta ventana!!",
            "1. Entra en la siguiente url: %s" % verify_url,
            "2. Ingresa este código en la página y presiona Allow:  %s" %
            user_code, "3. Espera a que se cierre esta ventana")

        # Generalmente cada 5 segundos se intenta comprobar si el usuario ha introducido el código
        while True:
            time.sleep(intervalo)
            try:
                if dialog_auth.iscanceled():
                    return ""

                url = "https://api.real-debrid.com/oauth/v2/device/credentials?client_id=%s&code=%s" \
                      % (client_id, device_code)
                data = scrapertools.downloadpage(url, headers=headers.items())
                data = jsontools.load_json(data)
                if "client_secret" in data:
                    # Código introducido, salimos del bucle
                    break
            except:
                pass

        try:
            dialog_auth.close()
        except:
            pass

        debrid_id = data["client_id"]
        secret = data["client_secret"]

        # Se solicita el token de acceso y el de actualización para cuando el primero caduque
        post = urllib.urlencode({
            "client_id":
            debrid_id,
            "client_secret":
            secret,
            "code":
            device_code,
            "grant_type":
            "http://oauth.net/grant_type/device/1.0"
        })
        data = scrapertools.downloadpage(
            "https://api.real-debrid.com/oauth/v2/token",
            post=post,
            headers=headers.items())
        data = jsontools.load_json(data)

        token = data["access_token"]
        refresh = data["refresh_token"]

        channeltools.set_channel_setting("realdebrid_id", debrid_id,
                                         "realdebrid")
        channeltools.set_channel_setting("realdebrid_secret", secret,
                                         "realdebrid")
        channeltools.set_channel_setting("realdebrid_token", token,
                                         "realdebrid")
        channeltools.set_channel_setting("realdebrid_refresh", refresh,
                                         "realdebrid")

        return token
    except:
        import traceback
        logger.error(traceback.format_exc())
        return ""