def ActualizarCanal(channel, Texto="Actualizado con exíto"): xbmcgui.Dialog().notification('Actualizaciones automaticas', 'Buscado actualizaciones...', xbmcgui.NOTIFICATION_INFO ,1000) itemlist=[] try: logger.info("Verificando actualización de: " + channel) actualizado = updater.updatechannel(channel) if actualizado: itemlist.append(Item(channel="launcher", action="alert", title=Texto)) except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) return itemlist
def update_channels(): channel_path = os.path.join(config.get_runtime_path(), "channels", '*.xml') channel_files = glob.glob(channel_path) # ---------------------------- import xbmcgui progress = xbmcgui.DialogProgressBG() progress.create("Update channels list") # ---------------------------- for index, channel in enumerate(channel_files): # ---------------------------- percentage = index * 100 / len(channel_files) # ---------------------------- channel_id = os.path.basename(channel)[:-4] updater.updatechannel(channel_id) # ---------------------------- progress.update(percentage, ' Update channel: ' + channel_id) # ---------------------------- # ---------------------------- progress.close()
def ActualizarCanal(channel, Texto="Actualizado con exíto"): xbmcgui.Dialog().notification('Actualizaciones automaticas', 'Buscado actualizaciones...', xbmcgui.NOTIFICATION_INFO, 1000) itemlist = [] try: logger.info("Verificando actualización de: " + channel) actualizado = updater.updatechannel(channel) if actualizado: itemlist.append( Item(channel="launcher", action="alert", title=Texto)) except: import sys for line in sys.exc_info(): logger.error("%s" % line) return itemlist
def run(): logger.info("[launcher.py] run") # Test if all the required directories are created config.verify_directories_created() # Extract parameters from sys.argv params, channel_name, title, channel_title, show_title, fulltitle, url, thumbnail, plot, uid, action, server, extra, subtitle, category, show, password = extract_parameters() logger.info("[launcher.py] 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" % (channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password)) if action=="": return 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("[launcher.py] 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=="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("[launcher.py] regular_channel_path=%s" % regular_channel_path) logger.info("[launcher.py] core_channel_path=%s" % core_channel_path) if channel_name=="buscador": import pelisalacarta.buscador 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("[launcher.py] 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("[launcher.py] 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("[launcher.py] multiplatform channel") from core.item import Item item = Item(channel=channel_name, title=title , channel_title=channel_title , show_title=show_title , fulltitle=fulltitle, url=url, thumbnail=thumbnail , plot=plot , uid=uid, server=server, category=category, extra=extra, subtitle=subtitle, show=show, password=password) ''' if item.subtitle!="": logger.info("[launcher.py] 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("[launcher.py] No subtitle") ''' from platformcode import xbmctools if action=="play": logger.info("[launcher.py] play") # Si el canal tiene una acción "play" tiene prioridad if hasattr(channel, 'play'): logger.info("[launcher.py] 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) else: import xbmcgui ventana_error = xbmcgui.Dialog() ok = ventana_error.ok ("plugin", "No hay nada para reproducir") else: logger.info("[launcher.py] 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) elif action=="strm_detail" or action=="play_from_library": logger.info("[launcher.py] 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("[launcher.py] 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("[launcher.py] add_serie_to_library") from platformcode import library import xbmcgui # Obtiene el listado desde el que se llamó action = item.extra 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) 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 último (el que dice "Añadir esta serie...") if i<len(itemlist): 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 ) except IOError: import sys for line in sys.exc_info(): logger.error( "%s" % line ) logger.info("[launcher.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="ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta")) logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios") else: itemlist.append(Item(title="La serie se ha añadido a la 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_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) f.write(item.show+","+item.url+","+item.channel+"\n") f.close(); elif action.startswith("serie_options##"): from core import suscription import xbmcgui dia = xbmcgui.Dialog() opciones = [] suscription_item = Item(channel=item.channel, title=item.show, url=item.url, action=action.split("##")[1], extra=item.extra, plot=item.plot, show=item.show, thumbnail=item.thumbnail) if not suscription.already_suscribed(suscription_item): opciones.append("Suscribirme a esta serie") else: opciones.append("Quitar suscripción a esta serie") #opciones.append("Añadir esta serie a favoritos") opciones.append("Descargar todos los episodios") seleccion = dia.select("Elige una opción", opciones) # "Elige una opción" if seleccion==0: if not suscription.already_suscribed(suscription_item): suscription.append_suscription(suscription_item) yes_pressed = xbmcgui.Dialog().yesno( "tvalacarta" , "Suscripción a \""+suscription_item.title+"\" creada" , "¿Quieres descargar los vídeos existentes ahora?" ) if yes_pressed: download_all_episodes(suscription_item,channel) else: suscription.remove_suscription(suscription_item) xbmcgui.Dialog().ok( "tvalacarta" , "Suscripción a \""+suscription_item.title+"\" eliminada" , "Los vídeos que hayas descargado se mantienen" ) elif seleccion==1: download_all_episodes(suscription_item,channel) ''' elif seleccion==1: from core import favoritos from core import downloadtools import xbmc keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(item.show)+" ["+item.channel+"]") keyboard.doModal() if keyboard.isConfirmed(): title = keyboard.getText() favoritos.savebookmark(titulo=title,url=item.url,thumbnail=item.thumbnail,server="",plot=item.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 action=="search": logger.info("[launcher.py] 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("[launcher.py] executing channel '"+action+"' method") if action!="findvideos": exec "itemlist = channel."+action+"(item)" else: # Intenta ejecutar una posible funcion "findvideos" del canal try: exec "itemlist = channel."+action+"(item)" # Si no funciona, lanza el método genérico para detectar vídeos except: logger.info("[launcher.py] no channel 'findvideos' method, executing core method") from servers import servertools itemlist = servertools.find_video_items(item) from core 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 import 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: %d , 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)
def controller(plugin_name, port, host, path, headers): # Lee la plantilla file_plantilla = open( os.path.join(config.get_runtime_path(), "platformcode", "mediaserver", "template", "page.html")) plantilla_pagina = file_plantilla.read() file_plantilla.close() file_plantilla = open( os.path.join(config.get_runtime_path(), "platformcode", "mediaserver", "template", "item.html")) plantilla_item = file_plantilla.read() file_plantilla.close() itemlist_respuesta = [] respuesta = "" try: # Menú principal if path == "/" + platform_name.PLATFORM_NAME + "/" or path == "/" + platform_name.PLATFORM_NAME: respuesta = plantilla_pagina.replace("{$page-title}", "pelisalacarta") import channelselector channelslist = channelselector.getmainlist() # Actualización automática de canales, actualiza la lista if config.get_setting("updatechannels") == "true": logger.info("Verificando actualización del channelselector") from core import updater actualizado = updater.updatechannel("channelselector") if actualizado: itemlist_respuesta.append( Item( url="http://" + host + "/" + platform_name.PLATFORM_NAME, title="¡Lista de canales actualizada¡", thumbnail= "http://pelisalacarta.mimediacenter.info/squares/Crystal_Clear_action_info.png", plot=channel.plot)) for channel in channelslist: # Quita el canal de ayuda y el de configuración, no sirven en WiiMC if channel.channel != "configuracion" and channel.channel != "ayuda": itemlist_respuesta.append( Item(title=channel.title, url="http://" + host + "/" + platform_name.PLATFORM_NAME + "/" + base64.b64encode(channel.serialize()).replace( "/", "%2F"), thumbnail=channel.thumbnail, plot=channel.plot)) else: item = extract_item_from_url(path) respuesta = plantilla_pagina.replace("{$page-title}", item.title) if item.channel == "channelselector" and item.action == "channeltypes": import channelselector channelslist = channelselector.getchanneltypes() for channel in channelslist: itemlist_respuesta.append( Item(url="http://" + host + "/" + platform_name.PLATFORM_NAME + "/" + base64.b64encode(channel.serialize()).replace( "/", "%2F"), title=channel.title, thumbnail=channel.thumbnail, plot=channel.plot)) elif item.channel == "channelselector" and item.action == "listchannels": import channelselector channelslist = channelselector.filterchannels(item.category) for channel in channelslist: if channel.type == "generic" or channel.type == "wiimc": channel.action = "mainlist" itemlist_respuesta.append( Item(url="http://" + host + "/" + platform_name.PLATFORM_NAME + "/" + base64.b64encode(channel.serialize()).replace( "/", "%2F"), title=channel.title, thumbnail=channel.thumbnail, plot=channel.plot)) else: itemlist, channel = getitems(item) # Las listas vacías son problemáticas, añade un elemento dummy if len(itemlist) == 0: itemlist.append(Item(title="(No hay elementos)")) for item in itemlist: if item.action == "search": if item.server == "": item.server = "none" if item.url == "": item.url = "none" url = "http://%s/%s" % ( host + "/" + platform_name.PLATFORM_NAME, base64.b64encode(item.serialize()).replace( "/", "%2F")) if item.thumbnail == "": item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/search.png" itemlist_respuesta.append( Item(url=url, title=item.title, thumbnail=item.thumbnail, plot=item.plot)) elif item.folder or item.action == "play" or item.action == "downloadall": if item.server == "": item.server = "none" if item.url == "": item.url = "none" if item.title == "": item.title = "Ver el video-" if item.thumbnail == "": #if item.server!="" and item.server.lower()!="directo": # item.thumbnail = "http://pelisalacarta.mimediacenter.info/servers/"+item.server+".png" #else: if item.folder: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/folder.png" else: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/file.png" url = "http://%s/%s" % ( host + "/" + platform_name.PLATFORM_NAME, base64.b64encode(item.serialize()).replace( "/", "%2F")) itemlist_respuesta.append( Item(url=url, title=item.title, thumbnail=item.thumbnail, plot=item.plot)) logger.info(" Nivel intermedio " + url) else: if item.thumbnail == "": #if item.server!="" and item.server.lower()!="directo": # item.thumbnail = "http://pelisalacarta.mimediacenter.info/servers/"+item.server+".png" #else: if item.folder: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/folder.png" else: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/file.png" itemlist_respuesta.append( Item(url=item.url, title=item.title, thumbnail=item.thumbnail, plot=item.plot)) logger.info(" Video " + item.url) itemlist_string = "" for item in itemlist_respuesta: item_string = plantilla_item item_string = item_string.replace("{$title}", item.title) item_string = item_string.replace("{$url}", item.url) item_string = item_string.replace("{$thumbnail}", item.thumbnail) item_string = item_string.replace( "{$plot}", scrapertools.htmlclean(item.plot)) itemlist_string = itemlist_string + item_string + "\n" respuesta = respuesta.replace("{$itemlist}", itemlist_string) except: import sys for line in sys.exc_info(): logger.error("%s" % line) return respuesta
def getitems(item): logger.info("getitems") itemlist = [] # Extrae los parámetros channel = item.channel accion = item.action url = item.url if url != "none": if not "filenium" in url: url = urllib.unquote_plus(url) server = item.server title = item.title extra = item.extra category = item.category fulltitle = item.fulltitle try: if accion == "mainlist" and config.get_setting( "updatechannels") == "true": try: logger.info("Verificando actualización del canal") from core import updater actualizado = updater.updatechannel(channel) if actualizado: itemlist.append( Item(title="¡Canal descargado y actualizado!")) except: import sys for line in sys.exc_info(): logger.error("%s" % line) # El item que invocó es importante para obtener el siguiente senderitem = Item(title=title, channel=channel, action=accion, url=url, server=server, extra=extra, category=category, fulltitle=fulltitle) if "|" in url: partes = urllib.unquote_plus(senderitem.url).split("|") refered_item = Item(title=partes[0], url=partes[2], thumbnail="", server=partes[1], plot="", extra=partes[3]) logger.info("refered_item title=" + refered_item.title + ", url=" + refered_item.url + ", server=" + refered_item.server + ", extra=" + refered_item.extra) else: refered_item = Item() # Importa el canal y ejecuta la función try: exec "from pelisalacarta.channels import " + channel + " as channelmodule" except: import sys for line in sys.exc_info(): logger.error("%s" % line) try: exec "from pelisalacarta import " + channel + " as channelmodule" except: import sys for line in sys.exc_info(): logger.error("%s" % line) try: exec "from core import " + channel + " as channelmodule" except: pass # play - es el menú de reproducción de un vídeo if accion == "play": logger.info("ACCION PLAY") if hasattr(channelmodule, 'play'): logger.info("[launcher.py] executing channel 'play' method") logger.info(channelmodule.__file__) itemlist = channelmodule.play(senderitem) senderitem = itemlist[0] senderitem.folder = False else: logger.info( "[launcher.py] no channel 'play' method, executing core method" ) itemlist = menu_video(senderitem) # play_video - genera una playlist con una sola entrada para que wiimc la reproduzca elif accion == "play_video": logger.info("ACCION PLAY_VIDEO") logger.info("url=" + senderitem.url) senderitem.folder = False itemlist.append(senderitem) # search - es el buscador elif channel == "buscador" and accion == "mainlist": logger.info("ACCION SEARCH (buscador)") texto = requestpath.split("plx")[1] exec "itemlist = buscador.do_search_results(texto)" elif accion == "search": logger.info("ACCION SEARCH") texto = requestpath.split("plx")[1] exec "itemlist = channelmodule." + accion + "(senderitem,texto)" # findvideos - debe encontrar videos reproducibles elif accion == "findvideos": logger.info("ACCION FINDVIDEOS") try: exec "itemlist = channelmodule." + accion + "(senderitem)" except: import sys for line in sys.exc_info(): logger.error("%s" % line) itemlist = findvideos(senderitem, channel) elif accion == "descargar": itemlist = download_item(senderitem, refered_item) elif accion == "download_all": itemlist = download_all(senderitem, refered_item) elif accion == "add_to_favorites": itemlist = add_to_favorites(senderitem, refered_item) elif accion == "remove_from_favorites": itemlist = remove_from_favorites(senderitem, refered_item) elif accion == "add_to_downloads": itemlist = add_to_downloads(senderitem, refered_item) elif accion == "remove_from_downloads": itemlist = remove_from_downloads(senderitem, refered_item) elif accion == "remove_from_error_downloads": itemlist = remove_from_error_downloads(senderitem, refered_item) elif accion == "add_again_to_downloads": itemlist = add_again_to_downloads(senderitem, refered_item) elif accion == "send_to_jdownloader": itemlist = send_to_jdownloader(senderitem, refered_item) elif accion == "search_trailer": itemlist = search_trailer(senderitem, refered_item) elif accion == "add_serie_to_wiideoteca": itemlist = wiideoteca.AgregarSerie(senderitem) elif accion == "UltimoVisto": itemlist = wiideoteca.UltimoVisto(senderitem) else: if senderitem.url == "none": senderitem.url = "" exec "itemlist.extend( channelmodule." + accion + "(senderitem) )" ''' # Lo almacena en cache fichero = open( cached_file ,"wb") cerealizer.dump(itemlist,fichero) fichero.close() ''' logger.info("Items devueltos") for item in itemlist: logger.info(" " + item.title + " | " + item.url + " | " + item.action) except: 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) return itemlist, channel
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("tvalacarta", 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="No se han encontrado vídeos", 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
def getitems(requestpath): logger.info("getitems") itemlist = [] # La ruta empleada en la petición ruta = requestpath.split("?")[0] logger.info("ruta="+ruta) # Los parámetros son las partes de la ruta separadas por "/" rutas = ruta.split("/") cadena = " " # Las imprime en el log for linea in rutas: cadena = cadena + linea + " | " logger.info( cadena ) # Extrae los parámetros channel = rutas[2] accion = rutas[3] url = rutas[4] if url!="none": url = urllib.unquote_plus(url) server = rutas[5].lower() title = urllib.unquote_plus(rutas[6]) extra = urllib.unquote_plus(rutas[7]) category = urllib.unquote_plus(rutas[8]) fulltitle = urllib.unquote_plus(rutas[9]) logger.info( "channel="+channel+", accion="+accion+", url="+url+", server="+server+", title="+title+", extra="+extra+", category="+category+" fulltitle="+fulltitle) print "channel="+channel+", accion="+accion+", url="+url+", server="+server+", title="+title+", extra="+extra+", category="+category if accion=="mainlist" and config.get_setting("updatechannels")=="true": logger.info("Verificando actualización del canal") from core import updater actualizado = updater.updatechannel(channel) if actualizado: itemlist.append( Item(title="¡Canal descargado y actualizado!") ) # Obtiene un nombre válido para la cache hashed_url = binascii.hexlify(md5.new(requestpath).digest()) cached_file = os.path.join( config.get_data_path() , "tmp" , "cache" , hashed_url ) logger.info("cached_file="+cached_file) # Si el fichero está en cache if channel not in ("trailertools","buscador","configuracion","pyload","wiidoteca") and os.path.exists(cached_file): # <-- logger.info( "Reading from cache" ) fichero = open( cached_file ,"rb") itemlist = cerealizer.load(fichero) fichero.close() else: logger.info( "Not cached" ) ### ESTUDIAR #if accion not in ("play","findvideos","detail"): titulo = "" ### # El item que invocó es importante para obtener el siguiente senderitem = Item( title=title , channel=channel, action=accion, url=url , server=server, extra=extra, category=category, fulltitle=fulltitle ) if "|" in url: ## <-- unquote despues de split para no interferir cuando | aparece en algun campo partes = senderitem.url.split("|") decpartes = [] for parte in partes: decpartes.append(urllib.unquote_plus(parte)) partes = decpartes ## <-- refered_item = Item(title=partes[0],url=partes[2],thumbnail=partes[5],server=partes[1],plot=partes[6],extra=partes[3], fulltitle=partes[4]) logger.info( "refered_item title="+refered_item.title+", url="+refered_item.url+", server="+refered_item.server+", extra="+refered_item.extra) else: refered_item = Item() # Importa el canal y ejecuta la función if channel in ("configuracion", "trailertools", "buscador") : exec "import "+channel else: try: exec "from tvalacarta.channels import "+channel except: exec "from core import "+channel # play - es el menú de reproducción de un vídeo if accion=="play": logger.info("ACCION PLAY") print "ACCION PLAY" try: exec "itemlist = "+channel+".play(senderitem)" print "itemlist = "+channel+".play(senderitem)" senderitem = itemlist[0] senderitem.folder=False except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) itemlist = menu_video(senderitem) # play_video - genera una playlist con una sola entrada para que wiimc la reproduzca elif accion=="play_video": logger.info("ACCION PLAY_VIDEO") senderitem.folder=False itemlist.append( senderitem ) # search - es el buscador elif accion == "search": logger.info("ACCION SEARCH") texto = requestpath.split(".rss")[1] exec "itemlist = "+channel+"."+accion+"(senderitem,texto)" # findvideos - debe encontrar videos reproducibles elif accion=="findvideos": logger.info("ACCION FINDVIDEOS") try: exec "itemlist = "+channel+"."+accion+"(senderitem)" except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) itemlist = findvideos(senderitem,channel) elif accion=="descargar": itemlist = download_item(senderitem,refered_item) elif accion=="downloadall": ## <-- itemlist = downloadall(senderitem,refered_item) ## <-- elif accion=="add_to_favorites": itemlist = add_to_favorites(senderitem,refered_item) elif accion=="remove_from_favorites": itemlist = remove_from_favorites(senderitem,refered_item) elif accion=="add_to_downloads": itemlist = add_to_downloads(senderitem,refered_item) elif accion=="remove_from_downloads": itemlist = remove_from_downloads(senderitem,refered_item) elif accion=="remove_from_error_downloads": itemlist = remove_from_error_downloads(senderitem,refered_item) elif accion=="add_again_to_downloads": itemlist = add_again_to_downloads(senderitem,refered_item) elif accion=="send_to_jdownloader": itemlist = send_to_jdownloader(senderitem,refered_item) elif accion=="send_to_pyload": itemlist = send_to_pyload(senderitem,refered_item) elif accion=="search_trailer": itemlist = search_trailer(senderitem,refered_item) elif accion=="add_serie_to_wiideoteca": itemlist = wiideoteca.AgregarSerie(senderitem) elif accion=="UltimoVisto": itemlist = wiideoteca.UltimoVisto(senderitem) else: if senderitem.url=="none": senderitem.url="" exec "itemlist.extend( "+channel+"."+accion+"(senderitem) )" # Lo almacena en cache fichero = open( cached_file ,"wb") cerealizer.dump(itemlist,fichero) fichero.close() logger.info("Items devueltos") for item in itemlist: logger.info( " " + item.title + " | " + item.url + " | " + item.action) return itemlist,channel
def run(): logger.info("streamondemand.platformcode.launcher run") # Extract item from sys.argv if sys.argv[2]: try: item = Item().fromurl(sys.argv[2]) params = "" #Esto es para mantener la compatiblidad con el formato anterior... #Contretamente para que funcionen los STRM hasta que no se actualicen al nuevo formato except: params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password, hasContentDetails, contentTitle, contentThumbnail, contentPlot = extract_parameters( ) item = Item(fanart=fanart, channel=channel_name, title=title, fulltitle=fulltitle, url=url, thumbnail=thumbnail, plot=plot, action=action, server=server, extra=extra, subtitle=subtitle, viewmode=viewmode, category=category, show=show, password=password, hasContentDetails=hasContentDetails, contentTitle=contentTitle, contentThumbnail=contentThumbnail, contentPlot=contentPlot) else: item = Item(action="selectchannel") params = "" logger.info(item.tostring()) if config.get_setting('filter_servers') == 'true': server_white_list, server_black_list = set_server_list() try: # Default action: open channel and launch mainlist function if (item.action == "selectchannel"): import channelselector itemlist = channelselector.mainlist(params, item.url, item.category) from platformcode import xbmctools xbmctools.renderItems(itemlist, item) # Actualizar version elif (item.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 (item.action == "channeltypes"): import channelselector itemlist = channelselector.channeltypes(params, item.url, item.category) from platformcode import xbmctools xbmctools.renderItems(itemlist, item) elif (item.action == "listchannels"): import channelselector itemlist = channelselector.listchannels(params, item.url, item.category) from platformcode import xbmctools xbmctools.renderItems(itemlist, item) # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel" else: 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") != "": import xbmc keyboard = xbmc.Keyboard("", "PIN para canales de adultos", True) keyboard.doModal() if (keyboard.isConfirmed()): tecleado = keyboard.getText() 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 if item.action == "mainlist" and 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", 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 streamondemand regular_channel_path = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") core_channel_path = os.path.join(config.get_runtime_path(), 'core', item.channel + ".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 item.channel == "personal" or item.channel == "personal2" or item.channel == "personal3" or item.channel == "personal4" or item.channel == "personal5": import channels.personal as channel elif os.path.exists(regular_channel_path): exec "import channels." + item.channel + " as channel" elif os.path.exists(core_channel_path): exec "from core import " + item.channel + " 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 item.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 (item.action == "strm"): from platformcode import xbmctools xbmctools.playstrm(params, item.url, item.category) else: exec "channel." + item.action + "(params, item.url, item.category)" else: logger.info( "streamondemand.platformcode.launcher multiplatform channel" ) ''' 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 item.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(item) 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(item) elif item.action == "strm_detail" or item.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 if item.server != "": try: from servers import servertools videourls = servertools.resolve_video_urls_for_playing( server=item.server, url=item.url, video_password=item.video_password) return videourls except: itemlist = [] pass else: try: itemlist = channel.findvideos(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers( itemlist, server_white_list, server_black_list) except: from servers import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers( itemlist, server_white_list, server_black_list) 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(item, strmfile=True) elif item.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 item.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('streamondemand', '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: 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 l'ha 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, item) #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 + "," + item.extra + "\n") f.close() elif item.action == "download_all_episodes": download_all_episodes(item, channel) elif item.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, item) else: logger.info( "streamondemand.platformcode.launcher executing channel '" + item.action + "' method") if item.action != "findvideos": exec "itemlist = channel." + item.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." + item.action + "(item)" if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers( itemlist, server_white_list, server_black_list) # 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) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers( itemlist, server_white_list, server_black_list) 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 handle = sys.argv[1] xbmcplugin.setContent(int(handle), "movies") # Añade los items a la lista de XBMC xbmctools.renderItems(itemlist, item) except urllib2.URLError, e: import traceback 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: %d , 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)
def controller(plugin_name,port,host,path,headers): # Lee la plantilla file_plantilla = open( os.path.join( config.get_runtime_path() , "platformcode" , "mediaserver" , "template" , "page.html") ) plantilla_pagina = file_plantilla.read() file_plantilla.close() file_plantilla = open( os.path.join( config.get_runtime_path() , "platformcode" , "mediaserver" , "template" , "item.html") ) plantilla_item = file_plantilla.read() file_plantilla.close() itemlist_respuesta = [] respuesta = "" try: # Menú principal if path == "/"+platform_name.PLATFORM_NAME+"/" or path=="/"+platform_name.PLATFORM_NAME: respuesta = plantilla_pagina.replace("{$page-title}","pelisalacarta") import channelselector channelslist = channelselector.getmainlist() # Actualización automática de canales, actualiza la lista if config.get_setting("updatechannels")=="true": logger.info("Verificando actualización del channelselector") from core import updater actualizado = updater.updatechannel("channelselector") if actualizado: itemlist_respuesta.append( Item( url="http://"+host+"/"+platform_name.PLATFORM_NAME , title="¡Lista de canales actualizada¡" , thumbnail="http://pelisalacarta.mimediacenter.info/squares/Crystal_Clear_action_info.png", plot=channel.plot ) ) for channel in channelslist: # Quita el canal de ayuda y el de configuración, no sirven en WiiMC if channel.channel!="configuracion" and channel.channel!="ayuda": itemlist_respuesta.append( Item(title=channel.title, url="http://"+host+"/"+platform_name.PLATFORM_NAME+"/"+base64.b64encode(channel.serialize()).replace("/","%2F"),thumbnail=channel.thumbnail, plot=channel.plot) ) else: item = extract_item_from_url(path) respuesta = plantilla_pagina.replace("{$page-title}",item.title) if item.channel=="channelselector" and item.action=="channeltypes": import channelselector channelslist = channelselector.getchanneltypes() for channel in channelslist: itemlist_respuesta.append( Item( url = "http://"+host+"/"+platform_name.PLATFORM_NAME+"/"+base64.b64encode(channel.serialize()).replace("/","%2F"), title = channel.title, thumbnail = channel.thumbnail, plot=channel.plot) ) elif item.channel=="channelselector" and item.action=="listchannels": import channelselector channelslist = channelselector.filterchannels(item.category) for channel in channelslist: if channel.type=="generic" or channel.type=="wiimc": channel.action="mainlist" itemlist_respuesta.append( Item( url = "http://"+host+"/"+platform_name.PLATFORM_NAME+"/"+base64.b64encode(channel.serialize()).replace("/","%2F"), title = channel.title, thumbnail = channel.thumbnail, plot=channel.plot) ) else: itemlist,channel = getitems(item) # Las listas vacías son problemáticas, añade un elemento dummy if len(itemlist)==0: itemlist.append( Item(title="(No hay elementos)") ) for item in itemlist: if item.action=="search": if item.server=="": item.server="none" if item.url=="": item.url="none" url = "http://%s/%s" % ( host+"/"+platform_name.PLATFORM_NAME , base64.b64encode( item.serialize() ).replace("/","%2F") ) if item.thumbnail=="": item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/search.png" itemlist_respuesta.append( Item(url=url, title = item.title, thumbnail=item.thumbnail, plot=item.plot) ) elif item.folder or item.action=="play" or item.action=="downloadall": if item.server=="": item.server="none" if item.url=="": item.url="none" if item.title=="": item.title="Ver el video-" if item.thumbnail=="": #if item.server!="" and item.server.lower()!="directo": # item.thumbnail = "http://pelisalacarta.mimediacenter.info/servers/"+item.server+".png" #else: if item.folder: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/folder.png" else: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/file.png" url = "http://%s/%s" % ( host+"/"+platform_name.PLATFORM_NAME , base64.b64encode( item.serialize() ).replace("/","%2F") ) itemlist_respuesta.append( Item(url=url, title = item.title, thumbnail=item.thumbnail, plot=item.plot) ) logger.info(" Nivel intermedio "+url) else: if item.thumbnail=="": #if item.server!="" and item.server.lower()!="directo": # item.thumbnail = "http://pelisalacarta.mimediacenter.info/servers/"+item.server+".png" #else: if item.folder: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/folder.png" else: item.thumbnail = "http://pelisalacarta.mimediacenter.info/squares/file.png" itemlist_respuesta.append( Item(url=item.url, title = item.title, thumbnail=item.thumbnail, plot=item.plot) ) logger.info(" Video "+item.url) itemlist_string ="" for item in itemlist_respuesta: item_string = plantilla_item item_string = item_string.replace("{$title}",item.title) item_string = item_string.replace("{$url}",item.url) item_string = item_string.replace("{$thumbnail}",item.thumbnail) item_string = item_string.replace("{$plot}",scrapertools.htmlclean(item.plot)) itemlist_string = itemlist_string+item_string+"\n" respuesta = respuesta.replace("{$itemlist}",itemlist_string) except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) return respuesta
def controller(plugin_name,port,host,path,headers): respuesta = "" respuesta += "version=7\n" respuesta += "logo=http://pelisalacarta.mimediacenter.info/icon.png\n" respuesta += "title="+plugin_name+" "+VERSIONTAG+" (WiiMC)\n" respuesta += "\n" if path == "/wiimc/" or path=="/wiimc": import channelselector channelslist = channelselector.getmainlist() # Actualización automática de canales, actualiza la lista if config.get_setting("updatechannels")=="true": logger.info("Verificando actualización del channelselector") try: from core import updater actualizado = updater.updatechannel("channelselector") if actualizado: respuesta += "type=playlist\n" respuesta += "name=¡Lista de canales actualizada!\n" respuesta += "thumb=\n" respuesta += "URL=http://"+host+"/wiimc/\n" respuesta += "\n" except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) for channel in channelslist: # Quita el canal de ayuda y el de configuración, no sirven en WiiMC if channel.channel!="configuracion" and channel.channel!="ayuda" and channel.channel!="trailertools": if channel.channel!="buscador": respuesta += "type=playlist\n" else: respuesta += "type=search\n" respuesta += "name="+channel.title+"\n" respuesta += "thumb=http://"+plugin_name+".mimediacenter.info/wiimc/"+channel.channel+".png\n" respuesta += "URL=http://"+host+"/wiimc/"+base64.b64encode(channel.serialize()).replace("/","%2F")+"/playlist.plx\n" respuesta += "\n" else: item = extract_item_from_url(path) if item.channel=="channelselector" and item.action=="channeltypes": import channelselector channelslist = channelselector.getchanneltypes() for channel in channelslist: if channel.category!="M" and channel.category!="G": respuesta += "type=playlist\n" respuesta += "name="+channel.title+"\n" respuesta += "thumb=http://"+plugin_name+".mimediacenter.info/wiimc/"+channel.channel+".png\n" respuesta += "URL=http://"+host+"/wiimc/"+base64.b64encode(channel.serialize()).replace("/","%2F")+"/playlist.plx\n" respuesta += "\n" elif item.channel=="channelselector" and item.action=="listchannels": import channelselector channelslist = channelselector.filterchannels(item.category) for channel in channelslist: if channel.type=="generic" or channel.type=="wiimc": channel.action="mainlist" respuesta += "type=playlist\n" respuesta += "name="+channel.title+"\n" respuesta += "thumb=http://"+plugin_name+".mimediacenter.info/wiimc/"+channel.channel+".png\n" respuesta += "URL=http://"+host+"/wiimc/"+base64.b64encode(channel.serialize()).replace("/","%2F")+"/playlist.plx\n" respuesta += "\n" else: itemlist,channel = getitems(item,path) # Las listas vacías son problemáticas, añade un elemento dummy if len(itemlist)==0: itemlist.append( Item(title="(No hay elementos)") ) for item in itemlist: if item.action=="search" or item.action=="login" or item.action=="password": if item.server=="": item.server="none" if item.url=="": item.url="none" url = "http://%s/%s/playlist.plx" % ( host+"/wiimc" , base64.b64encode( item.serialize() ).replace("/","%2F") ) respuesta += "type=search\n" respuesta += "name=%s\n" % item.title if item.thumbnail != "": respuesta += "thumb=%s\n" % item.thumbnail respuesta += "URL=%s\n" % url respuesta += "\n" if item.action=="search": logger.info(" Buscador "+url) else: logger.info(" Login "+url) elif item.folder or item.action=="play" or item.action=="downloadall": if item.server=="": item.server="none" if item.url=="": item.url="none" if item.title=="": item.title="Ver el video-" url = "http://%s/%s/playlist.plx" % ( host+"/wiimc" , base64.b64encode( item.serialize() ).replace("/","%2F") ) respuesta += "type=playlist\n" respuesta += "name=%s\n" % item.title if item.thumbnail != "": respuesta += "thumb=%s\n" % item.thumbnail respuesta += "URL=%s\n" % url respuesta += "\n" logger.info(" Nivel intermedio "+url) else: respuesta += "type=video\n" respuesta += "name=%s\n" % item.title respuesta += "URL=%s\n" % item.url respuesta += "\n" logger.info(" Video "+item.url) return respuesta
def run(): logger.info("pelisalacarta.platformcode.launcher run") # Extract parameters from sys.argv params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password, hasContentDetails, contentTitle, contentThumbnail, contentPlot = extract_parameters() logger.info("pelisalacarta.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, hasContentDetails=%s contentTitle=%s contentThumbnail=%s contentPlot=%s" % (fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password,hasContentDetails, contentTitle, contentThumbnail, contentPlot)) if config.get_setting('filter_servers') == 'true': server_white_list, server_black_list = set_server_list() try: # Default action: open channel and launch mainlist function if ( action=="selectchannel" ): 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("pelisalacarta.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": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(channel_name) and config.get_setting("adult_pin")!="": import xbmc keyboard = xbmc.Keyboard("","PIN para canales de adultos",True) keyboard.doModal() if (keyboard.isConfirmed()): tecleado = keyboard.getText() 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 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("pelisalacarta.platformcode.launcher regular_channel_path=%s" % regular_channel_path) logger.info("pelisalacarta.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("pelisalacarta.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("pelisalacarta.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("pelisalacarta.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, hasContentDetails=hasContentDetails, contentTitle=contentTitle, contentThumbnail=contentThumbnail, contentPlot=contentPlot) ''' if item.subtitle!="": logger.info("pelisalacarta.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("pelisalacarta.platformcode.launcher No subtitle") ''' from platformcode import xbmctools if action=="play": logger.info("pelisalacarta.platformcode.launcher play") # Si el canal tiene una acción "play" tiene prioridad if hasattr(channel, 'play'): logger.info("pelisalacarta.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, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot) else: import xbmcgui ventana_error = xbmcgui.Dialog() ok = ventana_error.ok ("plugin", "No hay nada para reproducir") else: logger.info("pelisalacarta.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, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot) elif action=="strm_detail" or action=="play_from_library": logger.info("pelisalacarta.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) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist, server_white_list, server_black_list) except: from servers import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist, server_white_list, server_black_list) 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("pelisalacarta.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("pelisalacarta.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("pelisalacarta.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("pelisalacarta.platformcode.launcherError al grabar el archivo "+item.title) errores = errores + 1 pDialog.close() # Actualizacion de la biblioteca itemlist=[] if errores > 0: itemlist.append(Item(title="ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta")) logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios") else: itemlist.append(Item(title="La serie se ha añadido a la 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("pelisalacarta.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("pelisalacarta.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)" if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist, server_white_list, server_black_list) # Si no funciona, lanza el método genérico para detectar vídeos else: logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, executing core method") from servers import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist, server_white_list, server_black_list) 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: %d , 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)
def controller(plugin_name, port, host, path, headers): netplayer_ua = "Mozilla/5.0 (Windows; U; en-US; rv:1.8.1.11; Gecko/20071129; Firefox/2.5.0) Maple 6.0.00067 Navi" respuesta = '<?xml version=\'1.0\' encoding="UTF-8" ?>\n<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n' respuesta += "<channel>\n" respuesta += "<link>%s</link>\n\n" % path if path == "/rss" or path == "/rss/": import channelselector channelslist = channelselector.getmainlist() respuesta += "<title>Menú Principal</title>\n\n" # Parametrizar # Actualización automática de canales, actualiza la lista if config.get_setting("updatechannels") == "true": try: from core import updater actualizado = updater.updatechannel("channelselector") if actualizado: respuesta += "<title>¡Lista de canales actualizada!</title>\n" respuesta += "<image></image>\n" if headers.get("User-Agent") == netplayer_ua: respuesta += "<enclosure url=\"http://" + host + "/rss/\" type=\"text/xml\" />\n" else: respuesta += "<link>http://" + host + "/rss/</link>\n" respuesta += "\n" except: pass for channel in channelslist: respuesta += "<item>\n" respuesta += "<title>" + channel.title + "</title>\n" if headers.get("User-Agent") == netplayer_ua: respuesta += "<description><![CDATA[<img src=\"http://" + plugin_name + ".mimediacenter.info/posters/" + channel.channel + ".png\" />]]></description>\n" else: respuesta += "<image>http://" + plugin_name + ".mimediacenter.info/posters/" + channel.channel + ".png</image>\n" if channel.channel == "trailertools": enlace = "http://" + host + "/rss/" + channel.channel + "/search/none/none/none/none/none/none/none/playlist.rss" if headers.get("User-Agent") == netplayer_ua: respuesta += "<textinput>\n" #respuesta += "<title>%s</title>\n" % entityunescape(channel.title) respuesta += "<link>" + enlace + "</link>\n" respuesta += "</textinput>\n" else: respuesta += "<link>rss_command://search</link>" respuesta += "<search url=\"" + enlace + "%s\" />" else: if headers.get("User-Agent") == netplayer_ua: respuesta += "<enclosure url=\"http://" + host + "/rss/" + channel.channel + "/" + channel.action + "/none/none/none/none/none/none/none/playlist.rss\" type=\"text/xml\" />\n" else: respuesta += "<link>http://" + host + "/rss/" + channel.channel + "/" + channel.action + "/none/none/none/none/none/none/none/playlist.rss</link>\n" respuesta += "</item>\n" respuesta += "\n" elif path.startswith("/rss/channelselector/channeltypes"): import channelselector channelslist = channelselector.getchanneltypes() respuesta += "<title>Tipo de contenido</title>\n\n" # Parametrizar for channel in channelslist: respuesta += "<item>\n" respuesta += "<title>" + channel.title + "</title>\n" if headers.get("User-Agent") == netplayer_ua: respuesta += "<description><![CDATA[<img src=\"http://" + plugin_name + ".mimediacenter.info/wiimc/" + channel.thumbnail + ".png\" />]]></description>\n" respuesta += "<enclosure url=\"http://" + host + "/rss/" + channel.channel + "/" + channel.action + "/" + channel.category + "/none/none/none/none/none/playlist.rss\" type=\"text/xml\" />\n" else: respuesta += "<link>http://" + host + "/rss/" + channel.channel + "/" + channel.action + "/" + channel.category + "/none/none/none/none/none/playlist.rss</link>\n" respuesta += "<image>http://" + plugin_name + ".mimediacenter.info/wiimc/" + channel.thumbnail + ".png</image>\n" respuesta += "</item>\n" respuesta += "\n" elif path.startswith("/rss/channelselector/listchannels"): category = path.split("/")[4] logger.info("##category=" + category) import channelselector channelslist = channelselector.filterchannels(category) respuesta += "<title>Canales</title>\n\n" # Parametrizar for channel in channelslist: if channel.type == "generic" or channel.type == "rss": # or channel.type=="wiimc": respuesta += "<item>\n" respuesta += "<title>" + channel.title.replace( "_generico", "").replace(" (Multiplataforma)", "") + "</title>\n" if headers.get("User-Agent") == netplayer_ua: respuesta += "<description><![CDATA[<img src=\"http://" + plugin_name + ".mimediacenter.info/posters/" + channel.channel + ".png\" />]]></description>\n" respuesta += "<enclosure url=\"http://" + host + "/rss/" + channel.channel + "/mainlist/none/none/none/none/none/none/playlist.rss\" type=\"text/xml\" />\n" else: respuesta += "<link>http://" + host + "/rss/" + channel.channel + "/mainlist/none/none/none/none/none/none/playlist.rss</link>\n" respuesta += "<image>http://" + plugin_name + ".mimediacenter.info/posters/" + channel.channel + ".png</image>\n" respuesta += "</item>\n" respuesta += "\n" else: import rsstools itemlist, channel = rsstools.getitems(path, headers.get("User-Agent")) # Las listas vacías son problemáticas, añade un elemento dummy if len(itemlist) == 0: itemlist.append( Item(title="(No hay elementos)", action=path.split("/")[3])) ## <--- import urllib respuesta += "<title>%s</title>\n" % channel.replace( "_generico", "").replace(" (Multiplataforma)", "") for item in itemlist: respuesta += "<item>\n" if item.server == "": item.server = "none" if item.url == "": item.url = "none" if item.extra == "": item.extra = "none" if item.title == "": item.title = "none" if item.fulltitle == "": item.fulltitle = "none" if item.category == "": item.category = "none" if item.channel == "": item.channel = channel if item.action == "search": url = "http://%s/rss/%s/%s/%s/%s/%s/%s/%s/%s/playlist.rss" % ( host, channel, item.action, urllib.quote_plus( item.url), item.server, urllib.quote_plus( item.title), urllib.quote_plus( item.extra), urllib.quote_plus(item.category), urllib.quote_plus(item.fulltitle)) if headers.get("User-Agent") == netplayer_ua: respuesta += "<textinput>\n" respuesta += "<title>%s</title>\n" % entityunescape( item.title) if item.fulltitle not in ("", "none"): respuesta += "<description>%s</description>\n" % item.fulltitle #if item.thumbnail != "": respuesta += "<image>%s</image>\n" % item.thumbnail respuesta += "<link>" + url + "</link>\n" respuesta += "</textinput>\n" else: respuesta += "<title>%s</title>\n" % entityunescape( item.title) if item.fulltitle not in ("", "none"): respuesta += "<fulltitle>%s</fulltitle>\n" % item.fulltitle if item.thumbnail != "": respuesta += "<image>%s</image>\n" % item.thumbnail respuesta += "<link>rss_command://search</link>\n" respuesta += "<search url=\"" + url + "%s\" />\n" respuesta += "\n" elif item.action == "EXIT": respuesta += "<title>%s</title>\n" % entityunescape(item.title) url = "http://%s/rss/" % host if headers.get("User-Agent") == netplayer_ua: if item.thumbnail != "": respuesta += "<description><![CDATA[<img src=\"%s\" />]]></description>\n" % item.thumbnail respuesta += "<enclosure url=\"%s\" type=\"text/xml\" />\n" % url else: if item.thumbnail != "": respuesta += "<image>%s</image>\n" % item.thumbnail respuesta += "<link>%s</link>\n" % url respuesta += "\n" elif item.folder or item.action == "play" or item.action == "downloadall": logger.info(" Nivel intermedio") item.fulltitle = DepuraTitulo(item.fulltitle, "false", "false") from core.scrapertools import slugify play_name = "%s_%s.dat" % (item.channel, urllib.quote(item.fulltitle)) play_name = slugify(play_name) if item.plot not in ("none", ""): item.plot = item.plot.replace("\n", " ") salva_descripcion(play_name, item.fulltitle, item.plot, item.thumbnail) else: fulltitle, plot, thumbnail = recupera_descripcion( play_name) if fulltitle != "" and item.fulltitle in ("", "none"): item.fulltitle = fulltitle if plot != "" and item.plot == "": item.plot = plot if thumbnail != "" and item.thumbnail == "": item.thumbnail = thumbnail if item.title == "none": item.title = "Ver el video" url = "http://%s/rss/%s/%s/%s/%s/%s/%s/%s/%s/playlist.rss" % ( host, item.channel, item.action, urllib.quote_plus( item.url), item.server, urllib.quote( item.title), urllib.quote_plus( item.extra), urllib.quote_plus(item.category), urllib.quote_plus(item.fulltitle)) respuesta += "<title><![CDATA[%s]]></title>\n" % unicode( item.title, "iso-8859-1", errors="ignore").encode("utf-8") if item.fulltitle not in ("", "none"): respuesta += "<fulltitle><![CDATA[%s]]></fulltitle>\n" % unicode( item.title, "iso-8859-1", errors="ignore").encode("utf-8") if headers.get("User-Agent") == netplayer_ua: if item.plot != "" or item.thumbnail != "": respuesta += "<description><![CDATA[ " if item.thumbnail != "": respuesta += "<img src=\"%s\" />" % item.thumbnail if item.plot != "" or item.thumbnail != "": respuesta += "%s ]]></description>\n" % unicode( item.plot, "iso-8859-1", errors="ignore").encode("utf-8") respuesta += "<enclosure url=\"%s\" type=\"text/xml\"/>\n" % url else: if item.plot != "": respuesta += "<description><![CDATA[ %s ]]></description>\n" % unicode( item.plot, "iso-8859-1", errors="ignore").encode("utf-8") if item.thumbnail != "": respuesta += "<image>%s</image>\n" % item.thumbnail respuesta += "<link>%s</link>\n" % url respuesta += "\n" else: logger.info(" Video") from core.scrapertools import slugify play_name = "%s_%s.dat" % (item.channel, urllib.quote(item.fulltitle)) play_name = slugify(play_name) fulltitle, plot, thumbnail = recupera_descripcion(play_name) if fulltitle != "" and item.fulltitle in ("", "none"): item.fulltitle = fulltitle if plot != "" and item.plot == "": item.plot = plot if thumbnail != "" and item.thumbnail == "": item.thumbnail = thumbnail if fulltitle == "": respuesta += "<title><![CDATA[%s]]></title>\n" % entityunescape( item.title) else: respuesta += "<title><![CDATA[%s]]></title>\n" % unicode( fulltitle, "iso-8859-1", errors="ignore").encode("utf-8") respuesta += "<fulltitle><![CDATA[%s]]></fulltitle>\n" % unicode( item.title, "iso-8859-1", errors="ignore").encode("utf-8") if headers.get("User-Agent") == netplayer_ua: if plot != "" or thumbnail != "": respuesta += "<description><![CDATA[" if thumbnail != "": respuesta += "<img src=\"%s\" />" % thumbnail if plot != "" or thumbnail != "": respuesta += "%s]]></description>\n" % unicode( plot, "iso-8859-1", errors="ignore").encode("utf-8") cad = item.url if cad.find(".flv") != -1: respuesta += "<enclosure url=\"%s\" type=\"video/x-flv\" />\n" % item.url else: respuesta += "<enclosure url=\"%s\" type=\"video/mpeg\" />\n" % item.url else: respuesta += "<description><![CDATA[%s]]></description>\n" % unicode( plot, "iso-8859-1", errors="ignore").encode("utf-8") respuesta += "<enclosure url=\"%s\" type=\"video/x-flv\" />\n" % item.url respuesta += "<image>%s</image>\n" % thumbnail respuesta += "</item>\n\n" respuesta += "</channel>\n" respuesta += "</rss>\n" print "--------------------------------------------" print respuesta print "--------------------------------------------" return respuesta
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("tvalacarta",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", "No hay nada para reproducir") 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="No se han encontrado vídeos", 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="No hay elementos para mostrar", 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="Se ha producido un error", thumbnail=os.path.join( plugintools.get_runtime_path() , "resources" , "images" , "thumb_error.png" )) ] return itemlist
def run(): import sys logger.info("[tvalacarta.py] run") # Verifica si el path de usuario del plugin está creado if not os.path.exists(config.get_data_path()): logger.debug("[tvalacarta.py] Path de usuario no existe, se crea: "+config.get_data_path()) os.mkdir(config.get_data_path()) # Imprime en el log los parámetros de entrada logger.info("[tvalacarta.py] sys.argv=%s" % str(sys.argv)) # Crea el diccionario de parametros params = dict() if len(sys.argv)>=2 and len(sys.argv[2])>0: params = dict(part.split('=') for part in sys.argv[ 2 ][ 1: ].split('&')) logger.info("[tvalacarta.py] params=%s" % str(params)) # Extrae la url de la página if (params.has_key("url")): url = urllib.unquote_plus( params.get("url") ) else: url='' # Extrae la accion if (params.has_key("action")): action = params.get("action") else: action = "selectchannel" # Extrae el server if (params.has_key("server")): server = params.get("server") else: server = "" # Extrae la categoria if (params.has_key("category")): category = urllib.unquote_plus( params.get("category") ) else: if params.has_key("channel"): category = params.get("channel") else: category = "" try: # Accion por defecto - elegir canal if ( action=="selectchannel" ): 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("[pelisalacarta.py] Actualizacion automática desactivada") import channelselector as plugin plugin.listchannels(params, url, category) elif (action=="channeltypes"): import channelselector as plugin plugin.channeltypes(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(params.get("channel")) if actualizado: import xbmcgui advertencia = xbmcgui.Dialog() advertencia.ok("plugin",params.get("channel"),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(), PLUGIN_NAME , 'channels' , params.get("channel")+".py" ) core_channel_path = os.path.join( config.get_runtime_path(), 'core' , params.get("channel")+".py" ) if params.get("channel")=="buscador": import pelisalacarta.buscador as channel elif os.path.exists( regular_channel_path ): exec "import pelisalacarta.channels."+params.get("channel")+" as channel" elif os.path.exists( core_channel_path ): exec "from core import "+params.get("channel")+" as channel" 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 print "generico=" , generico if not generico: exec "channel."+action+"(params, url, category)" else: if params.has_key("title"): title = urllib.unquote_plus( params.get("title") ) else: title = "" if params.has_key("thumbnail"): thumbnail = urllib.unquote_plus( params.get("thumbnail") ) else: thumbnail = "" if params.has_key("plot"): plot = urllib.unquote_plus( params.get("plot") ) else: plot = "" if params.has_key("server"): server = urllib.unquote_plus( params.get("server") ) else: server = "directo" if params.has_key("extradata"): extra = urllib.unquote_plus( params.get("extradata") ) else: extra = "" if params.has_key("subtitle"): subtitle = urllib.unquote_plus( params.get("subtitle") ) else: subtitle = "" from core.item import Item item = Item(channel=params.get("channel"), title=title , url=url, thumbnail=thumbnail , plot=plot , server=server, category=category, extra=extra, subtitle=subtitle) if item.subtitle!="": logger.info("Descargando subtítulos de "+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("Sin subtitulos") from core import xbmctools if action=="play": # Si el canal tiene una acción "play" tiene prioridad try: itemlist = channel.play(item) if len(itemlist)>0: item = itemlist[0] except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) xbmctools.playvideo(params.get("channel"),item.server,item.url,item.category,item.title,item.thumbnail,item.plot,subtitle=item.subtitle) else: if action!="findvideos": exec "itemlist = channel."+action+"(item)" else: # Intenta ejecutar una posible funcion "findvideos" del canal try: exec "itemlist = channel."+action+"(item)" # Si no funciona, lanza el método genérico para detectar vídeos except: itemlist = findvideos(item) xbmctools.renderItems(itemlist, params, url, category) except urllib2.URLError,e: import sys for line in sys.exc_info(): logger.error( "%s" % line ) 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: %d , 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)
def controller(plugin_name,port,host,path,headers): respuesta = '<?xml version=\'1.0\' encoding="UTF-8" ?>\n<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n' respuesta += "<channel>\n" respuesta += "<link>%s</link>\n\n" % path if path == "/rss" or path == "/rss/": import channelselector channelslist = channelselector.getmainlist() respuesta += "<title>Menú Principal</title>\n\n" # Parametrizar # Actualización automática de canales, actualiza la lista if config.get_setting("updatechannels")=="true": try: from core import updater actualizado = updater.updatechannel("channelselector") if actualizado: respuesta += "<title>¡Lista de canales actualizada!</title>\n" respuesta += "<image></image>\n" respuesta += "<link>http://"+host+"/rss/</link>\n" respuesta += "\n" except: pass for channel in channelslist: respuesta += "<item>\n" respuesta += "<title>"+channel.title+"</title>\n" respuesta += "<image>http://"+plugin_name+".mimediacenter.info/posters/"+channel.channel+".png</image>\n" if channel.channel=="trailertools": enlace = "http://"+host+"/rss/"+channel.channel+"/search/none/none/none/none/none/none/none/playlist.rss" respuesta += "<link>rss_command://search</link>" respuesta += "<search url=\""+enlace+"%s\" />" else: respuesta += "<link>http://"+host+"/rss/"+channel.channel+"/"+channel.action+"/none/none/none/none/none/none/none/playlist.rss</link>\n" respuesta += "</item>\n" respuesta += "\n" elif path.startswith("/rss/channelselector/channeltypes"): import channelselector channelslist = channelselector.getchanneltypes() respuesta += "<title>Tipo de contenido</title>\n\n" # Parametrizar for channel in channelslist: respuesta += "<item>\n" respuesta += "<title>"+channel.title+"</title>\n" respuesta += "<link>http://"+host+"/rss/"+channel.channel+"/"+channel.action+"/"+channel.category+"/none/none/none/none/none/playlist.rss</link>\n" respuesta += "<image>http://"+plugin_name+".mimediacenter.info/wiimc/"+channel.thumbnail+".png</image>\n" respuesta += "</item>\n" respuesta += "\n" elif path.startswith("/rss/channelselector/listchannels"): category = path.split("/")[4] logger.info("##category="+category) import channelselector channelslist = channelselector.filterchannels(category) respuesta += "<title>Canales</title>\n\n" # Parametrizar for channel in channelslist: if channel.type=="generic" or channel.type=="rss": # or channel.type=="wiimc": respuesta += "<item>\n" respuesta += "<title>"+channel.title.replace("_generico","").replace(" (Multiplataforma)","")+"</title>\n" respuesta += "<link>http://"+host+"/rss/"+channel.channel+"/mainlist/none/none/none/none/none/none/playlist.rss</link>\n" respuesta += "<image>http://"+plugin_name+".mimediacenter.info/posters/"+channel.channel+".png</image>\n" respuesta += "</item>\n" respuesta += "\n" else: import rsstools itemlist,channel = rsstools.getitems(path) # Las listas vacías son problemáticas, añade un elemento dummy if len(itemlist)==0: itemlist.append( Item(title="(No hay elementos)", action=path.split("/")[3]) ) ## <--- import urllib respuesta += "<title>%s</title>\n" % channel.replace("_generico","").replace(" (Multiplataforma)","") for item in itemlist: respuesta += "<item>\n" if item.server=="": item.server="none" if item.url=="": item.url="none" if item.extra=="": item.extra="none" if item.title=="": item.title="none" if item.fulltitle=="": item.fulltitle="none" if item.category=="": item.category="none" if item.channel=="": item.channel=channel if item.action == "search": url = "http://%s/rss/%s/%s/%s/%s/%s/%s/%s/%s/playlist.rss" % ( host , channel , item.action , urllib.quote_plus(item.url) , item.server, urllib.quote_plus(item.title),urllib.quote_plus(item.extra),urllib.quote_plus(item.category),urllib.quote_plus(item.fulltitle)) respuesta += "<title>%s</title>\n" % entityunescape(item.title) if item.fulltitle not in ("","none"): respuesta += "<fulltitle>%s</fulltitle>\n" % item.fulltitle if item.thumbnail != "": respuesta += "<image>%s</image>\n" % item.thumbnail respuesta += "<link>rss_command://search</link>\n" respuesta += "<search url=\""+url+"%s\" />\n" respuesta += "\n" elif item.action=="EXIT": respuesta += "<title>%s</title>\n" % entityunescape(item.title) if item.thumbnail != "": respuesta += "<image>%s</image>\n" % item.thumbnail url = "http://%s/rss/" % host respuesta += "<link>%s</link>\n" % url respuesta += "\n" elif item.folder or item.action=="play" or item.action=="downloadall": logger.info(" Nivel intermedio") item.fulltitle = DepuraTitulo(item.fulltitle, "false", "false") from core.scrapertools import slugify play_name = "%s_%s.dat" % ( item.channel , urllib.quote(item.fulltitle) ) play_name = slugify(play_name) if item.plot not in ("none",""): item.plot = item.plot.replace("\n"," ") salva_descripcion(play_name, item.fulltitle, item.plot, item.thumbnail) else: fulltitle,plot,thumbnail = recupera_descripcion(play_name) if fulltitle != "" and item.fulltitle in ("","none"): item.fulltitle = fulltitle if plot != "" and item.plot == "": item.plot = plot if thumbnail != "" and item.thumbnail == "": item.thumbnail = thumbnail if item.title=="none": item.title="Ver el video" url = "http://%s/rss/%s/%s/%s/%s/%s/%s/%s/%s/playlist.rss" % ( host , item.channel , item.action , urllib.quote_plus(item.url) , item.server , urllib.quote(item.title),urllib.quote_plus(item.extra),urllib.quote_plus(item.category),urllib.quote_plus(item.fulltitle) ) respuesta += "<title><![CDATA[%s]]></title>\n" % unicode(item.title,"iso-8859-1",errors="ignore").encode("utf-8") if item.fulltitle not in ("","none"): respuesta += "<fulltitle><![CDATA[%s]]></fulltitle>\n" % unicode(item.title,"iso-8859-1",errors="ignore").encode("utf-8") if item.plot != "": respuesta += "<description><![CDATA[ %s ]]></description>\n" % unicode(item.plot,"iso-8859-1",errors="ignore").encode("utf-8") if item.thumbnail != "": respuesta += "<image>%s</image>\n" % item.thumbnail respuesta += "<link>%s</link>\n" % url respuesta += "\n" else: logger.info(" Video") from core.scrapertools import slugify play_name = "%s_%s.dat" % ( item.channel , urllib.quote(item.fulltitle) ) play_name = slugify(play_name) fulltitle,plot,thumbnail = recupera_descripcion(play_name) if fulltitle != "" and item.fulltitle in ("","none"): item.fulltitle = fulltitle if plot != "" and item.plot == "": item.plot = plot if thumbnail != "" and item.thumbnail == "": item.thumbnail = thumbnail #respuesta += "<title><![CDATA[%s]]></title>\n" % entityunescape(item.title) respuesta += "<title><![CDATA[%s]]></title>\n" % unicode(fulltitle,"iso-8859-1",errors="ignore").encode("utf-8") respuesta += "<fulltitle><![CDATA[%s]]></fulltitle>\n" % unicode(item.title,"iso-8859-1",errors="ignore").encode("utf-8") respuesta += "<description><![CDATA[%s]]></description>\n" % unicode(plot,"iso-8859-1",errors="ignore").encode("utf-8") respuesta += "<enclosure url=\"%s\" type=\"video/x-flv\" />\n" % item.url respuesta += "<image>%s</image>\n" % thumbnail respuesta += "</item>\n\n" respuesta += "</channel>\n" respuesta += "</rss>\n" print "--------------------------------------------" print respuesta print "--------------------------------------------" return respuesta
def getitems(item): logger.info("getitems") itemlist = [] # Extrae los parámetros channel = item.channel accion = item.action url = item.url if url!="none": if not "filenium" in url: url = urllib.unquote_plus(url) server = item.server title = item.title extra = item.extra category = item.category fulltitle = item.fulltitle try: if accion=="mainlist" and config.get_setting("updatechannels")=="true": try: logger.info("Verificando actualización del canal") from core import updater actualizado = updater.updatechannel(channel) if actualizado: itemlist.append( Item(title="¡Canal descargado y actualizado!") ) except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) # El item que invocó es importante para obtener el siguiente senderitem = Item( title=title , channel=channel, action=accion, url=url , server=server, extra=extra, category=category, fulltitle=fulltitle ) if "|" in url: partes = urllib.unquote_plus(senderitem.url).split("|") refered_item = Item(title=partes[0],url=partes[2],thumbnail="",server=partes[1],plot="",extra=partes[3]) logger.info( "refered_item title="+refered_item.title+", url="+refered_item.url+", server="+refered_item.server+", extra="+refered_item.extra) else: refered_item = Item() # Importa el canal y ejecuta la función try: exec "from pelisalacarta.channels import "+channel+" as channelmodule" except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) try: exec "from pelisalacarta import "+channel+" as channelmodule" except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) try: exec "from core import "+channel+" as channelmodule" except: pass # play - es el menú de reproducción de un vídeo if accion=="play": logger.info("ACCION PLAY") if hasattr(channelmodule, 'play'): logger.info("[launcher.py] executing channel 'play' method") logger.info(channelmodule.__file__) itemlist = channelmodule.play(senderitem) senderitem = itemlist[0] senderitem.folder=False else: logger.info("[launcher.py] no channel 'play' method, executing core method") itemlist = menu_video(senderitem) # play_video - genera una playlist con una sola entrada para que wiimc la reproduzca elif accion=="play_video": logger.info("ACCION PLAY_VIDEO") logger.info("url="+senderitem.url) senderitem.folder=False itemlist.append( senderitem ) # search - es el buscador elif channel=="buscador" and accion=="mainlist": logger.info("ACCION SEARCH (buscador)") texto = requestpath.split("plx")[1] exec "itemlist = buscador.do_search_results(texto)" elif accion=="search": logger.info("ACCION SEARCH") texto = requestpath.split("plx")[1] exec "itemlist = channelmodule."+accion+"(senderitem,texto)" # findvideos - debe encontrar videos reproducibles elif accion=="findvideos": logger.info("ACCION FINDVIDEOS") try: exec "itemlist = channelmodule."+accion+"(senderitem)" except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) itemlist = findvideos(senderitem,channel) elif accion=="descargar": itemlist = download_item(senderitem,refered_item) elif accion=="download_all": itemlist = download_all(senderitem,refered_item) elif accion=="add_to_favorites": itemlist = add_to_favorites(senderitem,refered_item) elif accion=="remove_from_favorites": itemlist = remove_from_favorites(senderitem,refered_item) elif accion=="add_to_downloads": itemlist = add_to_downloads(senderitem,refered_item) elif accion=="remove_from_downloads": itemlist = remove_from_downloads(senderitem,refered_item) elif accion=="remove_from_error_downloads": itemlist = remove_from_error_downloads(senderitem,refered_item) elif accion=="add_again_to_downloads": itemlist = add_again_to_downloads(senderitem,refered_item) elif accion=="send_to_jdownloader": itemlist = send_to_jdownloader(senderitem,refered_item) elif accion=="search_trailer": itemlist = search_trailer(senderitem,refered_item) elif accion=="add_serie_to_wiideoteca": itemlist = wiideoteca.AgregarSerie(senderitem) elif accion=="UltimoVisto": itemlist = wiideoteca.UltimoVisto(senderitem) else: if senderitem.url=="none": senderitem.url="" exec "itemlist.extend( channelmodule."+accion+"(senderitem) )" ''' # Lo almacena en cache fichero = open( cached_file ,"wb") cerealizer.dump(itemlist,fichero) fichero.close() ''' logger.info("Items devueltos") for item in itemlist: logger.info( " " + item.title + " | " + item.url + " | " + item.action) except: 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) return itemlist,channel
def controller(plugin_name, port, host, path, headers): respuesta = "" respuesta += "version=7\n" respuesta += "logo=http://tvalacarta.mimediacenter.info/icon.png\n" respuesta += "title=" + plugin_name + " " + VERSIONTAG + " (WiiMC)\n" respuesta += "\n" if path == "/wiimc/" or path == "/wiimc": import channelselector channelslist = channelselector.getmainlist() # Actualización automática de canales, actualiza la lista if config.get_setting("updatechannels") == "true": logger.info("Verificando actualización del channelselector") try: from core import updater actualizado = updater.updatechannel("channelselector") if actualizado: respuesta += "type=playlist\n" respuesta += "name=¡Lista de canales actualizada!\n" respuesta += "thumb=\n" respuesta += "URL=http://" + host + "/wiimc/\n" respuesta += "\n" except: import sys for line in sys.exc_info(): logger.error("%s" % line) for channel in channelslist: # Quita el canal de ayuda y el de configuración, no sirven en WiiMC if channel.channel != "configuracion" and channel.channel != "ayuda": if channel.channel != "buscador": respuesta += "type=playlist\n" else: respuesta += "type=search\n" respuesta += "name=" + channel.title + "\n" respuesta += "thumb=http://" + plugin_name + ".mimediacenter.info/wiimc/" + channel.channel + ".png\n" respuesta += "URL=http://" + host + "/wiimc/" + base64.b64encode( channel.serialize()).replace("/", "%2F") + "/playlist.plx\n" respuesta += "\n" else: item = extract_item_from_url(path) if item.channel == "channelselector" and item.action == "channeltypes": import channelselector channelslist = channelselector.getchanneltypes() for channel in channelslist: respuesta += "type=playlist\n" respuesta += "name=" + channel.title + "\n" respuesta += "thumb=http://" + plugin_name + ".mimediacenter.info/wiimc/" + channel.channel + ".png\n" respuesta += "URL=http://" + host + "/wiimc/" + base64.b64encode( channel.serialize()).replace("/", "%2F") + "/playlist.plx\n" respuesta += "\n" elif item.channel == "channelselector" and item.action == "listchannels": import channelselector channelslist = channelselector.filterchannels(item.category) for channel in channelslist: if (channel.type == "generic" or channel.type == "wiimc") and channel.extra != "rtmp": channel.action = "mainlist" respuesta += "type=playlist\n" respuesta += "name=" + channel.title + "\n" respuesta += "thumb=http://" + plugin_name + ".mimediacenter.info/wiimc/" + channel.channel + ".png\n" respuesta += "URL=http://" + host + "/wiimc/" + base64.b64encode( channel.serialize()).replace("/", "%2F") + "/playlist.plx\n" respuesta += "\n" else: itemlist, channel = getitems(item) # Las listas vacías son problemáticas, añade un elemento dummy if len(itemlist) == 0: itemlist.append(Item(title="(No hay elementos)")) for item in itemlist: if item.action == "search": if item.server == "": item.server = "none" if item.url == "": item.url = "none" url = "http://%s/%s/playlist.plx" % ( host + "/wiimc", base64.b64encode( item.serialize()).replace("/", "%2F")) respuesta += "type=search\n" respuesta += "name=%s\n" % item.title if item.thumbnail != "": respuesta += "thumb=%s\n" % item.thumbnail respuesta += "URL=%s\n" % url respuesta += "\n" logger.info(" Buscador " + url) elif item.folder or item.action == "play" or item.action == "downloadall": if item.server == "": item.server = "none" if item.url == "": item.url = "none" if item.title == "": item.title = "Ver el video-" url = "http://%s/%s/playlist.plx" % ( host + "/wiimc", base64.b64encode( item.serialize()).replace("/", "%2F")) respuesta += "type=playlist\n" respuesta += "name=%s\n" % item.title if item.thumbnail != "": respuesta += "thumb=%s\n" % item.thumbnail respuesta += "URL=%s\n" % url respuesta += "\n" logger.info(" Nivel intermedio " + url) else: respuesta += "type=video\n" respuesta += "name=%s\n" % item.title respuesta += "URL=%s\n" % item.url respuesta += "\n" logger.info(" Video " + item.url) return respuesta
def run(): logger.info("[launcher.py] 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( "[launcher.py] 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() # Actualizar version elif (action == "update"): try: from core import updater updater.update(params) except ImportError: logger.info( "[launcher.py] 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") # 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(), PLUGIN_NAME, 'channels', channel_name + ".py") core_channel_path = os.path.join(config.get_runtime_path(), 'core', channel_name + ".py") logger.info("[launcher.py] regular_channel_path=%s" % regular_channel_path) logger.info("[launcher.py] core_channel_path=%s" % core_channel_path) if channel_name == "buscador": import pelisalacarta.buscador as channel elif os.path.exists(regular_channel_path): exec "import mywebtv.channels." + channel_name + " as channel" elif os.path.exists(regular_channel_path): exec "import tvalacarta.channels." + channel_name + " as channel" elif os.path.exists(core_channel_path): exec "from core import " + channel_name + " as channel" logger.info("[launcher.py] 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("[launcher.py] xbmc native channel") if (action == "strm"): from platformcode.xbmc import xbmctools xbmctools.playstrm(params, url, category) else: exec "channel." + action + "(params, url, category)" else: logger.info("[launcher.py] 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("[launcher.py] 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("[launcher.py] No subtitle") ''' from platformcode.xbmc import xbmctools if action == "play": logger.info("[launcher.py] play") # Si el canal tiene una acción "play" tiene prioridad if hasattr(channel, 'play'): logger.info( "[launcher.py] 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", "No hay nada para reproducir") else: logger.info( "[launcher.py] 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("[launcher.py] 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.xbmc 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("[launcher.py] add_pelicula_to_library") from platformcode.xbmc 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("[launcher.py] add_serie_to_library, show=" + item.show) from platformcode.xbmc 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('mywebtv', '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) 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 último (el que dice "Añadir esta serie...") if i < len(itemlist): 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( "[launcher.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= "ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta" )) logger.info("[launcher.py] No se pudo añadir " + str(errores) + " episodios") else: itemlist.append( Item(title="La serie se ha añadido a la 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_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) f.write(item.show + "," + item.url + "," + item.channel + "\n") f.close() elif action == "download_all_episodes": download_all_episodes(item, channel) elif action == "search": logger.info("[launcher.py] 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("[launcher.py] 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( "[launcher.py] no channel 'findvideos' method, executing core method" ) from servers import servertools itemlist = servertools.find_video_items(item) from core 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: %d , 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)
def getitems(requestpath): logger.info("getitems") itemlist = [] # La ruta empleada en la petición ruta = requestpath.split("?")[0] logger.info("ruta=" + ruta) # Los parámetros son las partes de la ruta separadas por "/" rutas = ruta.split("/") cadena = " " # Las imprime en el log for linea in rutas: cadena = cadena + linea + " | " logger.info(cadena) # Extrae los parámetros channel = rutas[2] accion = rutas[3] url = rutas[4] if url != "none": url = urllib.unquote_plus(url) server = rutas[5].lower() title = urllib.unquote_plus(rutas[6]) extra = urllib.unquote_plus(rutas[7]) category = urllib.unquote_plus(rutas[8]) fulltitle = urllib.unquote_plus(rutas[9]) logger.info("channel=" + channel + ", accion=" + accion + ", url=" + url + ", server=" + server + ", title=" + title + ", extra=" + extra + ", category=" + category + " fulltitle=" + fulltitle) print "channel=" + channel + ", accion=" + accion + ", url=" + url + ", server=" + server + ", title=" + title + ", extra=" + extra + ", category=" + category if accion == "mainlist" and config.get_setting("updatechannels") == "true": logger.info("Verificando actualización del canal") from core import updater actualizado = updater.updatechannel(channel) if actualizado: itemlist.append(Item(title="¡Canal descargado y actualizado!")) # Obtiene un nombre válido para la cache hashed_url = binascii.hexlify(md5.new(requestpath).digest()) cached_file = os.path.join(config.get_data_path(), "tmp", "cache", hashed_url) logger.info("cached_file=" + cached_file) # Si el fichero está en cache if channel not in ("trailertools", "buscador", "configuracion", "pyload", "wiidoteca") and os.path.exists(cached_file): # <-- logger.info("Reading from cache") fichero = open(cached_file, "rb") itemlist = cerealizer.load(fichero) fichero.close() else: logger.info("Not cached") ### ESTUDIAR #if accion not in ("play","findvideos","detail"): titulo = "" ### # El item que invocó es importante para obtener el siguiente senderitem = Item(title=title, channel=channel, action=accion, url=url, server=server, extra=extra, category=category, fulltitle=fulltitle) if "|" in url: ## <-- unquote despues de split para no interferir cuando | aparece en algun campo partes = senderitem.url.split("|") decpartes = [] for parte in partes: decpartes.append(urllib.unquote_plus(parte)) partes = decpartes ## <-- refered_item = Item(title=partes[0], url=partes[2], thumbnail=partes[5], server=partes[1], plot=partes[6], extra=partes[3], fulltitle=partes[4]) logger.info("refered_item title=" + refered_item.title + ", url=" + refered_item.url + ", server=" + refered_item.server + ", extra=" + refered_item.extra) else: refered_item = Item() # Importa el canal y ejecuta la función if channel in ("configuracion", "trailertools", "buscador"): exec "import " + channel else: try: exec "from tvalacarta.channels import " + channel except: exec "from core import " + channel # play - es el menú de reproducción de un vídeo if accion == "play": logger.info("ACCION PLAY") print "ACCION PLAY" try: exec "itemlist = " + channel + ".play(senderitem)" print "itemlist = " + channel + ".play(senderitem)" senderitem = itemlist[0] senderitem.folder = False except: import sys for line in sys.exc_info(): logger.error("%s" % line) itemlist = menu_video(senderitem) # play_video - genera una playlist con una sola entrada para que wiimc la reproduzca elif accion == "play_video": logger.info("ACCION PLAY_VIDEO") senderitem.folder = False itemlist.append(senderitem) # search - es el buscador elif accion == "search": logger.info("ACCION SEARCH") texto = requestpath.split(".rss")[1] exec "itemlist = " + channel + "." + accion + "(senderitem,texto)" # findvideos - debe encontrar videos reproducibles elif accion == "findvideos": logger.info("ACCION FINDVIDEOS") try: exec "itemlist = " + channel + "." + accion + "(senderitem)" except: import sys for line in sys.exc_info(): logger.error("%s" % line) itemlist = findvideos(senderitem, channel) elif accion == "descargar": itemlist = download_item(senderitem, refered_item) elif accion == "downloadall": ## <-- itemlist = downloadall(senderitem, refered_item) ## <-- elif accion == "add_to_favorites": itemlist = add_to_favorites(senderitem, refered_item) elif accion == "remove_from_favorites": itemlist = remove_from_favorites(senderitem, refered_item) elif accion == "add_to_downloads": itemlist = add_to_downloads(senderitem, refered_item) elif accion == "remove_from_downloads": itemlist = remove_from_downloads(senderitem, refered_item) elif accion == "remove_from_error_downloads": itemlist = remove_from_error_downloads(senderitem, refered_item) elif accion == "add_again_to_downloads": itemlist = add_again_to_downloads(senderitem, refered_item) elif accion == "send_to_jdownloader": itemlist = send_to_jdownloader(senderitem, refered_item) elif accion == "send_to_pyload": itemlist = send_to_pyload(senderitem, refered_item) elif accion == "search_trailer": itemlist = search_trailer(senderitem, refered_item) elif accion == "add_serie_to_wiideoteca": itemlist = wiideoteca.AgregarSerie(senderitem) elif accion == "UltimoVisto": itemlist = wiideoteca.UltimoVisto(senderitem) else: if senderitem.url == "none": senderitem.url = "" exec "itemlist.extend( " + channel + "." + accion + "(senderitem) )" # Lo almacena en cache fichero = open(cached_file, "wb") cerealizer.dump(itemlist, fichero) fichero.close() logger.info("Items devueltos") for item in itemlist: logger.info(" " + item.title + " | " + item.url + " | " + item.action) return itemlist, channel