def MostrarMenuVideo(item,itemlist):
    opciones = []
    Reproducible = False
    video_urls=0
    seleccion = -1
    for itemopcion in itemlist:
      opciones.append(itemopcion.title)
      if itemopcion.action=="play_video": 
        Reproducible = True
        video_urls+=1

    if len(opciones)>0:    
      default_action = config.get_setting("default_action")
      if default_action=="0" or not Reproducible: #Preguntar
          seleccion = xbmcgui.Dialog().select(config.get_localized_string(30163), opciones) #"Elige una opción"
      elif default_action=="1": #Ver en Calidad Baja
          seleccion = 0
      elif default_action=="2": #Ver en Calidad Alta
          seleccion = video_urls -1
      elif default_action=="3": #Mandar a jDownloader
        if config.get_setting("jdownloader_enabled")=="true":
          seleccion = opciones.index(config.get_localized_string(30158)) #"Enviar a JDownloader"
      else:
          seleccion=0
    return seleccion
def getmainlist():
    logger.info("channelselector.getmainlist")
    itemlist = []

    # Obtiene el idioma, y el literal
    idioma = config.get_setting("languagefilter")
    logger.info("channelselector.getmainlist idioma=%s" % idioma)
    langlistv = [config.get_localized_string(30025),config.get_localized_string(30026),config.get_localized_string(30027),config.get_localized_string(30028),config.get_localized_string(30029)]
    try:
        idiomav = langlistv[int(idioma)]
    except:
        idiomav = langlistv[0]

    itemlist.append( Item(channel="seriesly", title="Buscar", action="search") )
    itemlist.append( Item(channel="seriesly", title="Mis series", action="show_series", url="series" ) )
    itemlist.append( Item(channel="seriesly", title="Mis pelis", action="show_movies", url="movies" ) )
    itemlist.append( Item(channel="seriesly", title="Mis documentales", action="show_documentaries", url="documentaries" ) )
    itemlist.append( Item(channel="seriesly", title="Mis tvshows", action="show_tvshows", url="tvshows" ) )

    if "xbmceden" in config.get_platform():
        itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"configuracion.png"), folder=False) )
    else:
        itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"configuracion.png")) )

    return itemlist
def add_to_downloads(item, VideoItem = None): 
  from core import descargas
  item.title = guitools.Keyboard(item.title)
  if item.title:
    item.fulltitle=""
    descargas.GuardarDescarga(item)
    guitools.Dialog_OK(config.get_localized_string(30101) , item.title + "\n" + config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
def save_download_movie(item):
    logger.info("contentAction: %s | contentChannel: %s | contentTitle: %s" % (
    item.contentAction, item.contentChannel, item.contentTitle))

    progreso = platformtools.dialog_progress("Download", "Recupero del film")

    result = scraper.find_and_set_infoLabels(item)
    if not result:
        progreso.close()
        item.contentType = "video"
        return save_download_video(item)

    progreso.update(0, "Aggiunta del film...")

    item.downloadFilename = filetools.validate_path("%s [%s]" % (item.contentTitle.strip(), item.contentChannel))

    write_json(item)

    progreso.close()

    if not platformtools.dialog_yesno(config.get_localized_string(30101), "Avviare il download adesso?"):
        platformtools.dialog_ok(config.get_localized_string(30101), item.contentTitle,
                                config.get_localized_string(30109))
    else:
        start_download(item)
Example #5
0
def save_download_tvshow(item):
    logger.info("contentAction: %s | contentChannel: %s | contentType: %s | contentSerieName: %s" % (item.contentAction, item.contentChannel, item.contentType, item.contentSerieName))
    
    progreso = platformtools.dialog_progress("Descargas", "Obteniendo datos de la serie")
    
    tmdb.find_and_set_infoLabels_tmdb(item)
    
    item.downloadFilename = item.downloadFilename = "%s [%s]" % (item.contentSerieName, item.contentChannel)
    
    progreso.update(0, "Obteniendo episodios...", "conectando con %s..." % item.contentChannel)

    episodes = get_episodes(item)

    progreso.update(0, "Añadiendo capitulos...", " ")

    for x, i in enumerate(episodes):
        progreso.update(x * 100 / len(episodes), "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle))
        write_json(i)
    progreso.close()

    if not platformtools.dialog_yesno(config.get_localized_string(30101), "¿Iniciar la descarga ahora?"):
        platformtools.dialog_ok(config.get_localized_string(30101),
                                str(len(episodes)) + " capitulos de: " + item.contentSerieName,
                                config.get_localized_string(30109))
    else:
        for i in episodes:
            res = start_download(i)
            if res == STATUS_CODES.canceled:
                break
Example #6
0
def save_download_movie(item):
    logger.info("pelisalacarta.channels.descargas save_download_movie")
    
    progreso = platformtools.dialog_progress("Descargas", "Obteniendo datos de la pelicula")
    tmdb.find_and_set_infoLabels_tmdb(item)
    
    progreso.update(0, "Añadiendo pelicula...")
    
    item.action = "menu"
    item.channel = "descargas"
    item.downloadStatus = 0
    item.downloadProgress = 0
    item.downloadSize = 0
    item.downloadCompleted = 0
    item.downloadFilename = "%s [%s]" % (item.contentTitle.strip(), item.contentChannel)
    if item.text_color: del item.text_color
    if item.text_bold: del item.text_bold
    if item.text_italic: del item.text_italic

    item.path = filetools.encode(os.path.join(config.get_setting("downloadlistpath"), str(time.time()) + ".json"))
    filetools.write(item.path, item.tojson())
    
    progreso.close()
    
    if not platformtools.dialog_yesno(config.get_localized_string(30101), "¿Iniciar la descarga ahora?"):
        platformtools.dialog_ok(config.get_localized_string(30101), item.contentTitle,
                                config.get_localized_string(30109))
    else:
        start_download(item)
def save_download_tvshow(item):
    logger.info("contentAction: %s | contentChannel: %s | contentType: %s | contentSerieName: %s" % (
    item.contentAction, item.contentChannel, item.contentType, item.contentSerieName))

    progreso = platformtools.dialog_progress("Download", "Recupero della serie")

    scraper.find_and_set_infoLabels(item)

    item.downloadFilename = filetools.validate_path("%s [%s]" % (item.contentSerieName, item.contentChannel))

    progreso.update(0, "Recupero episodi...", "connessione a %s..." % item.contentChannel)

    episodes = get_episodes(item)

    progreso.update(0, "Aggiunta capitoli...", " ")

    for x, i in enumerate(episodes):
        progreso.update(x * 100 / len(episodes),
                        "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle))
        write_json(i)
    progreso.close()

    if not platformtools.dialog_yesno(config.get_localized_string(30101), "Avviare il download adesso?"):
        platformtools.dialog_ok(config.get_localized_string(30101),
                                str(len(episodes)) + " capitoli di: " + item.contentSerieName,
                                config.get_localized_string(30109))
    else:
        for i in episodes:
            res = start_download(i)
            if res == STATUS_CODES.canceled:
                break
Example #8
0
def add_serie_to_library(item):
  from core import library
  channelmodule = ImportarCanal(item.channel)
  if item.extra: action = item.extra
  if item.refered_action: action = item.refered_action
  
  if "###" in action:
    item.extra = action.split("###")[1]
    action = action.split("###")[0]
  item.action = action
  
  nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )
  if not os.path.exists(nombre_fichero_config_canal):
      f = open( nombre_fichero_config_canal , "w" )
  else:
      f = open( nombre_fichero_config_canal , "r" )
      contenido = f.read()
      f.close()
      f = open( nombre_fichero_config_canal , "w" )
      f.write(contenido)

  f.write(item.serialize()+"\n")
  f.close();

  exec "itemlist = channelmodule."+action+"(item)"
  for episodio in itemlist:
    if episodio.action!="add_serie_to_library" and episodio.action!="download_all_episodes":
        episodio.category="Series"
        episodio.refered_action = action
        library.Guardar(episodio)
  guitools.Dialog_OK(config.get_localized_string(30101) , item.title +"\n"+ config.get_localized_string(30135)) # 'Se ha añadido a la Biblioteca'
  library.ActualizarBiblioteca(item)   
def add_to_library(item, VideoItem = None): 
  from core import library
  item.title = guitools.Keyboard(item.title)
  if item.title:
    library.Guardar(item)
    guitools.Dialog_OK(config.get_localized_string(30101) , item.title +"\n"+ config.get_localized_string(30135)) # 'Se ha añadido a la Biblioteca'
    library.ActualizarBiblioteca(item) 
Example #10
0
def save_download_tvshow(item):
    logger.info("pelisalacarta.channels.descargas save_download_tvshow")
    logger.info("Tipo: %s" % item.contentType)
    
    progreso = platformtools.dialog_progress("Descargas", "Obteniendo datos de la serie")
    
    tmdb.find_and_set_infoLabels_tmdb(item)

    item.downloadFilename = item.downloadFilename = "%s [%s]" % (item.contentSerieName, item.contentChannel)
    episodes = get_episodes(item)

    progreso.update(0, "Añadiendo capitulos...")

    for x, i in enumerate(episodes):
        progreso.update(x * 100 / len(episodes), os.path.basename(i.downloadFilename))
        i.path = os.path.join(config.get_setting("downloadlistpath"), str(time.time()) + ".json")
        filetools.write(i.path, i.tojson())
        time.sleep(0.1)

    progreso.close()

    if not platformtools.dialog_yesno(config.get_localized_string(30101), "¿Iniciar la descarga ahora?"):
        platformtools.dialog_ok(config.get_localized_string(30101),
                                str(len(episodes)) + " capitulos de: " + item.contentSerieName,
                                config.get_localized_string(30109))
    else:
        for i in episodes:
            res = start_download(i)
            if res == 1:
                break
def add_to_favorites(item, VideoItem = None):
  from core import favoritos
  item.title = guitools.Keyboard(item.title)
  if item.title:
    item.fulltitle=""
    favoritos.GuardarFavorito(item)
    guitools.Dialog_OK(config.get_localized_string(30102) , item.title + "\n" + config.get_localized_string(30108)) # 'se ha añadido a favoritos'
def getmainlist():
    logger.info("channelselector.getmainlist")
    itemlist = []

    # Obtiene el idioma, y el literal
    idioma = config.get_setting("languagefilter")
    logger.info("channelselector.getmainlist idioma=%s" % idioma)
    langlistv = [config.get_localized_string(30025),config.get_localized_string(30026),config.get_localized_string(30027),config.get_localized_string(30028),config.get_localized_string(30029)]
    try:
        idiomav = langlistv[int(idioma)]
    except:
        idiomav = langlistv[0]
    
    # Añade los canales que forman el menú principal
    itemlist.append( Item(title=config.get_localized_string(30118)+" ("+idiomav+")" , channel="channelselector" , action="channeltypes", thumbnail = urlparse.urljoin(get_thumbnail_path(),"channelselector.png") ) )
    itemlist.append( Item(title=config.get_localized_string(30103) , channel="buscador" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(),"buscador.png")) )
    itemlist.append( Item(title=config.get_localized_string(30128) , channel="trailertools" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(),"trailertools.png")) )
    itemlist.append( Item(title=config.get_localized_string(30102) , channel="favoritos" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(),"favoritos.png")) )
    if config.get_platform() in ("wiimc","rss") :itemlist.append( Item(title="Wiideoteca (Beta)" , channel="wiideoteca" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"wiideoteca.png")) )
    if config.get_platform()=="rss":itemlist.append( Item(title="pyLOAD (Beta)" , channel="pyload" , action="mainlist" , thumbnail = urlparse.urljoin(get_thumbnail_path(),"pyload.png")) )
    itemlist.append( Item(title=config.get_localized_string(30101) , channel="descargas" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"descargas.png")) )

    if "xbmceden" in config.get_platform():
        itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"configuracion.png"), folder=False) )
    else:
        itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"configuracion.png")) )

    if config.get_setting("fileniumpremium")=="true":
    	itemlist.append( Item(title="Torrents (Filenium)" , channel="descargasfilenium" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"torrents.png")) )

    #if config.get_library_support():
    if config.get_platform()!="rss": itemlist.append( Item(title=config.get_localized_string(30104) , channel="ayuda" , action="mainlist", thumbnail = urlparse.urljoin(get_thumbnail_path(),"ayuda.png")) )
    return itemlist
def mainlist(item):
    logger.info("[justintv.py] mainlist")

    itemlist = []
    try:
        lang = config.get_setting('justin_lang')
        if "," in lang:
            langs = lang.split(",")
            lang = ''
            for i in langs:
                idx  = abbrev.index(i)
                if len(lang)>0:
                    lang = lang + "," + languages[idx]
                else:
                    lang = languages[idx]
            
        else:
            idx  = abbrev.index(lang)
            lang = languages[idx]
    except:
        lang = 'all'
        idx  = abbrev.index(lang)
        lang = languages[idx]
    

    itemlist.append( Item(channel=__channel__, title=config.get_localized_string(30420) + ' (%s)' %lang, action="_language"     ,url = "", thumbnail =WEB_PATH+ "language.jpg",fanart = fanart, folder = False))
    itemlist.append( Item(channel=__channel__, title=config.get_localized_string(30414), action="listcategory"     ,url = "true", thumbnail='http://www-cdn.jtvnw.net/images/redesign/fp_vector_camera.png',fanart = fanart))
    itemlist.append( Item(channel=__channel__, title=config.get_localized_string(30413), action="listcategory"     ,url = "false", thumbnail='',fanart = fanart))
    return itemlist
Example #14
0
def add_pelicula_to_library(item):
    """
        guarda una pelicula en la libreria de cine. La pelicula puede ser un enlace dentro de un canal o un video
        descargado previamente.

        Para añadir episodios descargados en local, el item debe tener exclusivamente:
            - contentTitle: titulo de la pelicula
            - title: titulo a mostrar junto al listado de enlaces -findvideos- ("Reproducir video local HD")
            - infoLabels["tmdb_id"] o infoLabels["imdb_id"]
            - contentType == "movie"
            - channel = "descargas"
            - url : ruta local al video

        @type item: item
        @param item: elemento que se va a guardar.
    """
    logger.info("pelisalacarta.platformcode.library add_pelicula_to_library")

    new_item = item.clone(action="findvideos")
    insertados, sobreescritos, fallidos = save_library_movie(new_item)

    if fallidos == 0:
        platformtools.dialog_ok(config.get_localized_string(30131), new_item.contentTitle,
                                config.get_localized_string(30135))  # 'se ha añadido a la biblioteca'
    else:
        platformtools.dialog_ok(config.get_localized_string(30131),
                                "ERROR, la pelicula NO se ha añadido a la biblioteca")
