Ejemplo n.º 1
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", ""]]
Ejemplo n.º 2
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')
Ejemplo n.º 3
0
def get_setting(name, channel=""):
    """Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.
    
    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el archivo channel_data.json
    y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe devuelve un str vacio.
    
    Parametros:
    name -- nombre del parametro
    channel [opcional] -- nombre del canal
      
    Retorna:
    value -- El valor del parametro 'name'
    
    """   
    if channel:
      from core import channeltools
      value = channeltools.get_channel_setting(name, channel)
      if not value is None:
        return value

    # Devolvemos el valor del parametro global 'name'        
    return __settings__.getSetting( name ) 
Ejemplo n.º 4
0
def get_setting(name, channel=""):
    if channel:
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        if not value is None:
            return value

    # Devolvemos el valor del parametro global 'name'
    if name == "cache.dir":
        return ""

    if name == "debug" or name == "download.enabled":
        return "false"

    if name == "cookies.dir":
        return os.getcwd()

    if name == "cache.mode" or name == "thumbnail_type":
        return "2"
    else:
        import bridge
        try:
            devuelve = bridge.get_setting(name)
        except:
            devuelve = ""

        if type(devuelve) == BooleanType:
            if devuelve:
                devuelve = "true"
            else:
                devuelve = "false"

        return devuelve
Ejemplo n.º 5
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
Ejemplo n.º 6
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__)
Ejemplo n.º 7
0
def get_setting(name, channel=""):
    if channel:
      from core import channeltools
      value = channeltools.get_channel_setting(name, channel)
      if not value is None:
          return value

        
    # Devolvemos el valor del parametro global 'name'        
    if name=="cache.dir":
        return ""

    if name=="debug" or name=="download.enabled":
        return "false"
    
    if name=="cookies.dir":
        return os.getcwd()

    if name=="cache.mode" or name=="thumbnail_type":
        return "2"
    else:
        import bridge
        try:
            devuelve = bridge.get_setting(name)
        except:
            devuelve = ""
        
        if type(devuelve) == BooleanType:
            if devuelve:
                devuelve = "true"
            else:
                devuelve = "false"
        
        return devuelve