def buscartrailer(params,url,category):
    print "[trailertools.py] Modulo: buscartrailer()"
    thumbnail = ""
    solo = "false"
    videotitle = title = urllib.unquote_plus( params.get("title") ).strip()
    if ":]" in videotitle:
        solo = "true"
        videotitle = re.sub("\[[^\]]+\]","",videotitle).strip()
    if config.get_localized_string(30110) in videotitle: #"Buscar trailer para"
        videotitle = videotitle.replace(config.get_localized_string(30110),"").strip()
    if config.get_localized_string(30111) in videotitle: #"Insatisfecho?, busca otra vez : "
        videotitle = videotitle.replace(config.get_localized_string(30111),"").strip()
    
        listavideos = GetTrailerbyKeyboard(videotitle.strip(),category)
    else:
        listavideos = gettrailer(videotitle.strip().strip(),category,solo)
    
    if len(listavideos)>0:
        for video in listavideos:
            titulo = video[1]
            url        = video[0]
            thumbnail  = video[2]
            duracion = video[3]
            xbmctools.addnewvideo( "trailertools" , "youtubeplay" , category , "youtube" ,  titulo , url , thumbnail , "Ver Video","",duracion )
    
    xbmctools.addnewfolder( CHANNELNAME , "buscartrailer" , category , config.get_localized_string(30111)+" "+videotitle , url , os.path.join(IMAGES_PATH, 'trailertools.png'), "" ) #"Insatisfecho?, busca otra vez : "        
    # Propiedades
    xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
    xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def remove_from_favorites(item, itemSeleccion=-1): 
  from core import favoritos
  # En "extra" está el nombre del fichero en favoritos
  favoritos.BorrarFavorito(item)

  xbmcgui.Dialog().ok(config.get_localized_string(30102) , item.title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'
  xbmc.executebuiltin( "Container.Refresh" )
def getchanneltypes():
    logger.info("channelselector getchanneltypes")
    itemlist = []
    itemlist.append( Item( title=config.get_localized_string(30121) , channel="channelselector" , action="listchannels" , category="*"   , thumbnail=urlparse.urljoin(get_thumbnail_path(),"channelselector")))
    itemlist.append( Item( title=config.get_localized_string(30122) , channel="channelselector" , action="listchannels" , category="F"   , thumbnail=urlparse.urljoin(get_thumbnail_path(),"peliculas")))
    itemlist.append( Item( title=config.get_localized_string(30123) , channel="channelselector" , action="listchannels" , category="S"   , thumbnail=urlparse.urljoin(get_thumbnail_path(),"series")))

    return itemlist
    def start(self, list_controls=None, dict_values=None, title="Opciones", callback=None, item=None,
              custom_button=None, channelpath = None):
        logger.info("[xbmc_config_menu] start")

        # Ruta para las imagenes de la ventana
        self.mediapath = os.path.join(config.get_runtime_path(), 'resources', 'skins', 'Default', 'media')

        # Capturamos los parametros
        self.list_controls = list_controls
        self.values = dict_values
        self.title = title
        self.callback = callback
        self.item = item
        
        
        if type(custom_button) == dict:
          self.custom_button = {} 
          self.custom_button["label"] = custom_button.get("label", "")
          self.custom_button["function"] = custom_button.get("function", "")
          self.custom_button["visible"] = bool(custom_button.get("visible", True))
          self.custom_button["close"] = bool(custom_button.get("close", False))
        else:
          self.custom_button = None
          

        # Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal
        if not channelpath:
          channelpath = inspect.currentframe().f_back.f_back.f_code.co_filename
        self.channel = os.path.basename(channelpath).replace(".py", "")

        # Si no tenemos list_controls, hay que sacarlos del xml del canal
        if not self.list_controls:

            # Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools
            if os.path.join(config.get_runtime_path(), "channels") in channelpath:

                # La llamada se hace desde un canal
                self.list_controls, default_values = channeltools.get_channel_controls_settings(self.channel)

            # En caso contrario salimos
            else:
                return None

        # Si no se pasan dict_values, creamos un dict en blanco
        if self.values is None:
            self.values = {}

        # Ponemos el titulo
        if self.title == "":
            self.title = str(config.get_localized_string(30100)) + " -- " + self.channel.capitalize()

        elif self.title.startswith('@') and unicode(self.title[1:]).isnumeric():
            self.title = config.get_localized_string(int(self.title[1:]))

        # Muestra la ventana
        self.return_value = None
        self.doModal()
        return self.return_value
def add_to_downloads(item, itemSeleccion=-1): 
  from core import descargas
  from core import downloadtools
  keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(item.title))
  keyboard.doModal()
  if keyboard.isConfirmed():
      item.title = keyboard.getText()
      descargas.GuardarDescarga(item)
      xbmcgui.Dialog().ok(config.get_localized_string(30101) , item.title , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
def add_to_favorites(item, itemSeleccion=-1):
  from core import favoritos
  from core import downloadtools
  keyboard = xbmc.Keyboard(item.title)
  keyboard.doModal()
  if keyboard.isConfirmed():
      item.title = keyboard.getText()
      favoritos.GuardarFavorito(item)
      xbmcgui.Dialog().ok(config.get_localized_string(30102) , item.title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
Example #21
0
def listchannels(params,url,category):
	logger.info("[channelselector.py] listchannels")

	# Verifica actualizaciones solo en el primer nivel
	try:
		import updater
	except ImportError:
		logger.info("[channelselector.py] No disponible modulo actualizaciones")
	else:
		if config.get_setting("updatecheck2") == "true":
			logger.info("[channelselector.py] Verificar actualizaciones activado")
			updater.checkforupdates()
		else:
			logger.info("[channelselector.py] Verificar actualizaciones desactivado")

	addfolder("Antena3","antena3","mainlist")
	addfolder("ADNStream","adnstream","mainlist")
	addfolder("Barcelona TV","barcelonatv","mainlist")
	addfolder("Clan TV","clantve","mainlist")
	addfolder("El cine de las 3 mellizas","tresmellizas","mainlist")
	#addfolder("Boing","boing","mainlist")
	#addfolder("Totlol","totlol","mainlist")
	addfolder("EITB","eitb","mainlist")
	addfolder("Extremadura TV","extremaduratv","mainlist")
	addfolder("Hogarutil","hogarutil","mainlist")
	addfolder("Plus TV","plus","mainlist")
	addfolder("Andalucia TV","rtva","mainlist")
	addfolder("TVE","rtve","mainlist")
	addfolder("TVE Programas","rtveprogramas","mainlist")
	addfolder("TVE Mediateca","rtvemediateca","mainlist")
	#addfolder("TV Azteca","tva","mainlist")
	addfolder("Berria TB","berriatb","mainlist")
	addfolder("Earth TV","earthtv","mainlist")
	addfolder("Euronews","euronews","mainlist")
	addfolder("Comunidad Valenciana","rtvv","mainlist")
	#addfolder("Terra TV","terratv","mainlist")
	addfolder("Turbonick","turbonick","mainlist")
	addfolder("TV3","tv3","mainlist")
	addfolder("TVG","tvg","mainlist")
	addfolder("Mallorca TV","tvmallorca","mainlist")
	addfolder("Meristation","meristation","mainlist")
	addfolder("7rm","sieterm","mainlist")
	addfolder("Televisión Canaria","rtvc","mainlist")
	addfolder("Internautas TV","internautastv","mainlist")
	addfolder("Publico.tv","publicotv","mainlist")
	
	cadena = config.get_localized_string(30100)
	logger.info("cadena="+cadena)
	addfolder(cadena,"configuracion","mainlist") # Configuracion
	if (parametrizacion.DOWNLOAD_ENABLED):
		addfolder(config.get_localized_string(30101),"descargados","mainlist")   # Descargas
	addfolder(config.get_localized_string(30102),"favoritos","mainlist")     # Favoritos

	# Label (top-right)...
	xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category="Canales" )
	xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
	xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def alertnoencontrado(titulo):
    advertencia = xbmcgui.Dialog()
    #'Trailer no encontrado'
    #'El Trailer para "%s"'
    #'no se ha podido localizar.'
    #'�Deseas seguir buscando con el teclado?'
    tituloq = '"'+titulo+'"'
    resultado = advertencia.yesno(config.get_localized_string(30114), config.get_localized_string(30115) % tituloq, config.get_localized_string(30116),config.get_localized_string(30117))
    return(resultado)
Example #23
0
def getmainlist():
    logger.info("[channelselector.py] getmainlist")
    itemlist = []

    itemlist.append( Item(title=config.get_localized_string(30118) , channel="channelselector" , action="channeltypes") )
    itemlist.append( Item(title=config.get_localized_string(30102) , channel="favoritos" , action="mainlist") )
    itemlist.append( Item(title=config.get_localized_string(30101) , channel="descargas" , action="mainlist") )
    itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist") )

    return itemlist
def getmainlist(params,url,category):
    logger.info("[cinetube.py] getmainlist")

    itemlist = []
    itemlist.append( Item(channel=CHANNELNAME, title=config.get_localized_string(30401)    , action="listWall", url="http://www.megalive.com/"      , folder=True) )
    itemlist.append( Item(channel=CHANNELNAME, title= config.get_localized_string(30402)      , action="listcategory", url="http://www.megalive.com/?c=streams", folder=True) )
    itemlist.append( Item(channel=CHANNELNAME, title=config.get_localized_string(30403) , action="listfavorites"     , url=""                                       , folder=True) )
    itemlist.append( Item(channel=CHANNELNAME, title=config.get_localized_string(30404)   , action="playByID"             , url=""       , folder=True) )
    
    return itemlist
def getchanneltypes():
    logger.info("channelselector.getchanneltypes")
    itemlist = []
    itemlist.append( Item( title=config.get_localized_string(30121) , channel="channelselector" , action="listchannels" , category="*"   , thumbnail="channels.png"))
    itemlist.append( Item( title=config.get_localized_string(30129) , channel="channelselector" , action="listchannels" , category="N"   , thumbnail="channels-national.png"))
    itemlist.append( Item( title=config.get_localized_string(30130) , channel="channelselector" , action="listchannels" , category="R"   , thumbnail="channels-regional.png"))
    itemlist.append( Item( title=config.get_localized_string(30132) , channel="channelselector" , action="listchannels" , category="T"   , thumbnail="channels-thematic.png"))
    itemlist.append( Item( title=config.get_localized_string(30133) , channel="channelselector" , action="listchannels" , category="I"   , thumbnail="channels-children.png"))
    #itemlist.append( Item( title=config.get_localized_string(30134) , channel="channelselector" , action="listchannels" , category="NEW" , thumbnail="novedades"))
    return itemlist
Example #26
0
def check_video_options(item, video_urls):
  itemlist = []
  #Opciones Reproducir
  playable = (len(video_urls) > 0)
  
  for video_url in video_urls:
    itemlist.append(item.clone(option=config.get_localized_string(30151) + " " + video_url[0], video_url= video_url[1], action="play_video"))
  
  if item.server=="local":                            
    itemlist.append(item.clone(option=config.get_localized_string(30164), action="delete_file"))
    
  if not item.server=="local" and playable:           
    itemlist.append(item.clone(option=config.get_localized_string(30153), action="download", video_urls = video_urls))

  if item.channel=="favoritos":                       
    itemlist.append(item.clone(option=config.get_localized_string(30154), action="remove_from_favorites"))
    
  if not item.channel=="favoritos" and playable:      
    itemlist.append(item.clone(option=config.get_localized_string(30155), action="add_to_favorites", item_action = item.action))

  if not item.strmfile and playable and item.contentType == "movie":                  
    itemlist.append(item.clone(option=config.get_localized_string(30161), action="add_to_library", item_action = item.action))

  if config.get_setting("jdownloader_enabled")=="true" and playable:
    itemlist.append(item.clone(option=config.get_localized_string(30158), action="send_to_jdownloader"))
  if config.get_setting("pyload_enabled")=="true" and playable:
    itemlist.append(item.clone(option=config.get_localized_string(30158).replace("jdownloader","pyLoad"), action="send_to_pyload")) 
    
  if not item.channel in ["Trailer","ecarteleratrailers"] and playable:
    itemlist.append(item.clone(option=config.get_localized_string(30162), action="search_trailer"))
    
  return itemlist
Example #27
0
  def AbrirConfig(self,Opciones):
    from core import config
    SetData(None)
    JsonData = {}
    JsonOpciones={}
    JsonOpciones["Count"]=0
    for Opcion in Opciones:
      try:
        Opcion[0] = get_localized_string(int(Opcion[0]))
      except:
        pass
      try:
        ops = Opcion[3].split("|")
        for x, op in enumerate(ops):
          ops[x] = get_localized_string(int(ops[x])) 
        Opcion[3] = "|".join(ops)
      except:
        pass
      try:
        Opcion[8] = get_localized_string(int(Opcion[8]))
      except:
        pass
      
      JsonOpciones["Label"+str(JsonOpciones["Count"])] = Opcion[0]
      JsonOpciones["Id"+str(JsonOpciones["Count"])] = Opcion[1]
      JsonOpciones["Type"+str(JsonOpciones["Count"])] = Opcion[2]
      JsonOpciones["Lvalues"+str(JsonOpciones["Count"])] = Opcion[3]
      JsonOpciones["Values"+str(JsonOpciones["Count"])] = Opcion[4]
      JsonOpciones["Value"+str(JsonOpciones["Count"])] = Opcion[5]
      JsonOpciones["Option"+str(JsonOpciones["Count"])] = Opcion[6]
      JsonOpciones["Enabled"+str(JsonOpciones["Count"])] = Opcion[7]
      JsonOpciones["Category"+str(JsonOpciones["Count"])] = Opcion[8]
      JsonOpciones["Count"]+=1
      
    JsonData["Action"]="OpenConfig"    
    JsonData["Options"]=JsonOpciones

    SendMessage(json.dumps(JsonData))
    #logger.info("-----------------------------------------------------------------------")
    #logger.info("Petición de 'OpenConfig' enviada")
    while GetData() == None:
      continue
    #logger.info("Respuesta Recibida: " + GetData())
    #logger.info("-----------------------------------------------------------------------")
    
    if GetData():
      if GetData() <> "-1":
        JsonRespuesta = json.loads(GetData())
        from core import config
        config.set_settings(JsonRespuesta)
      JsonData = {}
      JsonData["Action"]="HideLoading"
      SendMessage(json.dumps(JsonData))
def getmainlist(preferred_thumb=""):
    logger.info("channelselector.getmainlist")
    itemlist = list()

    # Añade los canales que forman el menú principal
    itemlist.append(Item(title=config.get_localized_string(30130),
                         channel="novedades", action="mainlist",
                         thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                    "thumb_novedades.png"),
                         viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30118),
                         channel="channelselector", action="channeltypes",
                         thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                    "thumb_canales.png"),
                         viewmode="movie"))

    itemlist.append(Item(title=config.get_localized_string(30103),
                         channel="buscador", action="mainlist",
                         thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                    "thumb_buscar.png"),
                         viewmode="list"))
    itemlist.append(Item(title=config.get_localized_string(30102),
                         channel="favoritos", action="mainlist",
                         thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                    "thumb_favoritos.png"),
                         viewmode="movie"))
    if config.get_library_support():
        itemlist.append(Item(title=config.get_localized_string(30131),
                             channel="biblioteca", action="mainlist",
                             thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                        "thumb_biblioteca.png"),
                             viewmode="movie"))
    itemlist.append(Item(title=config.get_localized_string(30101), channel="descargas",
                         action="mainlist",
                         thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                    "thumb_descargas.png"),
                         viewmode="movie"))

    if "xbmceden" in config.get_platform():
        itemlist.append(Item(title=config.get_localized_string(30100),
                             channel="configuracion", action="mainlist",
                             thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                        "thumb_configuracion.png"),
                             folder=False, viewmode="list"))
    else:
        itemlist.append(Item(title=config.get_localized_string(30100),
                             channel="configuracion", action="mainlist",
                             thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb),
                                                        "thumb_configuracion.png"),
                             viewmode="list"))
        # Se ha insertado "folder=False" para que no se habra una ventana tras salir de la configuracion


    itemlist.append(Item(title=config.get_localized_string(30104), channel="ayuda", action="mainlist",
                         thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "thumb_ayuda.png"),
                         viewmode="list"))
    return itemlist
def getmainlist():
    logger.info("channelselector.getmainlist")
    itemlist = []

    itemlist.append( Item(title=config.get_localized_string(30118) , channel="channelselector" , action="channeltypes", thumbnail="channels.png") )
    itemlist.append( Item(title=config.get_localized_string(30102) , channel="favoritos" , action="mainlist", thumbnail="favorites.png") )
    itemlist.append( Item(title=config.get_localized_string(30101) , channel="descargas" , action="mainlist", thumbnail="downloads.png") )

    if "xbmceden" in config.get_platform():
        itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist", thumbnail="settings.png", folder=False) )
    else:
        itemlist.append( Item(title=config.get_localized_string(30100) , channel="configuracion" , action="mainlist", thumbnail="settings.png") )

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

    # Lista de categorias
    channel_types = ["movie", "serie", "anime", "documentary", "vos", "torrent", "latino"]
    dict_types_lang = {'movie': config.get_localized_string(30122), 'serie': config.get_localized_string(30123),
                       'anime': config.get_localized_string(30124), 'documentary': config.get_localized_string(30125),
                       'vos': config.get_localized_string(30136), 'adult': config.get_localized_string(30126),
                       'latino': config.get_localized_string(30127)}
    if config.get_setting("adult_mode") != "0":
        channel_types.append("adult")

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

    # Ahora construye el itemlist ordenadamente
    itemlist = list()
    title = config.get_localized_string(30121)
    itemlist.append(Item(title=title, channel="channelselector", action="filterchannels",
                         category=title, channel_type="all",
                         thumbnail=urlparse.urljoin(get_thumbnail_path(preferred_thumb), "thumb_canales_todos.png"),
                         viewmode="thumbnails"))

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

    return itemlist
Example #31
0
def alertanomegauploadlow(server):
    advertencia = xbmcgui.Dialog()
    #'La calidad elegida no esta disponible', 'o el video ha sido borrado',
    #'Prueba a reproducir en otra calidad'
    resultado = advertencia.ok( config.get_localized_string(30055) , config.get_localized_string(30061) , config.get_localized_string(30062))
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:
        # Predefinidos
        if type(command) == str:
            if command == "buscar_trailer" or item.action == "findvideos":
                context_commands.append(
                    ("cerca Trailer", "XBMC.RunPlugin(%s?%s)" %
                     (sys.argv[0],
                      item.clone(channel="trailertools",
                                 action="buscartrailer",
                                 contextual=True).tourl())))

        # 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, solo si el item no es un tag (etiqueta), ni es "Añadir a la biblioteca"
    if item.action and item.action not in [
            "add_pelicula_to_library", "add_serie_to_library"
    ]:
        # Mostrar informacion: si el item tiene plot suponemos q es una serie, temporada, capitulo o pelicula
        if item.infoLabels['plot']:
            context_commands.append(("Informazioni", "XBMC.Action(Info)"))

        # ExtendedInfo: Si esta instalado el addon y se cumplen una serie de condiciones
        if xbmc.getCondVisibility(
                'System.HasAddon(script.extendedinfo)') and config.get_setting(
                    "extended_info") == "true":
            if item.contentType == "episode" and item.contentEpisodeNumber and item.contentSeason \
                    and (item.infoLabels['tmdb_id'] or item.contentSerieName):
                param = "tvshow_id =%s, tvshow=%s, season=%s, episode=%s" \
                        % (item.infoLabels['tmdb_id'], item.contentSerieName, item.contentSeason,
                           item.contentEpisodeNumber)
                context_commands.append((
                    "ExtendedInfo",
                    "XBMC.RunScript(script.extendedinfo,info=extendedepisodeinfo,%s)"
                    % param))

            elif item.contentType == "season" and item.contentSeason \
                    and (item.infoLabels['tmdb_id'] or item.contentSerieName):
                param = "tvshow_id =%s,tvshow=%s, season=%s" \
                        % (item.infoLabels['tmdb_id'], item.contentSerieName, item.contentSeason)
                context_commands.append(
                    ("ExtendedInfo",
                     "XBMC.RunScript(script.extendedinfo,info=seasoninfo,%s)" %
                     param))

            elif item.contentType == "tvshow" and (
                    item.infoLabels['tmdb_id'] or item.infoLabels['tvdb_id']
                    or item.infoLabels['imdb_id'] or item.contentSerieName):
                param = "id =%s,tvdb_id=%s,imdb_id=%s,name=%s" \
                        % (item.infoLabels['tmdb_id'], item.infoLabels['tvdb_id'], item.infoLabels['imdb_id'],
                           item.contentSerieName)
                context_commands.append((
                    "ExtendedInfo",
                    "XBMC.RunScript(script.extendedinfo,info=extendedtvinfo,%s)"
                    % param))

            elif item.contentType == "movie" and (item.infoLabels['tmdb_id']
                                                  or item.infoLabels['imdb_id']
                                                  or item.contentTitle):
                param = "id =%s,imdb_id=%s,name=%s" \
                        % (item.infoLabels['tmdb_id'], item.infoLabels['imdb_id'], item.contentTitle)
                context_commands.append(
                    ("ExtendedInfo",
                     "XBMC.RunScript(script.extendedinfo,info=extendedinfo,%s)"
                     % param))

        # 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(
                ("Vai a menù principale", "XBMC.Container.Refresh (%s?%s)" %
                 (sys.argv[0], Item(channel=item.channel,
                                    action="mainlist").tourl())))

        # Añadir a Favoritos
        if version_xbmc < 17 and (
            (item.channel not in ["favoritos", "biblioteca", "ayuda", ""]
             or item.action in ["update_biblio"])
                and not parent_item.channel == "favoritos"):
            context_commands.append(
                (config.get_localized_string(30155), "XBMC.RunPlugin(%s?%s)" %
                 (sys.argv[0],
                  item.clone(channel="favoritos",
                             action="addFavourite",
                             from_channel=item.channel,
                             from_action=item.action).tourl())))

        # Añadimos opción contextual para Añadir la serie completa a la biblioteca
        if item.channel != "biblioteca" and item.action in ["episodios", "get_episodios"] \
                and item.contentSerieName:
            context_commands.append(
                ("Aggiungi serie a libreria", "XBMC.RunPlugin(%s?%s)" %
                 (sys.argv[0],
                  item.clone(action="add_serie_to_library",
                             from_action=item.action).tourl())))

        # Añadir Pelicula a Biblioteca
        if item.channel != "biblioteca" and item.action in ["detail", "findvideos"] \
                and item.contentType == 'movie':
            context_commands.append(
                ("Aggiungi film a libreria", "XBMC.RunPlugin(%s?%s)" %
                 (sys.argv[0],
                  item.clone(action="add_pelicula_to_library",
                             from_action=item.action).tourl())))

        # Descargar pelicula
        if item.contentType == "movie" and not item.channel == "descargas":
            context_commands.append(
                ("Scarica film", "XBMC.RunPlugin(%s?%s)" %
                 (sys.argv[0],
                  item.clone(channel="descargas",
                             action="save_download",
                             from_channel=item.channel,
                             from_action=item.action).tourl())))

        # Descargar serie
        if item.contentType == "tvshow" and not item.channel == "descargas":
            context_commands.append(
                ("Scarica serie", "XBMC.RunPlugin(%s?%s)" %
                 (sys.argv[0],
                  item.clone(channel="descargas",
                             action="save_download",
                             from_channel=item.channel,
                             from_action=item.action).tourl())))

        # Descargar episodio
        if item.contentType == "episode" and not item.channel == "descargas":
            context_commands.append(
                ("Scarica episodio", "XBMC.RunPlugin(%s?%s)" %
                 (sys.argv[0],
                  item.clone(channel="descargas",
                             action="save_download",
                             from_channel=item.channel,
                             from_action=item.action).tourl())))

        # Descargar temporada
        if item.contentType == "season" and not item.channel == "descargas":
            context_commands.append(
                ("Scarica stagione", "XBMC.RunPlugin(%s?%s)" %
                 (sys.argv[0],
                  item.clone(channel="descargas",
                             action="save_download",
                             from_channel=item.channel,
                             from_action=item.action).tourl())))
        # Abrir configuración
        if parent_item.channel not in [
                "configuracion", "novedades", "buscador"
        ]:
            context_commands.append(
                ("Configurazione", "XBMC.Container.Update(%s?%s)" %
                 (sys.argv[0], Item(channel="configuracion",
                                    action="mainlist").tourl())))

    # Añadir SuperFavourites al menu contextual (1.0.53 o superior necesario)
    sf_file_path = xbmc.translatePath(
        "special://home/addons/plugin.program.super.favourites/LaunchSFMenu.py"
    )
    check_sf = os.path.exists(sf_file_path)
    if check_sf and xbmc.getCondVisibility(
            'System.HasAddon("plugin.program.super.favourites")'):
        context_commands.append((
            "Super Favourites",
            "XBMC.RunScript(special://home/addons/plugin.program.super.favourites/LaunchSFMenu.py)"
        ))

    #context_commands.append((item.contentType, "XBMC.Action(Info)")) # For debug
    return sorted(context_commands, key=lambda comand: comand[0])
def get_dialogo_opciones(item, default_action, strm):
    logger.info("platformtools get_dialogo_opciones")
    #logger.debug(item.tostring('\n'))
    from core import servertools

    opciones = []
    error = False

    try:
        item.server = item.server.lower()
    except AttributeError:
        item.server = ""

    if item.server == "":
        item.server = "directo"

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode") == "0" and not strm)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    #Permitir varias calidades para server "directo"
    if item.video_urls:
        video_urls, puedes, motivo = item.video_urls, True, ""
    else:
        video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
            item.server, item.url, item.password, muestra_dialogo)

    seleccion = 0
    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        for video_url in video_urls:
            opciones.append(
                config.get_localized_string(30151) + " " + video_url[0])

        if item.server == "local":
            opciones.append(config.get_localized_string(30164))
        else:
            # "Descargar"
            opcion = config.get_localized_string(30153)
            opciones.append(opcion)

            if item.isFavourite:
                # "Quitar de favoritos"
                opciones.append(config.get_localized_string(30154))
            else:
                # "Añadir a favoritos"
                opciones.append(config.get_localized_string(30155))

            if not strm and item.contentType == 'movie':
                # "Añadir a Biblioteca"
                opciones.append(config.get_localized_string(30161))

            if config.get_setting("jdownloader_enabled") == "true":
                # "Enviar a JDownloader"
                opciones.append(config.get_localized_string(30158))

        if default_action == "3":
            seleccion = len(opciones) - 1

        # Busqueda de trailers en youtube
        if item.channel not in ["Trailer", "ecarteleratrailers"]:
            # "Buscar Trailer"
            opciones.append(config.get_localized_string(30162))

    # Si no puedes ver el vídeo te informa
    else:
        if item.server != "":
            if "<br/>" in motivo:
                dialog_ok(
                    "Non è possibile visualizzare questo video perché...",
                    motivo.split("<br/>")[0],
                    motivo.split("<br/>")[1], item.url)
            else:
                dialog_ok(
                    "Non è possibile visualizzare questo video perché...",
                    motivo, item.url)
        else:
            dialog_ok("Non è possibile visualizzare questo video perché...",
                      "Il server che lo ospita non è",
                      "ancora supportato da streamondemand", item.url)

        if item.channel == "favoritos":
            # "Quitar de favoritos"
            opciones.append(config.get_localized_string(30154))

        if len(opciones) == 0:
            error = True

    return opciones, video_urls, seleccion, error