Ejemplo n.º 8
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", ""]]
Ejemplo n.º 9
0
def get_setting(name, channel="", server=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """

    # Specific channel setting
    if channel:
        from core import channeltools
        return channeltools.get_channel_setting(name, channel)

    elif server:
        from core import servertools
        return servertools.get_server_setting(name, server)

    # Global setting
    else:
        # Devolvemos el valor del parametro global 'name'
        if name == "cache.dir":
            value = ""

        if name == "debug" or name == "download.enabled":
            value = False

        if name == "cookies.dir":
            value = os.getcwd()  #TODO no parece funcionar

        if name == "cache.mode" or name == "thumbnail_type":
            value = 2

        else:
            value = bridge.get_setting(name)

            # hack para devolver el tipo correspondiente
            settings_types = get_settings_types()

            if isinstance(settings_types.get(name),
                          tuple) and settings_types[name][0] == 'enum':
                value = settings_types[name][1].index(value)

            elif settings_types.get(name) == 'bool':
                value = bool(value)

        return value
Ejemplo n.º 10
0
def get_setting(name, channel=""):
    if channel:
      from core import channeltools
      value = channeltools.get_channel_setting(name, channel)
      if not value is None:
        return value

    return __settings__.getSetting( name )
Ejemplo n.º 11
0
def get_setting(name, channel="", server=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """

    # Specific channel setting
    if channel:

        # xbmc.log("config.get_setting reading channel setting '"+name+"' from channel xml")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        # xbmc.log.info("config.get_setting -> '"+repr(value)+"'")

        return value
            
    elif server:
        # xbmc.log("config.get_setting reading server setting '"+name+"' from server xml")
        from core import servertools
        value = servertools.get_server_setting(name, server)
        # xbmc.log("config.get_setting -> '"+repr(value)+"'")

        return value

    # Global setting
    else:
        #xbmc.log("config.get_setting reading main setting '"+name+"'")
        import xbmcplugin
        value = xbmcplugin.getSetting(name)
        #xbmc.log("config.get_setting -> '"+value+"'")

        # hack para devolver el tipo correspondiente
        if value == "true":
            return True
        elif value == "false":
            return False
        else:
            try:
                value = int(value)
            except ValueError:
                pass

            return value
Ejemplo n.º 12
0
def get_setting(name, channel="", server=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """

    # Specific channel setting
    if channel:

        # logger.info("config.get_setting reading channel setting '"+name+"' from channel xml")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        return value
            
    elif server:
        # logger.info("config.get_setting reading server setting '"+name+"' from server xml")
        from core import servertools
        value = servertools.get_server_setting(name, server)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        return value

    # Global setting
    else:
	    try:
	        if name in overrides:
	            dev = overrides[name]
	            #print "Overrides: ",name,"=",dev
	        #elif name=="debug":
	        #    return "true"
	        else:
	            dev=configfile.get("General",name)
	            #print "Config file: ",name,"=",dev
	        #print "get_setting",name,dev
	        return dev
	    except:
	        #print "get_setting",name,"(vacío)"
	        return ""
Ejemplo n.º 13
0
def get_setting(name,channel=""):
    if channel:
      from core import channeltools
      value = channeltools.get_channel_setting(name, channel)
      if not value is None:
        return value       
         
    global settings_dic
    if name in settings_dic:
      return settings_dic[name]
    else:
      return ""
Ejemplo n.º 14
0
def get_setting(name, channel=""):
    if channel:
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        if not value is None:
            return value

    global settings_dic
    if name in settings_dic:
        return settings_dic[name]
    else:
        return ""
Ejemplo n.º 15
0
def get_setting(name, channel=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """
    # xbmc.log("config.get_setting name="+name+", channel="+channel+", OLD_PLATFORM="+str(OLD_PLATFORM))

    # Specific channel setting
    if channel:

        # Old platforms read settings from settings-oldplatform.xml, all but the "include_in_global_search", "include_in_newest..."
        if OLD_PLATFORM and ("user" in name or "password" in name):
            # xbmc.log("config.get_setting reading channel setting from main xml '"+channel+"_"+name+"'")
            value = __settings__.getSetting(channel + "_" + name)
            # xbmc.log("config.get_setting -> '"+value+"'")
            return value

        # New platforms read settings from each channel
        else:
            # xbmc.log("config.get_setting reading channel setting '"+name+"' from channel xml")
            from core import channeltools
            value = channeltools.get_channel_setting(name, channel)
            # xbmc.log("config.get_setting -> '"+repr(value)+"'")

            if value is not None:
                return value
            else:
                return ""

    # Global setting
    else:
        # xbmc.log("config.get_setting reading main setting '"+name+"'")
        value = __settings__.getSetting(channel + name)
        if value.startswith("special://"):
            value = xbmc.translatePath(value)
        # xbmc.log("config.get_setting -> '"+value+"'")
        return value
Ejemplo n.º 16
0
def get_setting(name, channel=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """
    # xbmc.log("config.get_setting name="+name+", channel="+channel+", OLD_PLATFORM="+str(OLD_PLATFORM))

    # Specific channel setting
    if channel:

        # Old platforms read settings from settings-oldplatform.xml, all but the "include_in_global_search", "include_in_newest..."
        if OLD_PLATFORM and ("user" in name or "password" in name):
            # xbmc.log("config.get_setting reading channel setting from main xml '"+channel+"_"+name+"'")
            value = __settings__.getSetting(channel+"_"+name)
            # xbmc.log("config.get_setting -> '"+value+"'")
            return value

        # New platforms read settings from each channel
        else:
            # xbmc.log("config.get_setting reading channel setting '"+name+"' from channel xml")
            from core import channeltools
            value = channeltools.get_channel_setting(name, channel)
            # xbmc.log("config.get_setting -> '"+repr(value)+"'")

            if value is not None:
                return value
            else:
                return ""

    # Global setting
    else:
        # xbmc.log("config.get_setting reading main setting '"+name+"'")
        value = __settings__.getSetting(channel+name)
        # xbmc.log("config.get_setting -> '"+value+"'")
        return value
Ejemplo n.º 17
0
def get_setting(name, channel=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """

    # Specific channel setting
    if channel:

        # logger.info("config.get_setting reading channel setting '"+name+"' from channel xml")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        if value is not None:
            return value
        else:
            return ""

    # Global setting
    else:
        # logger.info("config.get_setting reading main setting '"+name+"'")
        global settings_dic
        value = settings_dic.get(name, "")
        
        if name == "adult_mode":
          global adult_setting
          id = threading.current_thread().name
          if adult_setting.get(id) == True:
            value = "2"

        # logger.info("config.get_setting -> '"+value+"'")
        return value
Ejemplo n.º 18
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)
Ejemplo n.º 19
0
def get_setting(name, channel=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """

    # Specific channel setting
    if channel:

        # logger.info("config.get_setting reading channel setting '"+name+"' from channel xml")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        if value is not None:
            return value
        else:
            return ""

    # Global setting
    else:
        # logger.info("config.get_setting reading main setting '"+name+"'")
        value = __settings__.getSetting(channel + name)
        # Translate Path if start with "special://"
        if value.startswith("special://") and "librarypath" not in name:
            value = xbmc.translatePath(value)

        # logger.info("config.get_setting -> '"+value+"'")
        return value
Ejemplo n.º 20
0
def get_setting(name, channel=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """

    # Specific channel setting
    if channel:

        # logger.info("config.get_setting reading channel setting '"+name+"' from channel xml")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        if value is not None:
            return value
        else:
            return ""

    # Global setting
    else:
        # logger.info("config.get_setting reading main setting '"+name+"'")
        value = xbmcplugin.getSetting(channel + name)
        # Translate Path if start with "special://"
        if value.startswith("special://") and "librarypath" not in name:
            value = xbmc.translatePath(value)

        # logger.info("config.get_setting -> '"+value+"'")
        return value
Ejemplo n.º 21
0
def mainlist(item):
    logger.info("pelisalacarta.channels.ayuda mainlist")
    itemlist = []

    cuantos = 0

    if cuantos > 0:
        itemlist.append(Item(channel=item.channel,
                             action="tutoriales", title="Ver guías y tutoriales en vídeo"))
    else:
        itemlist.extend(tutoriales(item))

    itemlist.append(Item(channel=item.channel, action="", title="",
                         folder=False))

    if config.is_xbmc():
        #FIXME Al poner folder=False el log muestra: "WARNING: Attempt to use invalid handle -1"
        itemlist.append(Item(channel=item.channel,
                             action="force_creation_advancedsettings",
                             title="Crear fichero advancedsettings.xml optimizado", folder=True))
        cuantos += cuantos

    if config.is_xbmc():
        itemlist.append(Item(channel=item.channel,
                             action="recover_advancedsettings",
                             title="Restaurar advancedsettings.xml del backup", folder=False))
        cuantos += cuantos

    if not config.is_xbmc():
        from core import channeltools
        title = "Activar cuenta real-debrid (No activada)"
        action = "realdebrid"
        token_auth = channeltools.get_channel_setting("realdebrid_token", "realdebrid")
        if config.get_setting("realdebridpremium") == "false":
            title = "Activar cuenta real-debrid (Marca la casilla en la ventana de configuración de pelisalacarta para continuar)"
            action = ""
        elif token_auth:
            title = "Activar cuenta real-debrid (Activada correctamente)"
        itemlist.append(Item(channel=item.channel, action=action, title=title))

    return itemlist
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
def get_setting(name, channel=""):
    if channel:
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        if not value is None:
            return value

        
    # Devolvemos el valor del parametro global 'name'        
    if name=="cache.dir":
        return ""

    if name=="debug" or name=="download.enabled":
        return "false"
    
    if name=="cookies.dir":
        return os.getcwd()

    if name=="cache.mode" or name=="thumbnail_type":
        return "2"
    else:
        try:
            devuelve = bridge.get_setting(name)
        except:
            devuelve = ""
        
        if type(devuelve) == BooleanType:
            if devuelve:
                devuelve = "true"
            else:
                devuelve = "false"

        if name == "adult_mode":
            devuelve = str(["Nunca","Siempre","Solo hasta que se reinicie Plex Media Server"].index(devuelve))

        return devuelve
Ejemplo n.º 24
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)
Ejemplo n.º 25
0
def mainlist(item):
    logger.info()
    itemlist = []

    if config.is_xbmc():
        itemlist.append(Item(channel=item.channel, action="", title="FAQ:",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - ¿Como reportar un error?",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="report_error"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - ¿Se pueden filtrar los enlaces?",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="filtrar_enlaces"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - ¿Se pueden activar/desactivar los canales?",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="onoff_canales"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - ¿Es posible la sincronización automática con Trakt?",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="trakt_sync"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - ¿Es posible mostrar todos los resultados juntos en el buscador global?",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="buscador_juntos"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - Los enlaces tardan en aparecer.",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="tiempo_enlaces"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - La búsqueda de contenido no se hace correctamente.",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="prob_busquedacont"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - Algún canal no funciona correctamente.",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="canal_fallo"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - Los enlaces Torrent no funcionan.",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra="prob_torrent"))
        itemlist.append(Item(channel=item.channel, action="faq",
                             title="    - No se actualiza correctamente la biblioteca.",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=True, extra="prob_bib"))
        itemlist.append(Item(channel="ayuda", action="faq",
                             title="    - Aparece un error al pulsar sobre un episodio.",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=True, extra="prob_bib"))
        itemlist.append(Item(channel="ayuda", action="faq",
                             title="    - Otros",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False, extra=""))

    itemlist.append(Item(channel=item.channel, title="Videotutoriales:",
                         thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                         folder=False, action=""))
    itemlist.extend(tutoriales(item))

    if config.is_xbmc():
        itemlist.append(Item(channel=item.channel,
                             action="force_creation_advancedsettings",
                             title="Optimizar fichero advancedsettings.xml",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False))
        itemlist.append(Item(channel=item.channel,
                             action="recover_advancedsettings",
                             title="Restaurar advancedsettings.xml del backup",
                             thumbnail=get_thumbnail_path("thumb_ayuda.png"),
                             folder=False))

    if not config.is_xbmc():
        from core import channeltools
        title = "Activar cuenta real-debrid (No activada)"
        action = "realdebrid"
        token_auth = channeltools.get_channel_setting("realdebrid_token", "realdebrid")
        if config.get_setting("realdebridpremium") == "false":
            title = "Activar cuenta real-debrid (Marca la casilla en la ventana de configuración de pelisalacarta para continuar)"
            action = ""
        elif token_auth:
            title = "Activar cuenta real-debrid (Activada correctamente)"
        itemlist.append(Item(channel="ayuda", action=action, title=title))

    return itemlist
Ejemplo n.º 26
0
def setting_channel_new(item):
    import xbmcgui

    # Cargar lista de opciones (canales activos del usuario y que permitan búsqueda global)
    # ------------------------
    lista = []
    ids = []
    lista_lang = []
    lista_ctgs = []
    channels_list = channelselector.filterchannels('all')
    for channel in channels_list:
        if channel.action == '':
            continue

        channel_parameters = channeltools.get_channel_parameters(
            channel.channel)

        # No incluir si en la configuracion del canal no existe "include_in_global_search"
        if not channel_parameters['include_in_global_search']:
            continue

        lbl = '%s' % channel_parameters['language']
        lbl += ' %s' % ', '.join(
            config.get_localized_category(categ)
            for categ in channel_parameters['categories'])

        it = xbmcgui.ListItem(channel.title, lbl)
        it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart})
        lista.append(it)
        ids.append(channel.channel)
        lista_lang.append(channel_parameters['language'])
        lista_ctgs.append(channel_parameters['categories'])

    # Diálogo para pre-seleccionar
    # ----------------------------
    preselecciones = [
        'Buscar con la selección actual', 'Modificar selección actual',
        'Modificar partiendo de Recomendados',
        'Modificar partiendo de Frecuentes', 'Modificar partiendo de Todos',
        'Modificar partiendo de Ninguno', 'Modificar partiendo de Castellano',
        'Modificar partiendo de Latino'
    ]
    presel_values = [
        'skip', 'actual', 'recom', 'freq', 'all', 'none', 'cast', 'lat'
    ]

    categs = [
        'movie', 'tvshow', 'documentary', 'anime', 'vos', 'direct', 'torrent'
    ]
    if config.get_setting('adult_mode') > 0:
        categs.append('adult')
    for c in categs:
        preselecciones.append('Modificar partiendo de %s' %
                              config.get_localized_category(c))
        presel_values.append(c)

    if item.action == 'setting_channel':  # Configuración de los canales incluídos en la búsqueda
        del preselecciones[0]
        del presel_values[0]
    # else: # Llamada desde "buscar en otros canales" (se puede saltar la selección e ir directo a la búsqueda)

    ret = platformtools.dialog_select(config.get_localized_string(59994),
                                      preselecciones)
    if ret == -1:
        return False  # pedido cancel
    if presel_values[ret] == 'skip':
        return True  # continuar sin modificar
    elif presel_values[ret] == 'none':
        preselect = []
    elif presel_values[ret] == 'all':
        preselect = range(len(ids))
    elif presel_values[ret] in ['cast', 'lat']:
        preselect = []
        for i, lg in enumerate(lista_lang):
            if presel_values[ret] in lg or '*' in lg:
                preselect.append(i)
    elif presel_values[ret] == 'actual':
        preselect = []
        for i, canal in enumerate(ids):
            channel_status = config.get_setting('include_in_global_search',
                                                canal)
            if channel_status:
                preselect.append(i)

    elif presel_values[ret] == 'recom':
        preselect = []
        for i, canal in enumerate(ids):
            _not, set_canal_list = channeltools.get_channel_controls_settings(
                canal)
            if set_canal_list.get('include_in_global_search', False):
                preselect.append(i)

    elif presel_values[ret] == 'freq':
        preselect = []
        for i, canal in enumerate(ids):
            frequency = channeltools.get_channel_setting('frequency', canal, 0)
            if frequency > 0:
                preselect.append(i)
    else:
        preselect = []
        for i, ctgs in enumerate(lista_ctgs):
            if presel_values[ret] in ctgs:
                preselect.append(i)

    # Diálogo para seleccionar
    # ------------------------
    ret = xbmcgui.Dialog().multiselect(config.get_localized_string(59994),
                                       lista,
                                       preselect=preselect,
                                       useDetails=True)
    if not ret:
        return False  # pedido cancel
    seleccionados = [ids[i] for i in ret]

    # Guardar cambios en canales para la búsqueda
    # -------------------------------------------
    for canal in ids:
        channel_status = config.get_setting('include_in_global_search', canal)
        # if not channel_status:
        #     channel_status = True

        if channel_status and canal not in seleccionados:
            config.set_setting('include_in_global_search', False, canal)
        elif not channel_status and canal in seleccionados:
            config.set_setting('include_in_global_search', True, canal)

    return True
Ejemplo n.º 27
0
def set_context_commands(item, parent_item):
    """
    Función para generar los menus contextuales.
        1. Partiendo de los datos de item.context
             a. Metodo antiguo item.context tipo str separando las opciones por "|" (ejemplo: item.context = "1|2|3")
                (solo predefinidos)
            b. Metodo list: item.context es un list con las diferentes opciones del menu:
                - Predefinidos: Se cargara una opcion predefinida con un nombre.
                    item.context = ["1","2","3"]

                - dict(): Se cargara el item actual modificando los campos que se incluyan en el dict() en caso de
                    modificar los campos channel y action estos serán guardados en from_channel y from_action.
                    item.context = [{"title":"Nombre del menu", "action": "action del menu", "channel",
                                    "channel del menu"}, {...}]

        2. Añadiendo opciones segun criterios
            Se pueden añadir opciones al menu contextual a items que cumplan ciertas condiciones

        3. Añadiendo opciones a todos los items
            Se pueden añadir opciones al menu contextual para todos los items

    @param item: elemento que contiene los menu contextuales
    @type item: item
    @param parent_item:
    @type parent_item: item
    """
    context_commands = []
    version_xbmc = int(xbmc.getInfoLabel("System.BuildVersion").split(".", 1)[0])

    # Creamos un list con las diferentes opciones incluidas en item.context
    if type(item.context) == str:
        context = item.context.split("|")
    elif type(item.context) == list:
        context = item.context
    else:
        context = []

    # Opciones segun item.context
    for command in context:
        # Formato dict
        if type(command) == dict:
            # Los parametros del dict, se sobreescriben al nuevo context_item en caso de sobreescribir "action" y
            # "channel", los datos originales se guardan en "from_action" y "from_channel"
            if "action" in command:
                command["from_action"] = item.action
            if "channel" in command:
                command["from_channel"] = item.channel
            context_commands.append(
                (command["title"], "XBMC.RunPlugin(%s?%s)" % (sys.argv[0], item.clone(**command).tourl())))

    # Opciones segun criterios
    if "info_partido" in item.context:
        try:
            name1, name2 = item.evento.split(" vs ")
            if re.search(r'(?i)futbol|fútbol|soccer|football', item.deporte):
                try:
                    from core import channeltools
                    modo = channeltools.get_channel_setting("modo", "futbol_window")
                except:
                    modo = False
                partidoCommand = "XBMC.RunPlugin(%s?%s)" % ( sys.argv[ 0 ] , item.clone(channel="futbol_window", action="ventana", maximiza=modo).tourl())
                context_commands.append(("Abrir info del partido", partidoCommand))
        except:
            import traceback
            logger.info(traceback.format_exc())

    # Ir al Menu Principal (channel.mainlist)
    if parent_item.channel not in ["novedades", "channelselector"] and item.action != "mainlist" \
            and parent_item.action != "mainlist":
        context_commands.append(("Ir al Menu Principal", "XBMC.Container.Refresh (%s?%s)" %
                                 (sys.argv[0], Item(channel=item.channel, action="mainlist").tourl())))

    # Abrir configuración
    if parent_item.channel not in ["configuracion", "novedades", "buscador"]:
        context_commands.append(("Abrir Configuración", "XBMC.Container.Update(%s?%s)" %
                                 (sys.argv[0], Item(channel="configuracion", action="mainlist").tourl())))

    return sorted(context_commands, key=lambda comand: comand[0])
Ejemplo n.º 28
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"))
Ejemplo n.º 29
0
def get_setting(name, channel="", server="", default=None):
    """
    Returns the configuration value of the requested parameter.

    Returns the value of the parameter 'name' in the global configuration, in the own configuration of the channel 'channel' or in that of the server 'server'.

    The channel and server parameters should not be used simultaneously. If the channel name is specified it will be returned
    the result of calling channeltools.get_channel_setting (name, channel, default). If the name of the
    server will return the result of calling servertools.get_channel_setting (name, server, default). If I dont know
    Specify none of the above will return the value of the parameter in the global configuration if it exists or
    the default value otherwise.

    @param name: parameter name
    @type name: str
    @param channel: channel name
    @type channel: str
    @param server: server name
    @type server: str
    @param default: return value in case the name parameter does not exist
    @type default: any

    @return: The value of the parameter 'name'
    @rtype: any

    """

    # Specific channel setting
    if channel:
        # logger.info("get_setting reading channel setting '"+name+"' from channel json")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel, default)
        # logger.info("get_setting -> '"+repr(value)+"'")
        return value

    # Specific server setting
    elif server:
        # logger.info("get_setting reading server setting '"+name+"' from server json")
        from core import servertools
        value = servertools.get_server_setting(name, server, default)
        # logger.info("get_setting -> '"+repr(value)+"'")
        return value

    # Global setting
    else:
        # logger.info("get_setting reading main setting '"+name+"'")
        value = __settings__.getSetting(name)
        if not value:
            return default
        # Translate Path if start with "special://"
        if value.startswith("special://") and "videolibrarypath" not in name:
            value = xbmc.translatePath(value)

        # hack para devolver el tipo correspondiente
        if value == "true":
            return True
        elif value == "false":
            return False
        else:
            # special case return as str
            try:
                value = int(value)
            except ValueError:
                pass
            return value
Ejemplo n.º 30
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
Ejemplo n.º 31
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
Ejemplo n.º 32
0
def get_setting(name, channel="", server=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.pelisalacarta\settings_channels el
    archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
    devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """

    # Specific channel setting
    if channel:

        # logger.info("config.get_setting reading channel setting '"+name+"' from channel xml")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        return value
            
    elif server:
        # logger.info("config.get_setting reading server setting '"+name+"' from server xml")
        from core import servertools
        value = servertools.get_server_setting(name, server)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        return value

    # Global setting
    else:
        # logger.info("config.get_setting reading main setting '"+name+"'")
        global settings_dic
        value = settings_dic.get(name, "")
        
        if name == "adult_mode":
            global adult_setting
            id = threading.current_thread().name
            if adult_setting.get(id) == True:
                value = "2"


        # hack para devolver el tipo correspondiente
        global settings_types

        if settings_types.get(name) in ['enum', 'number']:
            value = int(value)

        elif settings_types.get(name) == 'bool':
            value = value == 'true'

        elif not settings_types.has_key(name):
            try:
                t = eval (value)
                value = t[0](t[1])
            except:
                value = None


        return value
Ejemplo n.º 33
0
def filterchannels(category, view="thumb_"):
    logger.info()

    channelslist = []
    frequent_list = []
    freq = False
    if category == 'freq':
        freq = True
        category = 'all'
    # Si category = "allchannelstatus" es que estamos activando/desactivando canales
    # Si category = "all-channels" viene del canal test
    appenddisabledchannels = False
    if category == "allchannelstatus":
        category = "all"
        appenddisabledchannels = True

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

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

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

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

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

        try:
            channel_parameters = channeltools.get_channel_parameters(channel)

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

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

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

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

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

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

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

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

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

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

            # Si tiene configuración añadimos un item en el contexto
            context = []
            if channel_parameters["has_settings"]:
                context.append({
                    "title": config.get_localized_string(70525),
                    "channel": "setting",
                    "action": "channel_config",
                    "config": channel_parameters["channel"]
                })
            if os.path.exists(
                    os.path.join(config.get_runtime_path(), 'channels',
                                 'test.py')):
                context.append({
                    "title": config.get_localized_string(70215),
                    "channel": "test",
                    "action": "test_channel",
                    "contentChannel": channel_parameters["channel"],
                    "parameters": "test_channel"
                })

            if channel_parameters["req_assistant"]:
                channel_parameters[
                    "title"] = "{} [COLOR=yellow](requiere Assistant)[/COLOR]".format(
                        channel_parameters["title"])

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

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

    if config.get_setting('frequents'):
        for ch in channelslist:
            if int(ch.frequency) != 0:
                frequent_list.append(ch)

        frequent_list = sorted(frequent_list,
                               key=lambda item: item.frequency,
                               reverse=True)

        if freq:
            max_ff = config.get_setting("max_frequents_folder")
            if max_ff > 0:
                return frequent_list[0:max_ff]
            else:
                return frequent_list

        max_freq = config.get_setting("max_frequents")
        if frequent_list and category != 'all_channels':
            if len(frequent_list) >= max_freq:
                max_freq = max_freq
            else:
                max_freq = len(frequent_list)
            frequent_list = frequent_list[0:max_freq]
            frequent_list.insert(
                0, Item(title='- Canales frecuentes -', action=''))

            frequent_list.append(Item(title='- Todos los canales -',
                                      action=''))

    elif freq:
        for ch in channelslist:
            if int(ch.frequency) != 0:
                frequent_list.append(ch)

        frequent_list = sorted(frequent_list,
                               key=lambda item: item.frequency,
                               reverse=True)

        max_ff = config.get_setting("max_frequents_folder")
        if max_ff > 0:
            return frequent_list[0:max_ff]
        else:
            return frequent_list

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

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

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

    if frequent_list and config.get_setting('frequents'):
        channelslist = frequent_list + channelslist

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

        channelslist.insert(
            3,
            Item(channel='search',
                 action='years_menu',
                 title='Por Años',
                 type=category.replace('show', ''),
                 thumbnail=get_thumb("years.png"),
                 mode=category))

        channelslist.insert(
            4,
            Item(channel='search',
                 action='genres_menu',
                 title='Generos',
                 type=category.replace('show', ''),
                 thumbnail=get_thumb("genres.png"),
                 mode=category))

    ### Especiales (Halloween, otros)
    from datetime import date

    today = date.today()

    if today.month == 10 and category == "movie":
        this_year = today.year
        from_date = "%s-01-01" % this_year
        discovery = {
            "url": "discover/movie",
            "with_genres": "27",
            "primary_release_date.lte": "%s" % today,
            "primary_release_date.gte": from_date,
            "page": "1"
        }

        channelslist.insert(
            0,
            Item(channel="search",
                 title="Halloween %s" % this_year,
                 page=1,
                 action='discover_list',
                 discovery=discovery,
                 mode="movie",
                 thumbnail=get_thumb("channels_horror.png")))
    return channelslist
Ejemplo n.º 34
0
def get_setting(name, channel="", server=""):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.streamondemand\settings_channels el archivo channel_data.json
    y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
    Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe devuelve un str vacio.

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

    Retorna:
    value -- El valor del parametro 'name'

    """

    # Specific channel setting
    if channel:

        # logger.info("config.get_setting reading channel setting '"+name+"' from channel xml")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        return value

    elif server:
        # logger.info("config.get_setting reading server setting '"+name+"' from server xml")
        from core import servertools
        value = servertools.get_server_setting(name, server)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        return value

    # Global setting
    else:
        # logger.info("config.get_setting reading main setting '"+name+"'")
        value = __settings__.getSetting(name)

        # Translate Path if start with "special://"
        if value.startswith("special://") and "librarypath" not in name:
            value = xbmc.translatePath(value)

        # hack para devolver el tipo correspondiente
        settings_types = get_settings_types()

        if settings_types.get(name) in ['enum', 'number']:
            value = int(value)

        elif settings_types.get(name) == 'bool':
            value = value == 'true'

        elif not settings_types.has_key(name):
            try:
                t = eval(value)
                value = t[0](t[1])
            except:
                value = None

        return value
Ejemplo n.º 35
0
def get_setting(name, channel="", server="", default=None):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global, en la configuracion propia del canal 'channel'
    o en la del servidor 'server'.

    Los parametros channel y server no deben usarse simultaneamente. Si se especifica el nombre del canal se devolvera
    el resultado de llamar a channeltools.get_channel_setting(name, channel, default). Si se especifica el nombre del
    servidor se devolvera el resultado de llamar a servertools.get_channel_setting(name, server, default). Si no se
    especifica ninguno de los anteriores se devolvera el valor del parametro en la configuracion global si existe o
    el valor default en caso contrario.

    @param name: nombre del parametro
    @type name: str
    @param channel: nombre del canal
    @type channel: str
    @param server: nombre del servidor
    @type server: str
    @param default: valor devuelto en caso de que no exista el parametro name
    @type default: any

    @return: El valor del parametro 'name'
    @rtype: any

    """

    # Specific channel setting
    if channel:

        # logger.info("config.get_setting reading channel setting '"+name+"' from channel json")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel, default)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        return value

    elif server:
        # logger.info("config.get_setting reading server setting '"+name+"' from server json")
        from core import servertools
        value = servertools.get_server_setting(name, server, default)
        # logger.info("config.get_setting -> '"+repr(value)+"'")

        return value

    # Global setting
    else:
        # logger.info("config.get_setting reading main setting '"+name+"'")
        global settings_dic
        value = settings_dic.get(name, default)
        if value == default:
            return value

        # logger.info("config.get_setting -> '"+value+"'")
        # hack para devolver el tipo correspondiente
        if value == "true":
            return True
        elif value == "false":
            return False
        else:
            # special case return as str
            if name in ["adult_password", "adult_aux_intro_password", "adult_aux_new_password1",
                        "adult_aux_new_password2"]:
                return value
            else:
                try:
                    value = int(value)
                except ValueError:
                    pass

                return value
Ejemplo n.º 36
0
def setting_channel_new(item):
    import xbmcgui

    # Load list of options (active user channels that allow global search)
    lista = []
    ids = []
    lista_lang = []
    lista_ctgs = []
    channels_list = channelselector.filterchannels('all')
    for channel in channels_list:
        if channel.action == '':
            continue

        channel_parameters = channeltools.get_channel_parameters(channel.channel)

        # Do not include if "include_in_global_search" does not exist in the channel configuration
        if not channel_parameters['include_in_global_search']:
            continue

        lbl = '%s' % channel_parameters['language']
        lbl += ' %s' % ', '.join(config.get_localized_category(categ) for categ in channel_parameters['categories'])

        it = xbmcgui.ListItem(channel.title, lbl)
        it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart})
        lista.append(it)
        ids.append(channel.channel)
        lista_lang.append(channel_parameters['language'])
        lista_ctgs.append(channel_parameters['categories'])

    # Pre-select dialog
    preselecciones = [
        config.get_localized_string(70570),
        config.get_localized_string(70571),
        # 'Modificar partiendo de Recomendados',
        # 'Modificar partiendo de Frecuentes',
        config.get_localized_string(70572),
        config.get_localized_string(70573),
        # 'Modificar partiendo de Castellano',
        # 'Modificar partiendo de Latino'
    ]
    # presel_values = ['skip', 'actual', 'recom', 'freq', 'all', 'none', 'cast', 'lat']
    presel_values = ['skip', 'actual', 'all', 'none']

    categs = ['movie', 'tvshow', 'documentary', 'anime', 'vos', 'direct', 'torrent']
    for c in categs:
        preselecciones.append(config.get_localized_string(70577) + config.get_localized_category(c))
        presel_values.append(c)

    if item.action == 'setting_channel':  # Configuración de los canales incluídos en la búsqueda
        del preselecciones[0]
        del presel_values[0]
    # else: # Call from "search on other channels" (you can skip the selection and go directly to the search)

    ret = platformtools.dialog_select(config.get_localized_string(59994), preselecciones)
    if ret == -1:
        return False  # order cancel
    if presel_values[ret] == 'skip':
        return True  # continue unmodified
    elif presel_values[ret] == 'none':
        preselect = []
    elif presel_values[ret] == 'all':
        preselect = list(range(len(ids)))
    elif presel_values[ret] in ['cast', 'lat']:
        preselect = []
        for i, lg in enumerate(lista_lang):
            if presel_values[ret] in lg or '*' in lg:
                preselect.append(i)
    elif presel_values[ret] == 'actual':
        preselect = []
        for i, canal in enumerate(ids):
            channel_status = config.get_setting('include_in_global_search', canal)
            if channel_status:
                preselect.append(i)

    elif presel_values[ret] == 'recom':
        preselect = []
        for i, canal in enumerate(ids):
            _not, set_canal_list = channeltools.get_channel_controls_settings(canal)
            if set_canal_list.get('include_in_global_search', False):
                preselect.append(i)

    elif presel_values[ret] == 'freq':
        preselect = []
        for i, canal in enumerate(ids):
            frequency = channeltools.get_channel_setting('frequency', canal, 0)
            if frequency > 0:
                preselect.append(i)
    else:
        preselect = []
        for i, ctgs in enumerate(lista_ctgs):
            if presel_values[ret] in ctgs:
                preselect.append(i)

    # Dialog to select
    ret = platformtools.dialog_multiselect(config.get_localized_string(59994), lista, preselect=preselect, useDetails=True)

    if ret == None: return False  # order cancel
    seleccionados = [ids[i] for i in ret]

    # Save changes to search channels
    for canal in ids:
        channel_status = config.get_setting('include_in_global_search', canal)
        # if not channel_status:
        #     channel_status = True

        if channel_status and canal not in seleccionados:
            config.set_setting('include_in_global_search', False, canal)
        elif not channel_status and canal in seleccionados:
            config.set_setting('include_in_global_search', True, canal)

    return True
Ejemplo n.º 37
0
def get_setting(name, channel="", server="", default=None):
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global, en la configuracion propia del canal 'channel' 
    o en la del servidor 'server'.

    Los parametros channel y server no deben usarse simultaneamente. Si se especifica el nombre del canal se devolvera 
    el resultado de llamar a channeltools.get_channel_setting(name, channel, default). Si se especifica el nombre del 
    servidor se devolvera el resultado de llamar a servertools.get_channel_setting(name, server, default). Si no se
    especifica ninguno de los anteriores se devolvera el valor del parametro en la configuracion global si existe o 
    el valor default en caso contrario.

    @param name: nombre del parametro
    @type name: str
    @param channel: nombre del canal
    @type channel: str
    @param server: nombre del servidor
    @type server: str
    @param default: valor devuelto en caso de que no exista el parametro name
    @type default: cualquiera

    @return: El valor del parametro 'name'
    @rtype: El tipo del valor del parametro 

    """

    # Specific channel setting
    if channel:
        # logger.info("config.get_setting reading channel setting '"+name+"' from channel json")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel, default)
        # logger.info("config.get_setting -> '"+repr(value)+"'")
        return value

    # Specific server setting
    elif server:
        # logger.info("config.get_setting reading server setting '"+name+"' from server json")
        from core import servertools
        value = servertools.get_server_setting(name, server, default)
        # logger.info("config.get_setting -> '"+repr(value)+"'")
        return value

    # Global setting
    else:
        # logger.info("config.get_setting reading main setting '"+name+"'")
        value = __settings__.getSetting(name)
        if not value:
            return default
        # Translate Path if start with "special://"
        if value.startswith("special://") and "videolibrarypath" not in name:
            value = xbmc.translatePath(value)

        # hack para devolver el tipo correspondiente
        settings_types = get_settings_types()

        if settings_types.get(name) in ['enum', 'number']:
            try:
                value = int(value)
            except Exception, ex:
                from core import logger
                logger.error(
                    "Error al convertir '%s' de tipo 'enum','number' \n%s" %
                    (name, ex))

        elif settings_types.get(name) == 'bool':
            value = value == 'true'
Ejemplo n.º 38
0
def get_setting(name, channel="", server="", default=None, caching_var=True):
    global alfa_settings
    """
    Retorna el valor de configuracion del parametro solicitado.

    Devuelve el valor del parametro 'name' en la configuracion global, en la configuracion propia del canal 'channel'
    o en la del servidor 'server'.

    Los parametros channel y server no deben usarse simultaneamente. Si se especifica el nombre del canal se devolvera
    el resultado de llamar a channeltools.get_channel_setting(name, channel, default). Si se especifica el nombre del
    servidor se devolvera el resultado de llamar a servertools.get_channel_setting(name, server, default). Si no se
    especifica ninguno de los anteriores se devolvera el valor del parametro en la configuracion global si existe o
    el valor default en caso contrario.

    @param name: nombre del parametro
    @type name: str
    @param channel: nombre del canal
    @type channel: str
    @param server: nombre del servidor
    @type server: str
    @param default: valor devuelto en caso de que no exista el parametro name
    @type default: any

    @return: El valor del parametro 'name'
    @rtype: any

    """

    # Specific channel setting
    if channel:
        # logger.info("get_setting reading channel setting '"+name+"' from channel json")
        from core import channeltools
        value = channeltools.get_channel_setting(name, channel, default, caching_var=caching_var)
        # logger.info("get_setting -> '"+repr(value)+"'")
        return value

    # Specific server setting
    elif server:
        # logger.info("get_setting reading server setting '"+name+"' from server json")
        from core import servertools
        value = servertools.get_server_setting(name, server, default, caching_var=caching_var)
        # logger.info("get_setting -> '"+repr(value)+"'")
        return value

    # Global setting
    else:
        alfa_caching = bool(window.getProperty("alfa_caching"))
        if alfa_caching and caching_var:
            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 alfa_caching and caching_var and name not in str(alfa_no_caching_vars) \
                        and alfa_settings.get(name, None) != None:
            # Si el alfa_caching está activo y la variable cargada.  Si no, se cargan por el método tradicional
            return get_setting_values(name, alfa_settings.get(name, default))
        else:
            # logger.info("get_setting reading main setting '"+name+"'")
            value = __settings__.getSetting(name)
            if not value:
                return default
            return get_setting_values(name, value, decode_var_=False)