Example #34
0
def run():
    logger.info("streamondemand.platformcode.launcher run")
    
    # Test if all the required directories are created
    config.verify_directories_created()
    
    # Extract parameters from sys.argv
    params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password = extract_parameters()
    logger.info("streamondemand.platformcode.launcher fanart=%s, channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s" % (fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password))

    try:
        # Accion por defecto - elegir canal
        if ( action=="selectchannel" ):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)
            
            
            if config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

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

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

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

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

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

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

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

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            
            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

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

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

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

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

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

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

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

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

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

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

                    logger.info("item.server=#"+item.server+"#")
                    # Ejecuta find_videos, del canal o común
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    if len(itemlist)>0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)
    
                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)
                    
                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]
    
                        if seleccion==-1:
                            return
                    else:
                        elegido = item
                
                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" % (item.title,item.subtitle))
                    
                    from platformcode import xbmctools
                    logger.info("subtitle="+item.subtitle)
                    xbmctools.play_video(strmfile=True, channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=fulltitle)

                elif action=="add_pelicula_to_library":
                    logger.info("streamondemand.platformcode.launcher add_pelicula_to_library")
                    from platformcode import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary( titulo=item.fulltitle , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Cine" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )

                elif action=="add_serie_to_library":
                    logger.info("streamondemand.platformcode.launcher add_serie_to_library, show=#"+item.show+"#")
                    from platformcode import library
                    import xbmcgui
                
                    # Obtiene el listado desde el que se llamó
                    action = item.extra
                    
                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

                    exec "itemlist = channel."+action+"(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info ("[launcher.py] Total Episodios:"+str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
                        logger.info("streamondemand.platformcode.launcher add_serie_to_library, title="+item.title)
                        if (pDialog.iscanceled()):
                            return
                
                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                                nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle, extra=item.extra )
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error( "%s" % line )
                            logger.info("streamondemand.platformcode.launcher Error al grabar el archivo "+item.title)
                            errores = errores + 1
                        
                    pDialog.close()
                    
                    # Actualizacion de la biblioteca
                    itemlist=[]
                    if errores > 0:
                        itemlist.append(Item(title="ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"))
                        logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios")
                    else:
                        itemlist.append(Item(title="La serie è stata aggiunta alla biblioteca"))
                        logger.info ("[launcher.py] Ningún error al añadir "+str(errores)+" episodios")
                    
                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)
                    
                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
                    if not os.path.exists(nombre_fichero_config_canal):
                        nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

                    logger.info("nombre_fichero_config_canal="+nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open( nombre_fichero_config_canal , "w" )
                    else:
                        f = open( nombre_fichero_config_canal , "r" )
                        contenido = f.read()
                        f.close()
                        f = open( nombre_fichero_config_canal , "w" )
                        f.write(contenido)
                    from platformcode import library
                    f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
                    f.close();

                elif action=="download_all_episodes":
                    download_all_episodes(item,channel)

                elif action=="search":
                    logger.info("streamondemand.platformcode.launcher search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info("streamondemand.platformcode.launcher executing channel '"+action+"' method")
                    if action!="findvideos":
                        exec "itemlist = channel."+action+"(item)"
                            
                        #for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, 'findvideos'):
                            exec "itemlist = channel."+action+"(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info("streamondemand.platformcode.launcher no channel 'findvideos' method, executing core method")
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)

                        from platformcode import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys
                    handle = sys.argv[1]
                    xbmcplugin.setContent(int( handle ),"movies")
                    
                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError,e:
        import traceback,sys
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %s , Razon: %s" % (e.reason[0], e.reason[1]))
            texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web"
            ok = ventana_error.ok ("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado     
        elif hasattr(e,'code'):
            logger.info("codigo de error HTTP : %d" %e.code)
            texto = (config.get_localized_string(30051) % e.code) # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok ("plugin", texto)    
Example #35
0
TMDB_URL_BASE = 'http://api.themoviedb.org/3/'
TMDB_IMAGES_BASEURL = 'http://image.tmdb.org/t/p/'
INCLUDE_ADULT = 'true' if config.get_setting("enableadultmode") else 'false'
LANGUAGE_ID = 'it'

DTTIME = (datetime.datetime.utcnow() - datetime.timedelta(hours=5))
SYSTIME = DTTIME.strftime('%Y%m%d%H%M%S%f')
TODAY_TIME = DTTIME.strftime('%Y-%m-%d')
MONTH_TIME = (DTTIME - datetime.timedelta(days=30)).strftime('%Y-%m-%d')
MONTH2_TIME = (DTTIME - datetime.timedelta(days=60)).strftime('%Y-%m-%d')
YEAR_DATE = (DTTIME - datetime.timedelta(days=365)).strftime('%Y-%m-%d')

TIMEOUT_TOTAL = 60

NLS_Search_by_Title = config.get_localized_string(30980)
NLS_Search_by_Person = config.get_localized_string(30981)
NLS_Search_by_Company = config.get_localized_string(30982)
NLS_Now_Playing = config.get_localized_string(30983)
NLS_Popular = config.get_localized_string(30984)
NLS_Top_Rated = config.get_localized_string(30985)
NLS_Search_by_Collection = config.get_localized_string(30986)
NLS_List_by_Genre = config.get_localized_string(30987)
NLS_Search_by_Year = config.get_localized_string(30988)
NLS_Search_Similar_by_Title = config.get_localized_string(30989)
NLS_Search_Tvshow_by_Title = config.get_localized_string(30990)
NLS_Most_Voted = config.get_localized_string(30996)
NLS_Oscar = config.get_localized_string(30997)
NLS_Last_2_months = config.get_localized_string(30998)
NLS_Library = config.get_localized_string(30991)
NLS_Next_Page = config.get_localized_string(30992)
Example #36
0
def alertnodisponibleserver(server):
    advertencia = xbmcgui.Dialog()
    # 'El vídeo ya no está en %s' , 'Prueba en otro servidor o en otro canal'
    resultado = advertencia.ok( config.get_localized_string(30055),(config.get_localized_string(30057)%server),config.get_localized_string(30058))
Example #37
0
    def show_channel_settings(self, list_controls=None, dict_values=None, caption="", callback=None, item=None, custom_button=None, channelpath=None):
      from core import config
      from core import channeltools
      import inspect
      if not os.path.isdir(os.path.join(config.get_data_path(), "settings_channels")):
         os.mkdir(os.path.join(config.get_data_path(), "settings_channels"))
         
                
      title = caption

      if type(custom_button) == dict:
        custom_button = {"label"    : custom_button.get("label", ""),
                         "function" : custom_button.get("function", ""),
                         "visible"  : bool(custom_button.get("visible", True)),
                         "close"    : bool(custom_button.get("close", False))} 

      else:
        custom_button = None
            
      #Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal
      if not channelpath:
        channelpath = inspect.currentframe().f_back.f_back.f_code.co_filename
      channelname = os.path.basename(channelpath).replace(".py", "")

      #Si no tenemos list_controls, hay que sacarlos del xml del canal
      if not list_controls:      
      
        #Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools
        if os.path.join(config.get_runtime_path(), "channels") in channelpath:
        
          # La llamada se hace desde un canal
          list_controls, default_values = channeltools.get_channel_controls_settings(channelname)

        #En caso contrario salimos
        else:
          return None


      #Si no se pasan dict_values, creamos un dict en blanco
      if  dict_values == None:
        dict_values = {}
      
      #Ponemos el titulo
      if caption =="": 
        caption = str(config.get_localized_string(30100)) + " -- " + channelname.capitalize()
      elif caption.startswith('@') and unicode(caption[1:]).isnumeric():
          caption = config.get_localized_string(int(caption[1:]))
      
      
    
      JsonData = {}
      JsonData["action"]="OpenConfig"   
      JsonData["data"]={}
      JsonData["data"]["title"] = self.kodi_labels_to_html(caption)
      JsonData["data"]["custom_button"]=custom_button
      JsonData["data"]["items"]=[]
      

      # Añadir controles
      for c in list_controls:
          if not "default" in c: c["default"] = ""
          if not "color" in c: c["color"] = "auto"
          if not "label" in c: continue
          
          #Obtenemos el valor
          if not c["id"] in dict_values:
            if not callback:
              c["value"]= config.get_setting(c["id"],channelname)
            else:
              c["value"] = c["default"]

            
          # Translation
          if c['label'].startswith('@') and unicode(c['label'][1:]).isnumeric():
              c['label'] = str(config.get_localized_string(c['label'][1:]))
          if c["label"].endswith (":"): c["label"] = c["label"][:-1]
          
          if c['type'] == 'list':
              lvalues=[]
              for li in c['lvalues']:
                  if li.startswith('@') and unicode(li[1:]).isnumeric():
                      lvalues.append(str(config.get_localized_string(li[1:])))
                  else:
                      lvalues.append(li)
              c['lvalues'] = lvalues
              
          c["label"] = self.kodi_labels_to_html(c["label"])
          
          JsonData["data"]["items"].append(c)
        
      ID = self.send_message(JsonData)
      close = False
      
      while True:
        data = self.get_data(ID)
        if type(data) == dict:
          JsonData["action"]="HideLoading"
          JsonData["data"] = {}
          self.send_message(JsonData)
        
          for v in data:
              if data[v] == "true": data[v] = True
              if data[v] == "false": data[v] = False
              if unicode(data[v]).isnumeric():  data[v] =  int(data[v])
              
          if callback and '.' in callback:
              package, callback = callback.rsplit('.', 1)
          else:
              package = 'channels.%s' % channelname  
                
          cb_channel = None
          try:
              cb_channel = __import__(package, None, None, [package])
          except ImportError:
              logger.error('Imposible importar %s' % package)

          if callback:
              # Si existe una funcion callback la invocamos ...
              return getattr(cb_channel, self.callback)(item, data)
          else:
              # si no, probamos si en el canal existe una funcion 'cb_validate_config' ...
              try:
                  return getattr(cb_channel, 'cb_validate_config')(item, data)
              except AttributeError:
                  # ... si tampoco existe 'cb_validate_config'...
                  for v in data:
                      config.set_setting(v,data[v],channelname)
          
        elif data == "custom_button":
          try:
              cb_channel = __import__('channels.%s' % channelname, None, None, ["channels.%s" % channelname])
          except ImportError:
              logger.error('Imposible importar %s' % channelname)
              
          else:
            return_value = getattr(cb_channel, custom_button['function'])(item)
            if custom_button["close"] == True:
              return return_value
        
        elif data == False:
          return None
Example #38
0
    def set_context_commands(self, 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 = []


        # 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:
            # Predefinidos
            if type(command) == str:
                if command == "buscar_trailer":
                    context_commands.append(("Buscar Trailer", item.clone(channel="trailertools", action="buscartrailer", contextual=True).tourl()))

            # 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"], item.clone(**command).tourl()))

        # Opciones segun criterios

        # 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", Item(channel=item.channel, action="mainlist").tourl()))

        # Añadir a Favoritos
        if item.channel not in ["favoritos", "biblioteca", "ayuda","configuracion", ""] and not parent_item.channel == "favoritos":
            context_commands.append((config.get_localized_string(30155), item.clone(channel="favoritos", action="addFavourite", from_channel=item.channel, from_action=item.action).tourl()))

        # Añadimos opción contextual para Añadir la serie completa a la biblioteca
        if item.channel != "biblioteca" and item.action in ["episodios", "get_episodios"] \
                and (item.contentSerieName or item.show):
            context_commands.append(("Añadir Serie a Biblioteca", item.clone(action="add_serie_to_library",from_action=item.action).tourl()))

        # Añadir Pelicula a Biblioteca
        if item.channel != "biblioteca" and item.action in ["detail", "findvideos"] \
                and item.contentType == 'movie':
            context_commands.append(("Añadir Pelicula a Biblioteca", item.clone(action="add_pelicula_to_library", from_action=item.action).tourl()))

        # Descargar pelicula
        if item.contentType == "movie" and not item.channel == "descargas":
            context_commands.append(("Descargar Pelicula", item.clone(channel="descargas", action="save_download",from_channel=item.channel, from_action=item.action).tourl()))

        # Descargar serie
        if item.contentType == "tvshow" and not item.channel == "descargas":
            context_commands.append(("Descargar Serie", item.clone(channel="descargas", action="save_download",from_channel=item.channel, from_action=item.action).tourl()))

        # Descargar episodio
        if item.contentType == "episode" and not item.channel == "descargas":
            context_commands.append(("Descargar Episodio", item.clone(channel="descargas", action="save_download",from_channel=item.channel, from_action=item.action).tourl()))

        # Descargar temporada
        if item.contentType == "season" and not item.channel == "descargas":
            context_commands.append(("Descargar Temporada", item.clone(channel="descargas", action="save_download", from_channel=item.channel, from_action=item.action).tourl()))
            
        # Abrir configuración
        if parent_item.channel not in ["configuracion", "novedades", "buscador"]:
            context_commands.append(("Abrir Configuración", Item(channel="configuracion", action="mainlist").tourl()))


        return sorted(context_commands, key=lambda comand: comand[0])
def getmainlist(preferred_thumb=""):
    logger.info("channelselector.getmainlist")
    itemlist = list()

    # Añade los canales que forman el menú principal

    itemlist.append(
        Item(title=config.get_localized_string(30130),
             channel="novedades",
             action="mainlist",
             thumbnail=get_thumb(preferred_thumb, "thumb_novedades.png"),
             category=config.get_localized_string(30119),
             viewmode="thumbnails"))

    itemlist.append(
        Item(title=config.get_localized_string(30118),
             channel="channelselector",
             action="getchanneltypes",
             thumbnail=get_thumb(preferred_thumb, "thumb_canales.png"),
             category=config.get_localized_string(30119),
             viewmode="thumbnails"))

    itemlist.append(
        Item(title=config.get_localized_string(30103),
             channel="buscador",
             action="mainlist",
             thumbnail=get_thumb(preferred_thumb, "thumb_buscar.png"),
             category=config.get_localized_string(30119),
             viewmode="list"))

    itemlist.append(
        Item(title=config.get_localized_string(30102),
             channel="favoritos",
             action="mainlist",
             thumbnail=get_thumb(preferred_thumb, "thumb_favoritos.png"),
             category=config.get_localized_string(30102),
             viewmode="thumbnails"))

    if config.get_library_support():

        itemlist.append(
            Item(title=config.get_localized_string(30131),
                 channel="biblioteca",
                 action="mainlist",
                 thumbnail=get_thumb(preferred_thumb, "thumb_biblioteca.png"),
                 category=config.get_localized_string(30119),
                 viewmode="thumbnails"))

    itemlist.append(
        Item(title=config.get_localized_string(30101),
             channel="descargas",
             action="mainlist",
             thumbnail=get_thumb(preferred_thumb, "thumb_descargas.png"),
             viewmode="list"))

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

    if "xbmceden" in config.get_platform():

        itemlist.append(
            Item(title=config.get_localized_string(30100),
                 channel="configuracion",
                 action="mainlist",
                 thumbnail=get_thumb(preferred_thumb, thumb_configuracion),
                 folder=False,
                 viewmode="list"))
    else:
        itemlist.append(
            Item(title=config.get_localized_string(30100),
                 channel="configuracion",
                 action="mainlist",
                 thumbnail=get_thumb(preferred_thumb, thumb_configuracion),
                 category=config.get_localized_string(30100),
                 viewmode="list"))

    itemlist.append(
        Item(title=config.get_localized_string(30104),
             channel="ayuda",
             action="mainlist",
             thumbnail=get_thumb(preferred_thumb, "thumb_ayuda.png"),
             category=config.get_localized_string(30104),
             viewmode="list"))
    return itemlist
def getchanneltypes(preferred_thumb=""):
    logger.info("channelselector getchanneltypes")

    # Lista de categorias
    valid_types = [
        "movie", "serie", "anime", "documentary", "vos", "torrent", "latino",
        "adult"
    ]
    dict_cat_lang = {
        'movie': config.get_localized_string(30122),
        'serie': config.get_localized_string(30123),
        'anime': config.get_localized_string(30124),
        'documentary': config.get_localized_string(30125),
        'vos': config.get_localized_string(30136),
        'adult': config.get_localized_string(30126),
        'latino': config.get_localized_string(30127)
    }

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

    channel_files = glob.glob(channel_path)

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

    # Construye la lista de tipos
    channel_types = []

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

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

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

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

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

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

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

    return itemlist
Example #41
0
    def onInit(self):
        self.getControl(10004).setEnabled(False)
        self.getControl(10005).setEnabled(False)
        self.getControl(10006).setEnabled(False)
        self.ok_enabled = False
        self.default_enabled = False

        if xbmcgui.__version__ == "1.2":
            self.setCoordinateResolution(1)
        else:
            self.setCoordinateResolution(5)

        # Ponemos el título
        self.getControl(10002).setLabel(self.title)

        if self.custom_button is not None:
            if self.custom_button['visible']:
                self.getControl(10006).setLabel(self.custom_button['label'])
            else:
                self.getControl(10006).setVisible(False)
                self.getControl(10004).setPosition(
                    self.getControl(10004).getPosition()[0] + 80,
                    self.getControl(10004).getPosition()[1])
                self.getControl(10005).setPosition(
                    self.getControl(10005).getPosition()[0] + 80,
                    self.getControl(10005).getPosition()[1])

        # Obtenemos las dimensiones del area de controles
        self.controls_width = self.getControl(10007).getWidth() - 20
        self.controls_height = self.getControl(10007).getHeight()
        self.controls_pos_x = self.getControl(10007).getPosition(
        )[0] + self.getControl(10001).getPosition()[0] + 10
        self.controls_pos_y = self.getControl(
            10007).getPosition()[1] + self.getControl(10001).getPosition()[1]
        self.height_control = 35
        self.font = "font12"

        # En versiones antiguas: creamos 5 controles, de lo conrtario al hacer click al segundo control,
        # automaticamente cambia el label del tercero a "Short By: Name" no se porque...
        if xbmcgui.ControlEdit == ControlEdit:
            for x in range(5):
                control = xbmcgui.ControlRadioButton(-500, 0, 0, 0, "")
                self.addControl(control)

        for c in self.list_controls:
            # Saltamos controles que no tengan los valores adecuados
            if "type" not in c:
                continue
            if "label" not in c:
                continue
            if c["type"] != "label" and "id" not in c:
                continue
            if c["type"] == "list" and "lvalues" not in c:
                continue
            if c["type"] == "list" and not type(c["lvalues"]) == list:
                continue
            if c["type"] == "list" and not len(c["lvalues"]) > 0:
                continue
            if c["type"] != "label" and len([
                    control.get("id") for control in self.list_controls
                    if c["id"] == control.get("id")
            ]) > 1:
                continue

            # Translation label y lvalues
            if c['label'].startswith('@') and unicode(
                    c['label'][1:]).isnumeric():
                c['label'] = config.get_localized_string(int(c['label'][1:]))
            if c['type'] == 'list':
                lvalues = []
                for li in c['lvalues']:
                    if li.startswith('@') and unicode(li[1:]).isnumeric():
                        lvalues.append(config.get_localized_string(int(
                            li[1:])))
                    else:
                        lvalues.append(li)
                c['lvalues'] = lvalues

            # Valores por defecto en caso de que el control no disponga de ellos
            if c["type"] == "bool" and "default" not in c:
                c["default"] = False
            if c["type"] == "text" and "default" not in c:
                c["default"] = ""
            if c["type"] == "text" and "hidden" not in c:
                c["hidden"] = False
            if c["type"] == "list" and "default" not in c:
                c["default"] = 0
            if c["type"] == "label" and "id" not in c:
                c["id"] = None
            if "color" not in c:
                c["color"] = "0xFF0066CC"
            if "visible" not in c:
                c["visible"] = True
            if "enabled" not in c:
                c["enabled"] = True

            if c["type"] == "text" and not type(c["hidden"]) == bool:
                if c["hidden"].lower() == 'true':
                    c["hidden"] = True
                else:
                    c["hidden"] = False

            # Decidimos si usar el valor por defecto o el valor guardado
            if c["type"] in ["bool", "text", "list"]:
                if id not in self.values:
                    if not self.callback:
                        self.values[c["id"]] = config.get_setting(
                            c["id"], self.channel)
                    else:
                        self.values[c["id"]] = c["default"]

            if c["type"] == "bool":
                c["default"] = bool(c["default"])
                self.values[c["id"]] = bool(self.values[c["id"]])

            if c["type"] == "bool":
                self.add_control_bool(c)

            elif c["type"] == 'text':
                self.add_control_text(c)

            elif c["type"] == 'list':
                self.add_control_list(c)

            elif c["type"] == 'label':
                self.add_control_label(c)

        self.list_controls = [c for c in self.list_controls if "control" in c]

        self.evaluate_conditions()
        self.index = -1
        self.dispose_controls(0)
        self.getControl(100010).setVisible(False)
        self.getControl(10004).setEnabled(True)
        self.getControl(10005).setEnabled(True)
        self.getControl(10006).setEnabled(True)
        self.ok_enabled = True
        self.default_enabled = True
        self.check_default()
        self.check_ok(self.values)
Example #42
0
def play_from_library(item):
    """
        Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener
        más items, como mucho se puede colocar un dialogo de seleccion.
        Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante
        "Container.Update()" cargamos el strm como si un item desde dentro de pelisalacarta se tratara, quitando todas
        las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para
        la biblioteca.
        @type item: item
        @param item: elemento con información
    """
    logger.info()
    # logger.debug("item: \n" + item.tostring('\n'))

    import xbmcgui
    import xbmcplugin
    import xbmc
    # Intentamos reproducir una imagen (esto no hace nada y ademas no da error)
    xbmcplugin.setResolvedUrl(
        int(sys.argv[1]), True,
        xbmcgui.ListItem(
            path=os.path.join(config.get_runtime_path(), "icon.png")))

    # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion
    xbmc.Player().stop()

    # modificamos el action (actualmente la biblioteca necesita "findvideos" ya que es donde se buscan las fuentes
    item.action = "findvideos"

    window_type = config.get_setting("window_type", "biblioteca")

    # y volvemos a lanzar kodi
    if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1:
        # Ventana convencional
        xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" +
                            item.tourl() + ")")

    else:
        # Ventana emergente
        from channels import biblioteca
        p_dialog = platformtools.dialog_progress_bg('streamondemand',
                                                    'Caricamento in corso...')
        p_dialog.update(0, '')

        itemlist = biblioteca.findvideos(item)

        p_dialog.update(50, '')

        # Se filtran los enlaces segun la lista blanca y negra
        if config.get_setting('filter_servers') == 'true':
            itemlist = filtered_servers(itemlist)

        # Se limita la cantidad de enlaces a mostrar
        if config.get_setting("max_links", "biblioteca") != 0:
            itemlist = limit_itemlist(itemlist)

        # Se "limpia" ligeramente la lista de enlaces
        if config.get_setting("replace_VD", "biblioteca") == 1:
            itemlist = reorder_itemlist(itemlist)

        p_dialog.update(100, '')
        xbmc.sleep(500)
        p_dialog.close()

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

            # Se abre la ventana de seleccion
            if (item.contentSerieName != "" and item.contentSeason != ""
                    and item.contentEpisodeNumber != ""):
                cabecera = ("%s - %sx%s -- %s" %
                            (item.contentSerieName, item.contentSeason,
                             item.contentEpisodeNumber,
                             config.get_localized_string(30163)))
            else:
                cabecera = config.get_localized_string(30163)

            seleccion = platformtools.dialog_select(cabecera, opciones)
            if seleccion == -1:
                return

            else:
                item = biblioteca.play(itemlist[seleccion])[0]
                platformtools.play_video(item)
def alert_unsopported_server():
    # 'Servidor no soportado o desconocido' , 'Prueba en otro servidor o en otro canal'
    dialog_ok(config.get_localized_string(30065),
              config.get_localized_string(30058))
Example #44
0
def run():
    logger.info()

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

    # If no item, this is mainlist
    else:
        item = Item(channel="channelselector",
                    action="getmainlist",
                    viewmode="movie")

    logger.info(item.tostring())

    try:

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

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

            # Check for updates only on first screen
            if config.get_setting("check_for_plugin_updates") == "true":
                logger.info("Check for plugin updates enabled")
                from core import updater

                try:
                    config.set_setting("plugin_updates_available", "0")
                    version = updater.checkforupdates()
                    itemlist = channelselector.getmainlist()

                    if version:
                        config.set_setting("plugin_updates_available", "1")

                        platformtools.dialog_ok(
                            "Versione " + version + " disponible",
                            "E' possibile fare il download della nuova versione\n"
                            "selezionare la relativa voce nel menu principale")

                        itemlist = channelselector.getmainlist()
                        itemlist.insert(
                            0,
                            Item(title="Download versione " + version,
                                 version=version,
                                 channel="updater",
                                 action="update",
                                 thumbnail=channelselector.get_thumb(
                                     "squares", "thumb_actualizar.png")))
                except:
                    import traceback
                    logger.info(traceback.format_exc())
                    platformtools.dialog_ok(
                        "Impossibile connettersi",
                        "Non è stato possibile verificare", "aggiornamenti")
                    logger.info("Fallo al verificar la actualización")
                    config.set_setting("plugin_updates_available", "0")
                    itemlist = channelselector.getmainlist()

            else:
                logger.info("Check for plugin updates disabled")
                config.set_setting("plugin_updates_available", "0")
                itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

        # Action for updating plugin
        elif item.action == "update":

            from core import updater
            updater.update(item)
            config.set_setting("plugin_updates_available", "0")
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        # 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

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

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

                # Parental control
                can_open_channel = False

                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(item.channel) and config.get_setting(
                        "adult_pin") != "":

                    tecleado = platformtools.dialog_input(
                        "", "PIN per canali per adulti", True)
                    if tecleado is not None:
                        if tecleado == config.get_setting("adult_pin"):
                            can_open_channel = True

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

                if not can_open_channel:
                    return

            # 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 item.channel in [
                    "personal", "personal2", "personal3", "personal4",
                    "personal5"
            ]:
                import channels.personal as channel

            elif os.path.exists(channel_file):
                try:
                    channel = __import__('channels.%s' % item.channel, 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":
                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("plugin",
                                                "Niente da riprodurre")

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

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

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

                if config.get_setting("max_links", "biblioteca") != 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":
                library.add_pelicula_to_library(item)

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

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from channels import descargas
                item.action = item.extra
                del item.extra
                descargas.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())

                tecleado = platformtools.dialog_input('')
                if tecleado is not None:

                    # TODO revisar 'personal.py' porque no tiene función search y daría problemas
                    # DrZ3r0
                    itemlist = channel.search(item, tecleado.replace(" ", "+"))
                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)
                platformtools.render_items(itemlist, item)

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

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.info("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("plugin", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.info("Codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok(
                "plugin",
                config.get_localized_string(30051) % e.code)
def alert_no_disponible_server(server):
    # 'El vídeo ya no está en %s' , 'Prueba en otro servidor o en otro canal'
    dialog_ok(config.get_localized_string(30055),
              (config.get_localized_string(30057) % server),
              config.get_localized_string(30058))
Example #46
0
def get_next_items( item ):

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

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

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

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

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

        elif item.channel=="channelselector":

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

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

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

        else:

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

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

            # --- Update channels files --------------------------------------
            if item.action=="mainlist":
                from core import config
                if config.get_setting("updatechannels")=="true":
                    try:
                        from core import updater
                        actualizado = updater.updatechannel(item.channel)

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

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

            from platformcode import xbmctools

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

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

                        # FIXME: Este error ha que tratarlo de otra manera, al dar a volver sin ver el vídeo falla
                        try:
                            xbmctools.play_video(channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show)
                        except:
                            pass

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

                    # FIXME: Este error ha que tratarlo de otra manera, por al dar a volver sin ver el vídeo falla
                    # Mejor hacer el play desde la ventana
                    try:
                        xbmctools.play_video(channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle, Serie=item.show)
                    except:
                        pass


                return []

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

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

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

                if len(itemlist)==0:
                    itemlist = [ Item(title="Nessun video trovato", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ]
            # ---------------add_serie_to_library-----------
            elif item.action=="add_serie_to_library":
                plugintools.log("navigation.get_next_items add_serie_to_library")
                from platformcode import library
                import xbmcgui
                
                # Obtiene el listado desde el que se llamó
                action = item.extra
                    
                # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                if "###" in item.extra:
                    action = item.extra.split("###")[0]
                    item.extra = item.extra.split("###")[1]

                exec "itemlist = channel."+action+"(item)"

                # Progreso
                pDialog = xbmcgui.DialogProgress()
                ret = pDialog.create('streamondemand-pureita', 'Añadiendo episodios...')
                pDialog.update(0, 'Añadiendo episodio...')
                totalepisodes = len(itemlist)
                plugintools.log ("navigation.get_next_items Total Episodios:"+str(totalepisodes))
                i = 0
                errores = 0
                nuevos = 0
                for item in itemlist:
                    i = i + 1
                    pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
                    plugintools.log("streamondemand-pureita.navigation.py add_serie_to_library, title="+item.title)
                    if (pDialog.iscanceled()):
                        return
                
                    try:
                        #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                        # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                        if item.action!="add_serie_to_library" and item.action!="download_all_episodes":
                            nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle, extra=item.extra )
                    except IOError:
                        import sys
                        for line in sys.exc_info():
                            logger.error( "%s" % line )
                        plugintools.log("streamondemand-pureita.navigation.py Error al grabar el archivo "+item.title)
                        errores = errores + 1
                        
                pDialog.close()
                    
                # Actualizacion de la biblioteca
                itemlist=[]
                if errores > 0:
                    itemlist.append(Item(title="ERRORE, la serie NON si è aggiunta alla biblioteca o la fatto in modo incompleto"))
                    plugintools.log ("navigation.get_next_items No se pudo añadir "+str(errores)+" episodios")
                else:
                    itemlist.append(Item(title="La serie è stata aggiunta alla biblioteca"))
                    plugintools.log ("navigation.get_next_items Ningún error al añadir "+str(errores)+" episodios")
                    
                # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                #library.update(totalepisodes,errores,nuevos)
                #xbmctools.renderItems(itemlist, params, url, category)
                    
                #Lista con series para actualizar
                from core import config
                nombre_fichero_config_canal = os.path.join( config.get_library_path() , "series.xml" )
                if not os.path.exists(nombre_fichero_config_canal):
                    nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )

                plugintools.log("nombre_fichero_config_canal="+nombre_fichero_config_canal)
                if not os.path.exists(nombre_fichero_config_canal):
                    f = open( nombre_fichero_config_canal , "w" )
                else:
                    f = open( nombre_fichero_config_canal , "r" )
                    contenido = f.read()
                    f.close()
                    f = open( nombre_fichero_config_canal , "w" )
                    f.write(contenido)
                from platformcode import library
                f.write( library.title_to_folder_name(item.show)+","+item.url+","+item.channel+"\n")
                f.close();
                return itemlist
            # --------------------------------------------------------------------
            elif item.action=="download_all_episodes":
                plugintools.log("navigation.get_next_items download_all_episodes")
                download_all_episodes(item,channel)
			#---------------------------------------------------------------------
            else:

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

                for loaded_item in itemlist:

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

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

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


    return itemlist
Example #47
0
def play_menu(item):

    if type(item) == list and len(item) == 1:
        item = item[0]

    #Modo Normal
    if type(item) == Item:
        if item.server == "": item.server = "directo"
        video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
            item.server, item.url, item.password, True)

    #Modo "Play" en canal, puede devolver varias url
    elif type(item) == list and len(item) > 1:

        itemlist = item  #En este caso en el argumento item, en realidad hay un itemlist
        item = itemlist[0]  #Se asigna al item, el item primero del itemlist

        video_urls = []
        for videoitem in itemlist:
            if videoitem.server == "": videoitem.server = "directo"
            opcion_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(
                videoitem.server, videoitem.url)
            opcion_urls[0][
                0] = opcion_urls[0][0] + " [" + videoitem.fulltitle + "]"
            video_urls.extend(opcion_urls)
        item = itemlist[0]
        puedes = True
        motivo = ""

    if not "strmfile" in item: item.strmfile = False
    #TODO: unificar show y Serie ya que se usan indistintamente.
    if not "Serie" in item: item.Serie = item.show
    if item.server == "": item.server = "directo"

    opciones = check_video_options(item, video_urls)
    if not puedes:
        if item.server != "directo":
            motivo = motivo.replace("<br/>", "\n")
            platformtools.dialog_ok("No puedes ver ese vídeo porque...",
                                    motivo + "\n" + item.url)
        else:
            platformtools.dialog_ok(
                "No puedes ver ese vídeo porque...",
                "El servidor donde está alojado no está\nsoportado en pelisalacarta todavía\n"
                + item.url)

    if len(opciones) == 0:
        return

    default_action = config.get_setting("default_action")
    logger.info("default_action=" + default_action)
    # Si la accion por defecto es "Preguntar", pregunta
    if default_action == "0":
        seleccion = platformtools.dialog_select(
            config.get_localized_string(30163),
            [opcion.option for opcion in opciones])
    elif default_action == "1":
        seleccion = 0
    elif default_action == "2":
        seleccion = len(video_urls) - 1
    elif default_action == "3":
        seleccion = seleccion
    else:
        seleccion = 0

    if seleccion > -1:
        logger.info("seleccion=%d" % seleccion)
        logger.info("seleccion=%s" % opciones[seleccion].option)
        selecteditem = opciones[seleccion]
        del selecteditem.option
        run(opciones[seleccion])

    return
Example #48
0
def addnewvideo(item, IsPlayable='false', totalItems=0):
    contextCommands = []
    ok = False
    try:
        item.context = urllib.unquote_plus(item.context)
    except:
        item.context = ""
    if "|" in item.context:
        item.context = item.context.split("|")
    if DEBUG:
        logger.info('[xbmctools.py] addnewvideo')
        logger.info(item.tostring())

    icon_image = os.path.join(config.get_runtime_path(), "resources", "images",
                              "servers", item.server + ".png")
    if not os.path.exists(icon_image):
        icon_image = "DefaultVideo.png"

    listitem = xbmcgui.ListItem(item.title,
                                iconImage="DefaultVideo.png",
                                thumbnailImage=item.thumbnail)
    listitem.setInfo(
        "video", {
            "Title": item.title,
            "FileName": item.title,
            "Plot": item.plot,
            "Duration": item.duration,
            "Studio": item.channel.capitalize(),
            "Genre": item.category
        })

    set_infoLabels(
        listitem, item.plot
    )  # Modificacion introducida por super_berny para añadir infoLabels al ListItem

    if item.fanart != "":
        #logger.info("fanart :%s" %fanart)
        listitem.setProperty('fanart_image', item.fanart)
        xbmcplugin.setPluginFanart(pluginhandle, item.fanart)

    if IsPlayable == 'true':  #Esta opcion es para poder utilizar el xbmcplugin.setResolvedUrl()
        listitem.setProperty('IsPlayable', 'true')
    #listitem.setProperty('fanart_image',os.path.join(IMAGES_PATH, "cinetube.png"))
    if "1" in item.context:  #El uno añade al menu contextual la opcion de guardar en megalive un canal a favoritos
        addItemCommand = "XBMC.RunPlugin(%s?%s)" % (
            sys.argv[0], item.clone(action="saveChannelFavorites").tourl())
        contextCommands.append(
            (config.get_localized_string(30301), addItemCommand))

    if "2" in item.context:  #El dos añade al menu contextual la opciones de eliminar y/o renombrar un canal en favoritos
        addItemCommand = "XBMC.RunPlugin(%s?%s)" % (
            sys.argv[0], item.clone(action="deleteSavedChannel").tourl())
        contextCommands.append(
            (config.get_localized_string(30302), addItemCommand))
        addItemCommand = "XBMC.RunPlugin(%s?%s)" % (
            sys.argv[0], item.clone(action="renameChannelTitle").tourl())
        contextCommands.append(
            (config.get_localized_string(30303), addItemCommand))

    if "6" in item.context:  # Ver canal en vivo en justintv
        justinCommand = "XBMC.PlayMedia(%s?%s)" % (
            sys.argv[0], item.clone(channel="justintv",
                                    action="playVideo").tourl())
        contextCommands.append(
            (config.get_localized_string(30410), justinCommand))

    if "7" in item.context:  # Listar videos archivados en justintv
        justinCommand = "XBMC.Container.Update(%s?%s)" % (
            sys.argv[0], item.clone(channel="justintv",
                                    action="listarchives").tourl())
        contextCommands.append(
            (config.get_localized_string(30409), justinCommand))

    if "8" in item.context:  # Añadir canal a favoritos justintv
        justinCommand = "XBMC.RunPlugin(%s?%s)" % (
            sys.argv[0], item.clone(channel="justintv",
                                    action="addToFavorites").tourl())
        contextCommands.append(
            (config.get_localized_string(30406), justinCommand))

    if "9" in item.context:  # Remover canal de favoritos justintv
        justinCommand = "XBMC.Container.Update(%s?%s)" % (
            sys.argv[0],
            item.clone(channel="justintv",
                       action="removeFromFavorites").tourl())
        contextCommands.append(
            (config.get_localized_string(30407), justinCommand))

    if len(contextCommands) > 0:
        listitem.addContextMenuItems(contextCommands, replaceItems=False)
    try:
        item.title = item.title.encode(
            "utf-8"
        )  #This only aplies to unicode strings. The rest stay as they are.
        item.plot = item.plot.encode("utf-8")
    except:
        pass

    itemurl = '%s?%s' % (sys.argv[0], item.tourl())

    #logger.info("[xbmctools.py] itemurl=%s" % itemurl)
    if totalItems == 0:
        ok = xbmcplugin.addDirectoryItem(handle=pluginhandle,
                                         url=itemurl,
                                         listitem=listitem,
                                         isFolder=False)
    else:
        ok = xbmcplugin.addDirectoryItem(handle=pluginhandle,
                                         url=itemurl,
                                         listitem=listitem,
                                         isFolder=False,
                                         totalItems=totalItems)
    return ok
Example #49
0
def check_video_options(item, video_urls):
    itemlist = []
    #Opciones Reproducir
    playable = (len(video_urls) > 0)

    for video_url in video_urls:
        itemlist.append(
            item.clone(option=config.get_localized_string(30151) + " " +
                       video_url[0],
                       video_url=video_url[1],
                       action="play_video"))

    if item.server == "local":
        itemlist.append(
            item.clone(option=config.get_localized_string(30164),
                       action="delete_file"))
    if not item.server == "local" and playable:
        itemlist.append(
            item.clone(option=config.get_localized_string(30153),
                       action="download",
                       video_urls=video_urls))

    if item.channel == "favoritos":
        itemlist.append(
            item.clone(option=config.get_localized_string(30154),
                       action="remove_from_favorites"))
    if not item.channel == "favoritos" and playable:
        itemlist.append(
            item.clone(option=config.get_localized_string(30155),
                       action="add_to_favorites",
                       item_action=item.action))

    if not item.strmfile and playable:
        itemlist.append(
            item.clone(option=config.get_localized_string(30161),
                       action="add_to_library",
                       item_action=item.action))

    if item.channel != "descargas" and playable:
        itemlist.append(
            item.clone(option=config.get_localized_string(30157),
                       action="add_to_downloads",
                       item_action=item.action))
    if not item.channel != "descargas" and item.category == "errores":
        itemlist.append(
            item.clone(option=config.get_localized_string(30159),
                       action="remove_from_downloads_error"))
    if not item.channel != "descargas" and item.category == "errores" and playable:
        itemlist.append(
            item.clone(option=config.get_localized_string(30160),
                       action="move_to_downloads"))
    if not item.channel != "descargas" and not item.category == "errores":
        itemlist.append(
            item.clone(option=config.get_localized_string(30156),
                       action="remove_from_downloads"))

    if config.get_setting("jdownloader_enabled") == "true" and playable:
        itemlist.append(
            item.clone(option=config.get_localized_string(30158),
                       action="send_to_jdownloader"))
    if config.get_setting("pyload_enabled") == "true" and playable:
        itemlist.append(
            item.clone(option=config.get_localized_string(30158).replace(
                "jdownloader", "pyLoad"),
                       action="send_to_pyload"))

    if not item.channel in ["Trailer", "ecarteleratrailers"] and playable:
        itemlist.append(
            item.clone(option=config.get_localized_string(30162),
                       action="search_trailer"))

    return itemlist
Example #50
0
def alertnodisponible():
    advertencia = xbmcgui.Dialog()
    #'Vídeo no disponible'
    #'No se han podido localizar videos en la página del canal'
    resultado = advertencia.ok(config.get_localized_string(30055) , config.get_localized_string(30056))
Example #51
0
def show_channel_settings(list_controls=None,
                          dict_values=None,
                          caption="",
                          callback=None,
                          item=None,
                          custom_button=None,
                          channelpath=None,
                          kwargs=None,
                          ch_type=None):
    ''' Funcion que permite utilizar cuadros de configuracion personalizados.
    
    show_channel_settings(listado_controles, dict_values, caption, callback, item)
            Parametros:
                listado_controles: (list) Lista de controles a incluir en la ventana, segun el siguiente esquema:
                    (opcional)list_controls= [
                                {'id': "nameControl1",
                                  'type': "bool",                       # bool, text, list, label 
                                  'label': "Control 1: tipo RadioButton",
                                  'color': '0xFFee66CC',                # color del texto en formato ARGB hexadecimal
                                  'default': True,
                                  'enabled': True,
                                  'visible': True
                                },
                                {'id': "nameControl2",
                                  'type': "text",                       # bool, text, list, label 
                                  'label': "Control 2: tipo Cuadro de texto",
                                  'color': '0xFFee66CC',
                                  'default': "Valor por defecto",
                                  'hidden': False,                      # only for type = text Indica si hay que ocultar el texto (para passwords)
                                  'enabled': True,
                                  'visible': True
                                },
                                {'id': "nameControl3",
                                  'type': "list",                       # bool, text, list, label 
                                  'label': "Control 3: tipo Lista",
                                  'color': '0xFFee66CC',
                                  'default': 0,                         # Indice del valor por defecto en lvalues 
                                  'enabled': True,
                                  'visible': True,
                                  'lvalues':["item1", "item2", "item3", "item4"],  # only for type = list
                                },
                                {'id': "nameControl4",
                                  'type': "label",                       # bool, text, list, label 
                                  'label': "Control 4: tipo Etiqueta",
                                  'color': '0xFFee66CC',               
                                  'enabled': True,
                                  'visible': True
                                }]
                    Si no se incluye el listado_controles, se intenta obtener del xml del canal desde donde se hace la llamada. 
                    El formato de los controles en el xml es:
                        <?xml version="1.0" encoding="UTF-8" ?>
                        <channel>
                            ...
                            ...
                            <settings>
                                <id>nameControl1</id>
                                <type>bool</type>
                                <label>Control 1: tipo RadioButton</label>
                                <default>false</default>
                                <enabled>true</enabled>
                                <visible>true</visible>
                                <color>0xFFee66CC</color>
                            </settings>
                            <settings>
                                <id>nameControl2</id>
                                <type>text</type>
                                <label>Control 2: tipo Cuadro de texto</label>
                                <default>Valor por defecto</default>
                                <hidden>true</hidden>
                                <enabled>true</enabled>
                                <visible>true</visible>
                                <color>0xFFee66CC</color>
                            </settings>
                            <settings>
                                <id>nameControl3</id>
                                <type>list</type>
                                <label>Control 3: tipo Lista</label>
                                <default>0</default>
                                <enabled>true</enabled>
                                <color>0xFFee66CC</color>
                                <visible>true</visible>
                                <lvalues>item1</lvalues>
                                <lvalues>item2</lvalues>
                                <lvalues>item3</lvalues>
                                <lvalues>item4</lvalues>
                            </settings>
                            <settings>
                                <id>nameControl4</id>
                                <type>label</type>
                                <label>Control 4: tipo Etiqueta</label>
                                <enabled>true</enabled>
                                <visible>true</visible>
                                <color>0xFFee66CC</color>
                            </settings>
                            ...
                        </channel>  
                    
                    
                    Los campos 'label', 'default' y 'lvalues' pueden ser un numero precedido de '@'. En cuyo caso se buscara el literal en el archivo string.xml del idioma seleccionado.
                    Los campos 'enabled' y 'visible' admiten los comparadores eq(), gt() e it() y su funcionamiento se describe en: http://kodi.wiki/view/Add-on_settings#Different_types
                    Por el momento en PLEX, tanto si quedan disabled, como no visible, los ocultamos (quitandolos del itemlist)
                    Los campos hidden y color no tienen utilidad en PLEX
                    
                (opcional)dict_values: (dict) Diccionario que representa el par (id: valor) de los controles de la lista.
                    Si algun control de la lista no esta incluido en este diccionario se le asignara el valor por defecto.
                        dict_values={"nameControl1": False,
                                     "nameControl2": "Esto es un ejemplo"}
                
                (opcional) caption: (str) Titulo de la ventana de configuracion. Se puede localizar mediante un numero precedido de '@'
                (opcional) callback (str) Nombre de la funcion, del canal desde el que se realiza la llamada, que sera invocada al pulsar 
                    el boton aceptar de la ventana. A esta funcion se le pasara como parametros el objeto 'item' y el dicionario 'dict_values'
            Retorno: Si se especifica 'callback' se devolvera lo que devuelva esta funcion. Si no devolvera None     
    
    Ejemplos de uso:
        platformtools.show_channel_settings(): Así tal cual, sin pasar ningún argumento, la ventana detecta de que canal se ha hecho la llamada, 
            y lee los ajustes del XML y carga los controles, cuando le das a Aceptar los vuelve a guardar.
        
        return platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, callback='cb', ítem=ítem):
            Así abre la ventana con los controles pasados y los valores de dict_values, si no se pasa dict_values, carga los valores por defecto de los controles, 
            cuando le das a aceptar, llama a la función 'cb' del canal desde donde se ha llamado, pasando como parámetros, el ítem y el dict_values    
    
    '''
    logger.info()
    global params
    itemlist = []

    #Cuando venimos de hacer click en un control de la ventana, channelname ya se pasa como argumento, si no lo tenemos, detectamos de donde venimos
    if not channelpath:
        channelpath = inspect.currentframe().f_back.f_back.f_code.co_filename
    channelname = os.path.basename(channelpath).replace(".py", "")
    ch_type = os.path.basename(os.path.dirname(channelpath))
    kwargs = {}

    #Si no tenemos list_controls, hay que sacarlos del xml del canal
    if not list_controls:

        #Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools
        if os.path.join(config.get_runtime_path(), "channels") in channelpath:

            # La llamada se hace desde un canal
            list_controls, default_values = channeltools.get_channel_controls_settings(
                channelname)
            kwargs = {"channel": channelname}

        #Si la ruta del canal esta en la carpeta "servers", obtenemos los controles y valores mediante servertools
        elif os.path.join(config.get_runtime_path(), "servers") in channelpath:
            # La llamada se hace desde un server
            list_controls, default_values = servertools.get_server_controls_settings(
                channelname)
            kwargs = {"server": channelname}

        #En caso contrario salimos
        else:
            return itemlist

    #Si no se pasan dict_values, creamos un dict en blanco
    if dict_values == None:
        dict_values = {}

    if type(custom_button) == dict:
        custom_button = {
            "label": custom_button.get("label", ""),
            "function": custom_button.get("function", ""),
            "visible": bool(custom_button.get("visible", True)),
            "close": bool(custom_button.get("close", False))
        }

    else:
        custom_button = None

    #Ponemos el titulo
    if caption == "":
        caption = str(config.get_localized_string(
            "30100")) + " -- " + channelname.capitalize()
    elif caption.startswith('@') and unicode(caption[1:]).isnumeric():
        caption = config.get_localized_string(int(caption[1:]))

    # Añadir controles
    for c in list_controls:

        #Obtenemos el valor
        if not c["id"] in dict_values:
            if not callback:
                dict_values[c["id"]] = config.get_setting(c["id"], **kwargs)
            else:
                if not 'default' in c: c["default"] = ''
                dict_values[c["id"]] = c["default"]

        # Translation
        if c['label'].startswith('@') and unicode(c['label'][1:]).isnumeric():
            c['label'] = str(config.get_localized_string(c['label'][1:]))
        if c["label"].endswith(":"): c["label"] = c["label"][:-1]

        if c['type'] == 'list':
            lvalues = []
            for li in c['lvalues']:
                if li.startswith('@') and unicode(li[1:]).isnumeric():
                    lvalues.append(str(config.get_localized_string(li[1:])))
                else:
                    lvalues.append(li)
            c['lvalues'] = lvalues

        #Tipos de controles
        if c['type'] == 'label':
            titulo = c["label"]
            itemlist.append(
                Item(channel=__channel__,
                     action="control_label_click",
                     title=titulo,
                     extra=list_controls.index(c)))

        if c['type'] == 'bool':
            titulo = c["label"] + ":" + (' ' * 5) + (
                "[X]" if dict_values[c["id"]] else "[  ]")
            itemlist.append(
                Item(channel=__channel__,
                     action="control_bool_click",
                     title=titulo,
                     extra=list_controls.index(c)))

        elif c['type'] == 'list':
            titulo = c["label"] + ":" + (' ' * 5) + str(
                c["lvalues"][dict_values[c["id"]]])
            itemlist.append(
                Item(channel=__channel__,
                     action="control_list_click",
                     title=titulo,
                     extra=list_controls.index(c)))

        elif c['type'] == 'text':
            titulo = c["label"] + ":" + (' ' * 5) + str(dict_values[c["id"]])
            item = Item(channel=__channel__,
                        action="control_text_click",
                        title=titulo,
                        extra=list_controls.index(c))
            item.type = "input"
            item.value = dict_values[c["id"]]
            itemlist.append(item)

    params = {
        "list_controls": list_controls,
        "dict_values": dict_values,
        "caption": caption,
        "channelpath": channelpath,
        "callback": callback,
        "item": item,
        "custom_button": custom_button,
        "kwargs": kwargs,
        "ch_type": ch_type
    }
    if itemlist:

        #Creamos un itemlist nuevo añadiendo solo los items que han pasado la evaluacion
        evaluated = []
        for x in range(len(list_controls)):
            #por el momento en PLEX, tanto si quedan disabled, como no visible, los ocultamos (quitandolos del itemlist)
            visible = evaluate(x, list_controls[x]["enabled"]) and evaluate(
                x, list_controls[x]["visible"])
            if visible:
                evaluated.append(itemlist[x])

        # Añadir Titulo
        evaluated.insert(
            0,
            Item(channel=__channel__,
                 action="control_label_click",
                 title=caption))
        # Añadir item aceptar y cancelar
        evaluated.append(
            Item(channel=__channel__,
                 action="ok_Button_click",
                 title="Aceptar"))
        evaluated.append(
            Item(channel=channelname, action="mainlist", title="Cancelar"))

        if custom_button is None:
            evaluated.append(
                Item(channel=__channel__,
                     action="default_Button_click",
                     title="Por defecto"))
        else:
            if custom_button['visible'] == True:
                evaluated.append(
                    Item(channel=__channel__,
                         action="default_Button_click",
                         title=custom_button["label"]))

    return evaluated
Example #52
0
def addnewfolderextra( canal , accion , category , title , url , thumbnail , plot , extradata ,Serie="",totalItems=0,fanart="",context="",show="",fulltitle="", extrameta=None, extracmds=None):
    if fulltitle=="":
        fulltitle=title
    
    contextCommands = []
    ok = False
    
    try:
        context = urllib.unquote_plus(context)
    except:
        context=""
    
    if "|" in context:
        context = context.split("|")
    
    if DEBUG:
        try:
            logger.info('[xbmctools.py] addnewfolderextra( "'+extradata+'","'+canal+'" , "'+accion+'" , "'+category+'" , "'+title+'" , "' + url + '" , "'+thumbnail+'" , "'+plot+'")" , "'+Serie+'")"')
        except:
            logger.info('[xbmctools.py] addnewfolder(<unicode>)')
    listitem = xbmcgui.ListItem( title, iconImage="DefaultFolder.png", thumbnailImage=thumbnail )

    listitem.setInfo( "video", { "Title" : title, "Plot" : plot, "Studio" : canal } )
    if extrameta: listitem.setInfo( "video", extrameta )

    if fanart!="":
        listitem.setProperty('fanart_image',fanart) 
        xbmcplugin.setPluginFanart(pluginhandle, fanart)
    #Realzamos un quote sencillo para evitar problemas con títulos unicode
#    title = title.replace("&","%26").replace("+","%2B").replace("%","%25")
    try:
        title = title.encode ("utf-8") #This only aplies to unicode strings. The rest stay as they are.
    except:
        pass
    itemurl = '%s?fanart=%s&channel=%s&action=%s&category=%s&title=%s&fulltitle=%s&url=%s&thumbnail=%s&plot=%s&extradata=%s&Serie=%s&show=%s' % ( sys.argv[ 0 ] , fanart, canal , accion , urllib.quote_plus( category ) , urllib.quote_plus(title) , urllib.quote_plus(fulltitle) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( plot ) , urllib.quote_plus( extradata ) , Serie, urllib.quote_plus( show ))

    if Serie != "": #Añadimos opción contextual para Añadir la serie completa a la biblioteca
        addSerieCommand = "XBMC.RunPlugin(%s?channel=%s&action=addlist2Library&category=%s&title=%s&fulltitle=%s&url=%s&extradata=%s&Serie=%s&show=%s)" % ( sys.argv[ 0 ] , canal , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus(fulltitle) , urllib.quote_plus( url ) , urllib.quote_plus( extradata ) , Serie, urllib.quote_plus( show ) )
        contextCommands.append(("Añadir Serie a Biblioteca",addSerieCommand))
        
    if "1" in context and accion != "por_teclado":
        DeleteCommand = "XBMC.RunPlugin(%s?channel=buscador&action=borrar_busqueda&title=%s&url=%s&show=%s)" % ( sys.argv[ 0 ]  ,  urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( show ) )
        contextCommands.append((config.get_localized_string( 30300 ),DeleteCommand))
    if "4" in context:
        searchSubtitleCommand = "XBMC.RunPlugin(%s?channel=subtitletools&action=searchSubtitle&title=%s&url=%s&category=%s&fulltitle=%s&url=%s&thumbnail=%s&plot=%s&extradata=%s&Serie=%s&show=%s)" % ( sys.argv[ 0 ]  ,  urllib.quote_plus( title ) , urllib.quote_plus( url ), urllib.quote_plus( category ), urllib.quote_plus(fulltitle) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( plot ) , urllib.quote_plus( extradata ) , Serie, urllib.quote_plus( show ) )
        contextCommands.append(("XBMC Subtitle",searchSubtitleCommand))
    if "5" in context:
        trailerCommand = "XBMC.Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s)" % ( sys.argv[ 0 ] , "trailertools" , "buscartrailer" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" )  )
        contextCommands.append((config.get_localized_string(30162),trailerCommand))
    if "6" in context:
        justinCommand = "XBMC.PlayMedia(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s)" % ( sys.argv[ 0 ] , "justintv" , "playVideo" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" )  )
        contextCommands.append((config.get_localized_string(30410),justinCommand))

    if "8" in context:# Añadir canal a favoritos justintv
        justinCommand = "XBMC.RunPlugin(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s)" % ( sys.argv[ 0 ] , "justintv" , "addToFavorites" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" )  )
        contextCommands.append((config.get_localized_string(30406),justinCommand))

    if "9" in context:# Remover canal de favoritos justintv
        justinCommand = "XBMC.Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s)" % ( sys.argv[ 0 ] , "justintv" , "removeFromFavorites" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" )  )
        contextCommands.append((config.get_localized_string(30407),justinCommand))

    if config.get_platform()=="boxee":
        #logger.info("Modo boxee")
        ok = xbmcplugin.addDirectoryItem( handle = pluginhandle, url = itemurl , listitem=listitem, isFolder=True)
    else:
        #logger.info("Modo xbmc")
        if len(contextCommands) > 0:
            listitem.addContextMenuItems ( contextCommands, replaceItems=False)
        if extracmds:
            listitem.addContextMenuItems ( extracmds, replaceItems=False)
    
        if totalItems == 0:
            ok = xbmcplugin.addDirectoryItem( handle = pluginhandle, url = itemurl , listitem=listitem, isFolder=True)
        else:
            ok = xbmcplugin.addDirectoryItem( handle = pluginhandle, url = itemurl , listitem=listitem, isFolder=True, totalItems=totalItems)
    return ok
Example #53
0
def listar_busquedas(params,url="",category=""):
    import xbmc
    import xbmcgui
    import xbmcplugin

    from platformcode.xbmc import xbmctools
    #print "category :" +category
    if url == "" and category == "":
        channel_preset = params.channel
        accion = params.action
        category = "Buscador_Generico"
    else:
        channel_preset = params.get("channel")
        accion = params.get("action")
        category = "Buscador_Normal"
    #print "listar_busquedas()"
    channel2 = ""
    itemlist=[]
    # Despliega las busquedas anteriormente guardadas
    try:
        presets = config.get_setting("presets_buscados")

        if channel_preset != CHANNELNAME:
            channel2 = channel_preset
        logger.info("channel_preset :%s" %channel_preset)

        matches = ""
        if "|" in presets:
            matches = presets.split("|")
            itemlist.append( Item(channel="buscador" , action="por_teclado"  , title=config.get_localized_string(30103)+"..."  , url=matches[0] ,thumbnail="" , plot=channel2, category = category , context = 1 ))
            #addfolder( "buscador"   , config.get_localized_string(30103)+"..." , matches[0] , "por_teclado", channel2 ) # Buscar
        else:
            itemlist.append( Item(channel="buscador" , action="por_teclado"  ,  title=config.get_localized_string(30103)+"..." ,   url="" ,thumbnail="" , plot=channel2 , category = category , context = 0 ))
            #addfolder( "buscador"   , config.get_localized_string(30103)+"..." , "" , "por_teclado", channel2 )
        if len(matches)>0:
            for match in matches:

                title=scrapedurl = match
                itemlist.append( Item(channel=channel_preset , action="searchresults"  , title=title ,  url=scrapedurl, thumbnail="" , plot="" , category = category ,  context=1 ))
                #addfolder( channel_preset , title , scrapedurl , "searchresults" )
        elif presets != "":

            title = scrapedurl = presets
            itemlist.append( Item(channel=channel_preset , action="searchresults"  , title=title ,  url=scrapedurl, thumbnail= "" , plot="" , category = category , context = 1 ))
            #addfolder( channel_preset , title , scrapedurl , "searchresults" )
    except:
        itemlist.append( Item(channel="buscador" , action="por_teclado"  , title=config.get_localized_string(30103)+"..." ,  url="", thumbnail="" , plot=channel2 , category = category ,  context = 0  ))
        #addfolder( "buscador"   , config.get_localized_string(30103)+"..." , "" , "por_teclado" , channel2 )

    if url=="" and category=="Buscador_Generico":

        return itemlist
    else:
        for item in itemlist:
            channel = item.channel
            action = item.action
            category = category
            scrapedtitle = item.title
            scrapedurl = item.url
            scrapedthumbnail = item.thumbnail
            scrapedplot = item.plot
            extra=item.extra
            context = item.context
            xbmctools.addnewfolderextra( channel , action , category , scrapedtitle , scrapedurl , scrapedthumbnail, scrapedplot , extradata = extra , context = context)

        # Cierra el directorio
        xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
        xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
        xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
Example #54
0
def getmainlist(preferred_thumb=""):
    logger.info()
    itemlist = list()

    # Menu principale

    itemlist.append(
        Item(title=config.get_localized_string(30119),
             channel="channelselector",
             action="getchanneltypes",
             thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                    "images", "main_menu_category.png"),
             fanart=os.path.join(config.get_runtime_path(), "resources",
                                 "images", "background.jpg"),
             viewmode="movie"))
    itemlist.append(
        Item(title=config.get_localized_string(30137),
             channel="buscadorall",
             action="mainlist",
             thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                    "images", "main_menu_search.png"),
             fanart=os.path.join(config.get_runtime_path(), "resources",
                                 "images", "background.jpg"),
             viewmode="movie"))
    itemlist.append(
        Item(title=config.get_localized_string(50002),
             channel="novedades",
             action="mainlist",
             thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                    "images", "thumb_novedades.png"),
             fanart=os.path.join(config.get_runtime_path(), "resources",
                                 "images", "background.jpg"),
             viewmode="movie"))
    itemlist.append(
        Item(title=config.get_localized_string(30102),
             channel="favoritos",
             action="mainlist",
             thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                    "images", "main_menu_fav.png"),
             fanart=os.path.join(config.get_runtime_path(), "resources",
                                 "images", "background.jpg"),
             viewmode="movie"))
    if config.get_library_support():
        itemlist.append(
            Item(title=config.get_localized_string(30131),
                 channel="biblioteca",
                 action="mainlist",
                 thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                        "images", "main_menu_library.png"),
                 fanart=os.path.join(config.get_runtime_path(), "resources",
                                     "images", "background.jpg"),
                 viewmode="movie"))

    if "xbmceden" in config.get_platform():
        itemlist.append(
            Item(title=config.get_localized_string(30100),
                 channel="configuracion",
                 action="mainlist",
                 thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                        "images", "main_menu_conf.png"),
                 fanart=os.path.join(config.get_runtime_path(), "resources",
                                     "images", "background.jpg"),
                 folder=False,
                 viewmode="movie"))
    else:
        itemlist.append(
            Item(title=config.get_localized_string(30100),
                 channel="configuracion",
                 action="mainlist",
                 thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                        "images", "main_menu_conf.png"),
                 fanart=os.path.join(config.get_runtime_path(), "resources",
                                     "images", "background.jpg"),
                 viewmode="movie"))

    itemlist.append(
        Item(title=config.get_localized_string(30104),
             channel="ayuda",
             action="mainlist",
             thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                    "images", "main_menu_help.png"),
             fanart=os.path.join(config.get_runtime_path(), "resources",
                                 "images", "background.jpg"),
             viewmode="movie"))
    return itemlist
Example #55
0
def alerterrorpagina():
    advertencia = xbmcgui.Dialog()
    #'Error en el sitio web'
    #'No se puede acceder por un error en el sitio web'
    resultado = advertencia.ok(config.get_localized_string(30059) , config.get_localized_string(30060))
def set_opcion(item, seleccion, opciones, video_urls):
    logger.info("platformtools set_opcion")
    # logger.debug(item.tostring('\n'))
    salir = False
    # No ha elegido nada, lo más probable porque haya dado al ESC
    # TODO revisar
    if seleccion == -1:
        # Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem(item.title,
                                    iconImage="DefaultVideo.png",
                                    thumbnailImage=item.thumbnail)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, listitem)

    # "Enviar a JDownloader"
    if opciones[seleccion] == config.get_localized_string(30158):
        from core import scrapertools

        # TODO comprobar que devuelve 'data'
        if item.subtitle != "":
            data = scrapertools.cachePage(
                config.get_setting("jdownloader") +
                "/action/add/links/grabber0/start1/web=" + item.url + " " +
                item.thumbnail + " " + item.subtitle)
        else:
            data = scrapertools.cachePage(
                config.get_setting("jdownloader") +
                "/action/add/links/grabber0/start1/web=" + item.url + " " +
                item.thumbnail)
        salir = True

    # "Descargar"
    elif opciones[seleccion] == config.get_localized_string(30153):
        from channels import descargas
        if item.contentType == "list" or item.contentType == "tvshow":
            item.contentType = "video"
        item.play_menu = True
        descargas.save_download(item)
        salir = True

    # "Quitar de favoritos"
    elif opciones[seleccion] == config.get_localized_string(30154):
        from channels import favoritos
        favoritos.delFavourite(item)
        salir = True

    # "Añadir a favoritos":
    elif opciones[seleccion] == config.get_localized_string(30155):
        from channels import favoritos
        item.from_channel = "favoritos"
        favoritos.addFavourite(item)
        salir = True

    # "Añadir a Biblioteca":  # Library
    elif opciones[seleccion] == config.get_localized_string(30161):
        titulo = item.fulltitle
        if titulo == "":
            titulo = item.title

        new_item = item.clone(title=titulo,
                              action="play_from_library",
                              category="Cine",
                              fulltitle=item.fulltitle,
                              channel=item.channel)

        from core import library
        library.add_pelicula_to_library(new_item)

        salir = True

    # "Buscar Trailer":
    elif opciones[seleccion] == config.get_localized_string(30162):
        config.set_setting("subtitulo", "false")
        xbmc.executebuiltin("XBMC.RunPlugin(%s?%s)" %
                            (sys.argv[0],
                             item.clone(channel="trailertools",
                                        action="buscartrailer",
                                        contextual=True).tourl()))
        salir = True

    return salir
Example #57
0
def play_video(channel="",server="",url="",category="",title="", thumbnail="",plot="",extra="",desdefavoritos=False,desdedescargados=False,desderrordescargas=False,strmfile=False,Serie="",subtitle="", video_password="",fulltitle=""):
    from servers import servertools
    import sys
    import xbmcgui,xbmc
    try:
        logger.info("[xbmctools.py] play_video(channel=%s, server=%s, url=%s, category=%s, title=%s, thumbnail=%s, plot=%s, desdefavoritos=%s, desdedescargados=%s, desderrordescargas=%s, strmfile=%s, Serie=%s, subtitle=%s" % (channel,server,url,category,title,thumbnail,plot,desdefavoritos,desdedescargados,desderrordescargas,strmfile,Serie,subtitle))
    except:
        pass

    try:
        server = server.lower()
    except:
        server = ""

    if server=="":
        server="directo"

    try:
        from core import descargas
        download_enable=True
    except:
        download_enable=False

    view = False
    # Abre el diálogo de selección
    opciones = []
    default_action = config.get_setting("default_action")
    logger.info("default_action="+default_action)

    # Si no es el modo normal, no muestra el diálogo porque cuelga XBMC
    muestra_dialogo = (config.get_setting("player_mode")=="0" and not strmfile)

    # Extrae las URL de los vídeos, y si no puedes verlo te dice el motivo
    video_urls,puedes,motivo = servertools.resolve_video_urls_for_playing(server,url,video_password,muestra_dialogo)

    # Si puedes ver el vídeo, presenta las opciones
    if puedes:
        
        for video_url in video_urls:
            opciones.append(config.get_localized_string(30151) + " " + video_url[0])

        if server=="local":
            opciones.append(config.get_localized_string(30164))
        else:
            if download_enable:
                opcion = config.get_localized_string(30153)
                opciones.append(opcion) # "Descargar"
    
            if channel=="favoritos": 
                opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"
            else:
                opciones.append(config.get_localized_string(30155)) # "Añadir a favoritos"
        
            if not strmfile:
                opciones.append(config.get_localized_string(30161)) # "Añadir a Biblioteca"
        
            if download_enable:
                if channel!="descargas":
                    opciones.append(config.get_localized_string(30157)) # "Añadir a lista de descargas"
                else:
                    if category=="errores":
                        opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
                        opciones.append(config.get_localized_string(30160)) # "Pasar de nuevo a lista de descargas"
                    else:
                        opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
    
            if config.get_setting("jdownloader_enabled")=="true":
                opciones.append(config.get_localized_string(30158)) # "Enviar a JDownloader"
            if config.get_setting("pyload_enabled")=="true":
                opciones.append(config.get_localized_string(30158).replace("jDownloader","pyLoad")) # "Enviar a pyLoad"

        if default_action=="3":
            seleccion = len(opciones)-1
    
        # Busqueda de trailers en youtube    
        if not channel in ["Trailer","ecarteleratrailers"]:
            opciones.append(config.get_localized_string(30162)) # "Buscar Trailer"

    # Si no puedes ver el vídeo te informa
    else:
        import xbmcgui
        if server!="":
            advertencia = xbmcgui.Dialog()
            if "<br/>" in motivo:
                resultado = advertencia.ok( "Non è possibile guardare il video perché...",motivo.split("<br/>")[0],motivo.split("<br/>")[1],url)
            else:
                resultado = advertencia.ok( "Non è possibile guardare il video perché...",motivo,url)
        else:
            resultado = advertencia.ok( "Non è possibile guardare il video perché...","Il server che lo ospita non è","ancora supportato da streamondemand",url)

        if channel=="favoritos": 
            opciones.append(config.get_localized_string(30154)) # "Quitar de favoritos"

        if channel=="descargas":
            if category=="errores":
                opciones.append(config.get_localized_string(30159)) # "Borrar descarga definitivamente"
            else:
                opciones.append(config.get_localized_string(30156)) # "Quitar de lista de descargas"
        
        if len(opciones)==0:
            return

    # Si la accion por defecto es "Preguntar", pregunta
    if default_action=="0": # and server!="torrent":
        import xbmcgui
        dia = xbmcgui.Dialog()
        seleccion = dia.select(config.get_localized_string(30163), opciones) # "Elige una opción"
        #dia.close()
        '''
        elif default_action=="0" and server=="torrent":
            advertencia = xbmcgui.Dialog()
            logger.info("video_urls[0]="+str(video_urls[0][1]))
            if puedes and ('"status":"COMPLETED"' in video_urls[0][1] or '"percent_done":100' in video_urls[0][1]):
                listo  = "y está listo para ver"
            else:
                listo = "y se está descargando"
            resultado = advertencia.ok( "Torrent" , "El torrent ha sido añadido a la lista" , listo )
            seleccion=-1
        '''
    elif default_action=="1":
        seleccion = 0
    elif default_action=="2":
        seleccion = len(video_urls)-1
    elif default_action=="3":
        seleccion = seleccion
    else:
        seleccion=0

    logger.info("seleccion=%d" % seleccion)
    logger.info("seleccion=%s" % opciones[seleccion])

    # No ha elegido nada, lo más probable porque haya dado al ESC 
    if seleccion==-1:
        #Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),False,listitem)    # JUR Added
        #if config.get_setting("subtitulo") == "true":
        #    config.set_setting("subtitulo", "false")
        return

    if opciones[seleccion]==config.get_localized_string(30158): # "Enviar a JDownloader"
        #d = {"web": url}urllib.urlencode(d)
        from core import scrapertools
        
        if subtitle!="":
            data = scrapertools.cache_page(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+url+ " " +thumbnail + " " + subtitle)
        else:
            data = scrapertools.cache_page(config.get_setting("jdownloader")+"/action/add/links/grabber0/start1/web="+url+ " " +thumbnail)

        return

    if opciones[seleccion]==config.get_localized_string(30158).replace("jDownloader","pyLoad"): # "Enviar a pyLoad"
        logger.info("Enviando a pyload...")

        if Serie!="":
            package_name = Serie
        else:
            package_name = "streamondemand"

        from core import pyload_client
        pyload_client.download(url=url,package_name=package_name)
        return

    elif opciones[seleccion]==config.get_localized_string(30164): # Borrar archivo en descargas
        # En "extra" está el nombre del fichero en favoritos
        import os
        os.remove( url )
        xbmc.executebuiltin( "Container.Refresh" )
        return

    # Ha elegido uno de los vídeos
    elif seleccion < len(video_urls):
        mediaurl = video_urls[seleccion][1]
        if len(video_urls[seleccion])>2:
            wait_time = video_urls[seleccion][2]
        else:
            wait_time = 0
        view = True

    # Descargar
    elif opciones[seleccion]==config.get_localized_string(30153): # "Descargar"
        import xbmc
        # El vídeo de más calidad es el último
        mediaurl = video_urls[len(video_urls)-1][1]

        from core import downloadtools
        keyboard = xbmc.Keyboard(fulltitle)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            title = keyboard.getText()
            devuelve = downloadtools.downloadbest(video_urls,title)
            
            if devuelve==0:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Scaricato con successo")
            elif devuelve==-1:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Download interrotto")
            else:
                advertencia = xbmcgui.Dialog()
                resultado = advertencia.ok("plugin" , "Errore nel download")
        return

    elif opciones[seleccion]==config.get_localized_string(30154): #"Quitar de favoritos"
        from core import favoritos
        # En "extra" está el nombre del fichero en favoritos
        favoritos.deletebookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30105)) # 'Se ha quitado de favoritos'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30159): #"Borrar descarga definitivamente"
        from core import descargas
        descargas.delete_error_bookmark(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de la lista'
        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30160): #"Pasar de nuevo a lista de descargas":
        from core import descargas
        descargas.mover_descarga_error_a_pendiente(urllib.unquote_plus( extra ))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30107)) # 'Ha pasado de nuevo a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30155): #"Añadir a favoritos":
        from core import favoritos
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle)+" ["+channel+"]")
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            favoritos.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
        return

    elif opciones[seleccion]==config.get_localized_string(30156): #"Quitar de lista de descargas":
        from core import descargas
        # La categoría es el nombre del fichero en la lista de descargas
        descargas.deletebookmark((urllib.unquote_plus( extra )))

        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30106)) # 'Se ha quitado de lista de descargas'

        xbmc.executebuiltin( "Container.Refresh" )
        return

    elif opciones[seleccion]==config.get_localized_string(30157): #"Añadir a lista de descargas":
        from core import descargas
        from core import downloadtools

        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(fulltitle))
        keyboard.doModal()
        if keyboard.isConfirmed():
            title = keyboard.getText()
            descargas.savebookmark(titulo=title,url=url,thumbnail=thumbnail,server=server,plot=plot,fulltitle=title)
            
            advertencia = xbmcgui.Dialog()
            resultado = advertencia.ok(config.get_localized_string(30101) , title , config.get_localized_string(30109)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30161): #"Añadir a Biblioteca":  # Library
        from platformcode import library
        titulo = fulltitle
        if fulltitle=="":
            titulo = title
        library.savelibrary(titulo,url,thumbnail,server,plot,canal=channel,category=category,Serie=Serie)
        advertencia = xbmcgui.Dialog()
        resultado = advertencia.ok(config.get_localized_string(30101) , fulltitle , config.get_localized_string(30135)) # 'se ha añadido a la lista de descargas'
        return

    elif opciones[seleccion]==config.get_localized_string(30162): #"Buscar Trailer":
        config.set_setting("subtitulo", "false")
        import sys
        xbmc.executebuiltin("Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s&server=%s)" % ( sys.argv[ 0 ] , "trailertools" , "buscartrailer" , urllib.quote_plus( category ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" ) , server ))
        return

    # Si no hay mediaurl es porque el vídeo no está :)
    logger.info("[xbmctools.py] mediaurl="+mediaurl)
    if mediaurl=="":
        logger.info("b1")
        if server == "unknown":
            alertUnsopportedServer()
        else:
            alertnodisponibleserver(server)
        return

    # Si hay un tiempo de espera (como en megaupload), lo impone ahora
    if wait_time>0:
        logger.info("b2")
        continuar = handle_wait(wait_time,server,"Caricamento vídeo...")
        if not continuar:
            return

    # Obtención datos de la Biblioteca (solo strms que estén en la biblioteca)
    import xbmcgui
    if strmfile:
        logger.info("b3")
        xlistitem = getLibraryInfo(mediaurl)
    else:
        logger.info("b4")
        try:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail, path=mediaurl)
        except:
            xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        xlistitem.setInfo( "video", { "Title": title, "Plot" : plot , "Studio" : channel , "Genre" : category } )

    # Descarga el subtitulo
    if channel=="cuevana" and subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        logger.info("b5")
        try:
            import os
            ficherosubtitulo = os.path.join( config.get_data_path(), 'subtitulo.srt' )
            if os.path.exists(ficherosubtitulo):
                try:
                  os.remove(ficherosubtitulo)
                except IOError:
                  logger.info("Errore nell'eliminazione del file subtitulo.srt "+ficherosubtitulo)
                  raise
        
            from core import scrapertools
            data = scrapertools.cache_page(subtitle)
            #print data
            fichero = open(ficherosubtitulo,"w")
            fichero.write(data)
            fichero.close()
            #from core import downloadtools
            #downloadtools.downloadfile(subtitle, ficherosubtitulo )
        except:
            logger.info("Errore nel download del sottotitolo")

    # Lanza el reproductor
    if strmfile: #Si es un fichero strm no hace falta el play
        logger.info("b6")
        import sys
        xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,xlistitem)
        #if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
        #    logger.info("[xbmctools.py] Con subtitulos")
        #    setSubtitles()
        
    else:
        logger.info("b7")
        logger.info("player_mode="+config.get_setting("player_mode"))
        logger.info("mediaurl="+mediaurl)
        if config.get_setting("player_mode")=="3" or "megacrypter.com" in mediaurl:
            logger.info("b11")
            import download_and_play
            download_and_play.download_and_play( mediaurl , "download_and_play.tmp" , config.get_setting("downloadpath") )
            return

        elif config.get_setting("player_mode")=="0" or (config.get_setting("player_mode")=="3" and mediaurl.startswith("rtmp")):
            logger.info("b8")
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()
            playlist.add( mediaurl, xlistitem )

            # Reproduce
            # playersettings = config.get_setting('player_type')
            # logger.info("[xbmctools.py] playersettings="+playersettings)
        
            # player_type = xbmc.PLAYER_CORE_AUTO
            # if playersettings == "0":
            #     player_type = xbmc.PLAYER_CORE_AUTO
            #     logger.info("[xbmctools.py] PLAYER_CORE_AUTO")
            # elif playersettings == "1":
            #     player_type = xbmc.PLAYER_CORE_MPLAYER
            #     logger.info("[xbmctools.py] PLAYER_CORE_MPLAYER")
            # elif playersettings == "2":
            #     player_type = xbmc.PLAYER_CORE_DVDPLAYER
            #     logger.info("[xbmctools.py] PLAYER_CORE_DVDPLAYER")
        
            xbmcPlayer = xbmc.Player()
            xbmcPlayer.play(playlist)
            
            if channel=="cuevana" and subtitle!="":
                logger.info("subtitulo="+subtitle)
                if subtitle!="" and (opciones[seleccion].startswith("Ver") or opciones[seleccion].startswith("Watch")):
                    logger.info("[xbmctools.py] Con subtitulos")
                    setSubtitles()

        elif config.get_setting("player_mode")=="1":
            logger.info("b9")
            #xlistitem.setProperty('IsPlayable', 'true')
            #xlistitem.setProperty('path', mediaurl)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=mediaurl))
        
        elif config.get_setting("player_mode")=="2":
            logger.info("b10")
            xbmc.executebuiltin( "PlayMedia("+mediaurl+")" )
        
    # Descarga en segundo plano para vidxden, sólo en modo free
    '''
    elif server=="vidxden" and seleccion==0:
        from core import downloadtools
        import thread,os
        import xbmc
        
        logger.info("[xbmctools.py] ---------------------------------")
        logger.info("[xbmctools.py] DESCARGA EN SEGUNDO PLANO")
        logger.info("[xbmctools.py]   de "+mediaurl)
        temp_file = config.get_temp_file("background.file")
        if os.path.exists(temp_file):
            os.remove(temp_file)
        logger.info("[xbmctools.py]   a "+temp_file)
        logger.info("[xbmctools.py] ---------------------------------")
        thread.start_new_thread(downloadtools.downloadfile, (mediaurl,temp_file), {'silent':True})
        handle_wait(60,"Descarga en segundo plano","Se está descargando un trozo antes de empezar")
        playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
        playlist.clear()
        playlist.add( temp_file, xlistitem )
    
        player_type = xbmc.PLAYER_CORE_AUTO
        xbmcPlayer = xbmc.Player( player_type )
        xbmcPlayer.play(playlist)
        
        while xbmcPlayer.isPlaying():
            xbmc.sleep(5000)
            logger.info("sigo aquí...")
        logger.info("fin")
    '''

    if config.get_setting("subtitulo") == "true" and view:
        logger.info("b11")
        from platformcode import subtitletools
        wait2second()
        subtitletools.set_Subtitle()
        if subtitle!="":
            xbmc.Player().setSubtitles(subtitle)
    #FIXME: Qué cosa más fea...
    elif channel=="moviezet":
        xbmc.Player().setSubtitles(subtitle)
Example #58
0
    def start(self,
              list_controls=None,
              dict_values=None,
              title="Opzioni",
              callback=None,
              item=None,
              custom_button=None,
              channelpath=None):
        logger.info("[xbmc_config_menu] start")

        # Ruta para las imagenes de la ventana
        self.mediapath = os.path.join(config.get_runtime_path(), 'resources',
                                      'skins', 'Default', 'media')

        # Capturamos los parametros
        self.list_controls = list_controls
        self.values = dict_values
        self.title = title
        self.callback = callback
        self.item = item

        if type(custom_button) == dict:
            self.custom_button = {}
            self.custom_button["label"] = custom_button.get("label", "")
            self.custom_button["function"] = custom_button.get("function", "")
            self.custom_button["visible"] = bool(
                custom_button.get("visible", True))
            self.custom_button["close"] = bool(
                custom_button.get("close", False))
        else:
            self.custom_button = None

        # Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal
        if not channelpath:
            channelpath = inspect.currentframe(
            ).f_back.f_back.f_code.co_filename
        self.channel = os.path.basename(channelpath).replace(".py", "")

        # Si no tenemos list_controls, hay que sacarlos del xml del canal
        if not self.list_controls:

            # Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools
            if os.path.join(config.get_runtime_path(),
                            "channels") in channelpath:

                # La llamada se hace desde un canal
                self.list_controls, default_values = channeltools.get_channel_controls_settings(
                    self.channel)

            # En caso contrario salimos
            else:
                return None

        # Si no se pasan dict_values, creamos un dict en blanco
        if self.values is None:
            self.values = {}

        # Ponemos el titulo
        if self.title == "":
            self.title = str(config.get_localized_string(
                30100)) + " -- " + self.channel.capitalize()

        elif self.title.startswith('@') and unicode(
                self.title[1:]).isnumeric():
            self.title = config.get_localized_string(int(self.title[1:]))

        # Muestra la ventana
        self.return_value = None
        self.doModal()
        return self.return_value
Example #59
0
def addnewvideo( canal , accion , category , server , title , url , thumbnail, plot ,Serie="",duration="",fanart="",IsPlayable='false',context = "", subtitle="", viewmode="", totalItems = 0, show="", password="", extra="",fulltitle="", extrameta=None, extracmds=None):
    contextCommands = []
    ok = False
    try:
        context = urllib.unquote_plus(context)
    except:
        context=""
    if "|" in context:
        context = context.split("|")
    if DEBUG:
        try:
            logger.info('[xbmctools.py] addnewvideo( "'+canal+'" , "'+accion+'" , "'+category+'" , "'+server+'" , "'+title+'" ("'+fulltitle+'") , "' + url + '" , "'+thumbnail+'" , "'+plot+'")" , "'+Serie+'")"')
        except:
            logger.info('[xbmctools.py] addnewvideo(<unicode>)')
            
    icon_image = os.path.join( config.get_runtime_path() , "resources" , "images" , "servers" , server+".png" )
    if not os.path.exists(icon_image):
        icon_image = "DefaultVideo.png"
     
    listitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail )
    listitem.setInfo( "video", { "Title" : title, "FileName" : title, "Plot" : plot, "Duration" : duration, "Studio" : canal, "Genre" : category } )
    if extrameta: listitem.setInfo( "video", extrameta )

    if fanart!="":
        #logger.info("fanart :%s" %fanart)
        listitem.setProperty('fanart_image',fanart)
        xbmcplugin.setPluginFanart(pluginhandle, fanart)

    if IsPlayable == 'true': #Esta opcion es para poder utilizar el xbmcplugin.setResolvedUrl()
        listitem.setProperty('IsPlayable', 'true')
    #listitem.setProperty('fanart_image',os.path.join(IMAGES_PATH, "cinetube.png"))
    if "1" in context: #El uno añade al menu contextual la opcion de guardar en megalive un canal a favoritos
        addItemCommand = "XBMC.RunPlugin(%s?channel=%s&action=%s&category=%s&title=%s&fulltitle=%s&url=%s&thumbnail=%s&plot=%s&server=%s&Serie=%s&show=%s&password=%s&extradata=%s)" % ( sys.argv[ 0 ] , canal , "saveChannelFavorites" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( plot ) , server , Serie, urllib.quote_plus(show), urllib.quote_plus( password) , urllib.quote_plus(extra) )
        contextCommands.append((config.get_localized_string(30301),addItemCommand))
        
    if "2" in context:#El dos añade al menu contextual la opciones de eliminar y/o renombrar un canal en favoritos 
        addItemCommand = "XBMC.RunPlugin(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s&server=%s&Serie=%s&show=%s&password=%s&extradata=%s)" % ( sys.argv[ 0 ] , canal , "deleteSavedChannel" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( plot ) , server , Serie, urllib.quote_plus( show), urllib.quote_plus( password) , urllib.quote_plus(extra) )
        contextCommands.append((config.get_localized_string(30302),addItemCommand))
        addItemCommand = "XBMC.RunPlugin(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s&server=%s&Serie=%s&show=%s&password=%s&extradata=%s)" % ( sys.argv[ 0 ] , canal , "renameChannelTitle" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( plot ) , server , Serie, urllib.quote_plus( show),urllib.quote_plus( password) , urllib.quote_plus(extra) )
        contextCommands.append((config.get_localized_string(30303),addItemCommand))
            
    if "6" in context:# Ver canal en vivo en justintv
        justinCommand = "XBMC.PlayMedia(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s)" % ( sys.argv[ 0 ] , "justintv" , "playVideo" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( plot )  )
        contextCommands.append((config.get_localized_string(30410),justinCommand))

    if "7" in context:# Listar videos archivados en justintv
        justinCommand = "XBMC.Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s)" % ( sys.argv[ 0 ] , "justintv" , "listarchives" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" )  )
        contextCommands.append((config.get_localized_string(30409),justinCommand))

    if "8" in context:# Añadir canal a favoritos justintv
        justinCommand = "XBMC.RunPlugin(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s)" % ( sys.argv[ 0 ] , "justintv" , "addToFavorites" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" )  )
        contextCommands.append((config.get_localized_string(30406),justinCommand))

    if "9" in context:# Remover canal de favoritos justintv
        justinCommand = "XBMC.Container.Update(%s?channel=%s&action=%s&category=%s&title=%s&url=%s&thumbnail=%s&plot=%s)" % ( sys.argv[ 0 ] , "justintv" , "removeFromFavorites" , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( "" )  )
        contextCommands.append((config.get_localized_string(30407),justinCommand))

    if len (contextCommands) > 0:
        listitem.addContextMenuItems ( contextCommands, replaceItems=False)
    if extracmds:
        listitem.addContextMenuItems ( extracmds, replaceItems=False)
    try:
        title = title.encode ("utf-8")     #This only aplies to unicode strings. The rest stay as they are.
        plot  = plot.encode ("utf-8")
    except:
        pass
    
    itemurl = '%s?fanart=%s&channel=%s&action=%s&category=%s&title=%s&fulltitle=%s&url=%s&thumbnail=%s&plot=%s&server=%s&Serie=%s&subtitle=%s&viewmode=%s&show=%s&extradata=%s' % ( sys.argv[ 0 ] , fanart, canal , accion , urllib.quote_plus( category ) , urllib.quote_plus( title ) , urllib.quote_plus( fulltitle ) , urllib.quote_plus( url ) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( plot ) , server , Serie , urllib.quote_plus(subtitle), urllib.quote_plus(viewmode), urllib.quote_plus( show ) , urllib.quote_plus(extra) )
    #logger.info("[xbmctools.py] itemurl=%s" % itemurl)
    if totalItems == 0:
        ok = xbmcplugin.addDirectoryItem( handle = pluginhandle, url=itemurl, listitem=listitem, isFolder=False)
    else:
        ok = xbmcplugin.addDirectoryItem( handle = pluginhandle, url=itemurl, listitem=listitem, isFolder=False, totalItems=totalItems)
    return ok
Example #60
0
def alertUnsopportedServer():
    advertencia = xbmcgui.Dialog()
    # 'Servidor no soportado o desconocido' , 'Prueba en otro servidor o en otro canal'
    resultado = advertencia.ok( config.get_localized_string(30065),config.get_localized_string(30058))