def channels_list(): oc = ObjectContainer(view_group="PanelStream") """ oc.add(DirectoryObject(key=Callback(FrontPageList, name="Canales (Todos los idiomas)"), title="Canales (Todos los idiomas)", thumb="http://pelisalacarta.mimediacenter.info/squares/channelselector.png")) oc.add(DirectoryObject(key=Callback(FrontPageList, name="Buscador"), title="Buscador", thumb="http://pelisalacarta.mimediacenter.info/squares/buscador.png")) oc.add(DirectoryObject(key=Callback(ThemeList, name="Favoritos"), title="Favoritos")) oc.add(DirectoryObject(key=Callback(ThemeList, name="Descargas"), title="Descargas")) oc.add(DirectoryObject(key=Callback(ThemeList, name="Configuración"), title="Configuración")) oc.add(DirectoryObject(key=Callback(TagsList, name="Ayuda"), title="Ayuda t")) """ itemlist = channelselector.filterchannels(category="all") for item in itemlist: Log.Info("item=" + repr(item)) if item.type == "generic" and item.channel not in ["tengourl", "goear"]: oc.add( DirectoryObject( key=Callback(canal, channel_name=item.channel, action="mainlist"), title=item.title, thumb=item.thumbnail, ) ) return oc
def mainlist(item): logger.info("tvalacarta.channels.configuracion mainlist") itemlist = [] itemlist.append(Item(channel=CHANNELNAME, title="Preferencias", action="settings", folder=False)) itemlist.append(Item(channel=CHANNELNAME, title="", action="", folder=False)) itemlist.append(Item(channel=CHANNELNAME, title="Ajustes especiales", action="", folder=False)) itemlist.append(Item(channel="novedades", title=" Ajustes de la sección 'Novedades'", action="menu_opciones", folder=True)) itemlist.append(Item(channel="buscador", title=" Ajustes del buscador global", action="opciones", folder=True)) if config.is_xbmc(): itemlist.append(Item(channel=item.channel, action="updatebiblio", title=" Buscar nuevos episodios y actualizar biblioteca", folder=False)) itemlist.append(Item(channel=CHANNELNAME, title=" Comprobar actualizaciones", action="check_for_updates", folder=False)) itemlist.append(Item(channel=CHANNELNAME, title=" Añadir o Actualizar canal/conector desde una URL", action="menu_addchannels")) itemlist.append(Item(channel=item.channel, action="", title="", folder=False)) itemlist.append(Item(channel=CHANNELNAME, title="Ajustes por canales", action="", folder=False)) import channelselector from core import channeltools channel_list = channelselector.filterchannels("all") for channel in channel_list: jsonchannel = channeltools.get_channel_json(channel.channel) if jsonchannel.get("settings"): setting = jsonchannel["settings"] if type(setting) == list: if len([s for s in setting if "id" in s and not "include_in_" in s["id"]]): itemlist.append(Item(channel=CHANNELNAME, title=" Configuración del canal '%s'" % channel.title, action="channel_config", config=channel.channel, folder=False)) return itemlist
def channel_status(item, dict_values): try: for v in dict_values: if v == "all_channels": import channelselector from core import channeltools logger.info("Todos los canales | Estado seleccionado: %s" % str(dict_values[v]).lower()) if str(dict_values[v]) != "0": channel_list = channelselector.filterchannels("allchannelstatus") excluded_channels = ['tengourl', 'buscador', 'libreria', 'configuracion', 'novedades', 'personal', 'ayuda', 'descargas'] for channel in channel_list: if channel.channel not in excluded_channels: channel_parameters = channeltools.get_channel_parameters(channel.channel) new_status_all_default = None new_status_all = None new_status_all_default = channel_parameters["active"] # Opcion Activar todos if str(dict_values[v]) == "1": new_status_all = "true" # Opcion Desactivar todos if str(dict_values[v]) == "2": new_status_all = "false" # Opcion Recuperar estado por defecto if str(dict_values[v]) == "3": # Si tiene "enabled" en el json es porque el estado no es el del xml if config.get_setting("enabled", channel.channel): new_status_all = new_status_all_default # Si el canal no tiene "enabled" en el json no se guarda, se pasa al siguiente else: continue # Se guarda el estado del canal if new_status_all is not None: config.set_setting("enabled", new_status_all, channel.channel) break else: continue else: logger.info("Canal: %s | Estado: %s" % (v, str(dict_values[v]).lower())) config.set_setting("enabled", str(dict_values[v]).lower(), v) platformtools.itemlist_update(Item(channel=CHANNELNAME, action="mainlist")) except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_notification("Error", "Se ha producido un error al guardar")
def channels_list(): oc = ObjectContainer(view_group="PanelStream") itemlist = channelselector.filterchannels(category="all") for item in itemlist: Log.Info("item="+repr(item)) if item.channel not in ['tengourl']: oc.add(DirectoryObject(key=Callback(canal, channel_name=item.channel, action="mainlist", caller_item_serialized = item.tourl()), title=item.title, thumb=item.thumbnail)) return oc
def mainlist(item): logger.info() itemlist = list() itemlist.append(Item(channel=CHANNELNAME, title="Preferencias", action="settings", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append(Item(channel=CHANNELNAME, title="", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append(Item(channel=CHANNELNAME, title="Ajustes especiales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append(Item(channel="novedades", title=" Ajustes de la sección 'Novedades'", action="menu_opciones", folder=True, thumbnail=get_thumbnail_path("thumb_novedades.png"))) itemlist.append(Item(channel="buscador", title=" Ajustes del buscador global", action="opciones", folder=True, thumbnail=get_thumbnail_path("thumb_buscar.png"))) if config.get_library_support(): itemlist.append(Item(channel="biblioteca", title=" Ajustes de la biblioteca", action="channel_config", folder=True, thumbnail=get_thumbnail_path("thumb_biblioteca.png"))) itemlist.append(Item(channel="biblioteca", action="update_biblio", folder=False, thumbnail=get_thumbnail_path("thumb_biblioteca.png"), title=" Buscar nuevos episodios y actualizar biblioteca")) itemlist.append(Item(channel=CHANNELNAME, title=" Comprobar actualizaciones", action="check_for_updates", folder=False, thumbnail=get_thumbnail_path("Crystal_Clear_action_info.png"))) itemlist.append(Item(channel=CHANNELNAME, title=" Añadir o Actualizar canal/conector desde una URL", action="menu_addchannels")) itemlist.append(Item(channel=item.channel, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append(Item(channel=CHANNELNAME, title="Ajustes por canales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) import channelselector from core import channeltools channel_list = channelselector.filterchannels("all") for channel in channel_list: jsonchannel = channeltools.get_channel_json(channel.channel) if jsonchannel.get("settings"): setting = jsonchannel["settings"] if type(setting) == list: if len([s for s in setting if "id" in s and "include_in_" not in s["id"]]): itemlist.append(Item(channel=CHANNELNAME, title=" Configuración del canal '%s'" % channel.title, action="channel_config", config=channel.channel, folder=False, thumbnail=channel.thumbnail)) return itemlist
def runchannel(sender,channel,action="mainlist",category=""): Log("[__init__.py] runchannel") ''' from PMS import Prefs valor = Prefs.Get("megavideouser") Log("login="******"megavideouser") Log("login="******"get_data_path="+config.get_data_path()) ''' Log("channel="+channel) Log("action="+action) dir = MediaContainer(viewGroup="InfoList") # Importa el canal y obtiene los items try: exec "from pelisalacarta.channels import "+channel except: try: exec "from core import "+channel except: exec "import "+channel if channel!="channelselector": exec "itemlist = "+channel+"."+action+"(None)" elif action=="channeltypes": itemlist = channelselector.getchanneltypes() elif action=="listchannels": itemlist = channelselector.filterchannels(category) Log("itemlist %d items" % len(itemlist)) for item in itemlist: Log("item="+item.tostring()+" channel=["+item.channel+"]") category="" if "F" in item.category: category = category + "Películas, " if "S" in item.category: category = category + "Series, " if "D" in item.category: category = category + "Documentales, " if "A" in item.category: category = category + "Anime, " if "M" in item.category: category = category + "Música, " if "G" in item.category: category = category + "Servidores, " if "NEW" in item.category: category = "Los nuevos, " if category!="": category = category[:-2] if not item.thumbnail.startswith("http://"): item.thumbnail = 'http://pelisalacarta.mimediacenter.info/posters/'+item.channel+'.png' #Log("category=%s" % category) #thumbnail = 'images/posters/'+item.channel+'.png' #Log("thumbnail=%s" % thumbnail) # Opciones de menú if item.channel=="channelselector": dir.Append( Function( DirectoryItem( runchannel, title = item.title, subtitle = "", thumb = item.thumbnail, art=R(ART) ) , channel=item.channel , action = item.action , category = item.category )) # Los canales else: if item.type=="generic": dir.Append( Function( DirectoryItem( actionexecute, title = item.title, subtitle = category, thumb = item.thumbnail ) , itemtext = item.serialize() ) ) return dir
def run(): logger.info() # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info(item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector # Check for updates only on first screen if config.get_setting("check_for_plugin_updates") == "true": logger.info("Check for plugin updates enabled") from core import updater try: config.set_setting("plugin_updates_available","0") version = updater.checkforupdates() itemlist = channelselector.getmainlist() if version: config.set_setting("plugin_updates_available","1") platformtools.dialog_ok("Versione "+version+" disponible", "E' possibile fare il download della nuova versione\n" "selezionare la relativa voce nel menu principale") itemlist = channelselector.getmainlist() itemlist.insert(0, Item(title="Download versione "+version, version=version, channel="updater", action="update", thumbnail=os.path.join(config.get_runtime_path() , "resources" , "images", "service_update.png"))) except: import traceback logger.info(traceback.format_exc()) platformtools.dialog_ok("Impossibile connettersi", "Non è stato possibile verificare", "aggiornamenti") logger.info("Fallo al verificar la actualización") config.set_setting("plugin_updates_available","0") itemlist = channelselector.getmainlist() else: logger.info("Check for plugin updates disabled") config.set_setting("plugin_updates_available","0") itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "update": from core import updater updater.update(item) config.set_setting("plugin_updates_available","0") if config.get_system_platform() != "xbox": import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_pin") != "": tecleado = platformtools.dialog_input("", "PIN per canali per adulti", True) if tecleado is not None: if tecleado == config.get_setting("adult_pin"): can_open_channel = True # All the other cases can open the channel else: can_open_channel = True if not can_open_channel: return # Actualiza el canal individual if (item.action == "mainlist" and item.channel != "channelselector" and config.get_setting("check_for_channel_updates") == "true"): from core import updater updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info("channel_file=%s" % channel_file) channel = None if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels." + item.channel + " as channel" logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("plugin", "Niente da riprodurre") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist) if config.get_setting("max_links", "biblioteca") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import descargas item.action = item.extra del item.extra descargas.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) tecleado = platformtools.dialog_input('') if tecleado is not None: # TODO revisar 'personal.py' porque no tiene función search y daría problemas # DrZ3r0 itemlist = channel.search(item, tecleado.replace(" ", "+")) else: return platformtools.render_items(itemlist, item) # For all other actions else: logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("plugin", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
def run(item=None): logger.info() if not item: # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info(item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector # # Check for updates only on first screen # if config.get_setting("check_for_plugin_updates") == True: # logger.info("Check for plugin updates enabled") # from core import updater # # try: # config.set_setting("plugin_updates_available", 0) # new_published_version_tag, number_of_updates = updater.get_available_updates() # # config.set_setting("plugin_updates_available", number_of_updates) # itemlist = channelselector.getmainlist() # # if new_published_version_tag != "": # platformtools.dialog_notification(new_published_version_tag + " disponible", # "Ya puedes descargar la nueva versión del plugin\n" # "desde el listado principal") # # itemlist = channelselector.getmainlist() # itemlist.insert(0, Item(title="Descargar version " + new_published_version_tag, # version=new_published_version_tag, channel="updater", # action="update", # thumbnail=channelselector.get_thumb("update.png"))) # except: # import traceback # logger.error(traceback.format_exc()) # platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar", # "si hay actualizaciones") # logger.error("Fallo al verificar la actualización") # config.set_setting("plugin_updates_available", 0) # itemlist = channelselector.getmainlist() # # else: # logger.info("Check for plugin updates disabled") # config.set_setting("plugin_updates_available", 0) # itemlist = channelselector.getmainlist() itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # # Action for updating plugin # elif item.action == "update": # # from core import updater # updater.update(item) # config.set_setting("plugin_updates_available", 0) # # import xbmc # xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting( "adult_request_password"): tecleado = platformtools.dialog_input( "", "Contraseña para canales de adultos", True) if tecleado is None or tecleado != config.get_setting( "adult_password"): return # # Actualiza el canal individual # if (item.action == "mainlist" and item.channel != "channelselector" and # config.get_setting("check_for_channel_updates") == True): # from core import updater # updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info("channel_file=%s" % channel_file) channel = None if os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels." + item.channel + " as channel" logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("alfa", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) itemlist = servertools.filter_servers(itemlist) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) last_search = "" last_search_active = config.get_setting( "last_search", "search") if last_search_active: try: current_saved_searches_list = list( config.get_setting("saved_searches_list", "search")) last_search = current_saved_searches_list[0] except: pass tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if last_search_active and not tecleado.startswith("http"): from channels import search search.save_search(tecleado) itemlist = channel.search(item, tecleado) else: return platformtools.render_items(itemlist, item) # For all other actions else: logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.error("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string( 30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("alfa", texto) # Grab server response errors elif hasattr(e, 'code'): logger.error("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok( "alfa", config.get_localized_string(30051) % e.code)
def conf_tools(item): logger.info() # Activar o desactivar canales if item.extra == "channels_onoff": import channelselector from core import channeltools channel_list = channelselector.filterchannels("allchannelstatus") channel_language = config.get_setting("channel_language") if channel_language == "": channel_language = "all" excluded_channels = ['tengourl', 'buscador', 'libreria', 'configuracion', 'novedades', 'personal', 'ayuda', 'descargas'] list_controls = [] try: list_controls.append({'id': "all_channels", 'type': "list", 'label': "Todos los canales", 'default': 0, 'enabled': True, 'visible': True, 'lvalues': ['', 'Activar todos', 'Desactivar todos', 'Establecer estado por defecto']}) for channel in channel_list: # Si el canal esta en la lista de exclusiones lo saltamos if channel.channel not in excluded_channels: # Se cargan los ajustes del archivo json del canal jsonchannel = channeltools.get_channel_json(channel.channel) if jsonchannel.get("settings") or jsonchannel.get("active"): channel_parameters = channeltools.get_channel_parameters(channel.channel) # No incluir si es un canal para adultos, y el modo adulto está desactivado if (channel_parameters["adult"] == "true" and config.get_setting("adult_mode") == "0"): continue # No incluir si el canal es en un idioma filtrado if (channel_language != "all" and channel_parameters["language"] != channel_language): continue status = None xml_status = channel_parameters["active"].replace("t", "T").replace("f", "F") xml_status = eval(xml_status) if config.get_setting("enabled", channel.channel): status = config.get_setting("enabled", channel.channel) status = status.replace("t", "T").replace("f", "F") status = eval(status) # logger.info(channel.channel + " | Status: " + str(status)) else: status = xml_status # logger.info(channel.channel + " | Status (XML): " + str(status)) status_control = "" if not xml_status: status_control = " [COLOR grey](Desactivado por defecto)[/COLOR]" if status is not None: control = {'id': channel.channel, 'type': "bool", 'label': channel_parameters["title"] + status_control, 'default': status, 'enabled': True, 'visible': True} list_controls.append(control) else: logger.info("Algo va mal con el canal " + channel.channel) else: continue return platformtools.show_channel_settings(list_controls=list_controls, caption="Canales", callback="channel_status", custom_button={"visible": False}) except: import traceback logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_notification("Error", "Se ha producido un error con el canal %s" % channel.title) # Comprobacion de archivos channel_data.json elif item.extra == "lib_check_datajson": itemlist = [] import channelselector from core import channeltools channel_list = channelselector.filterchannels("allchannelstatus") # Tener una lista de exclusion no tiene mucho sentido por que se comprueba si # el xml tiene "settings", pero por si acaso se deja excluded_channels = ['tengourl', 'configuracion', 'personal', 'ayuda'] try: import os from core import jsontools for channel in channel_list: needsfix = None list_status = None list_controls = None default_settings = None channeljson_exists = None # Se convierte el "channel.channel" del canal biblioteca para que no de error if channel.channel == "libreria": channel.channel = "biblioteca" # Se comprueba si el canal esta en la lista de exclusiones if channel.channel not in excluded_channels: # Se comprueba que tenga "settings", sino se salta jsonchannel = channeltools.get_channel_json(channel.channel) if not jsonchannel.get("settings"): itemlist.append(Item(channel=CHANNELNAME, title=channel.title + " - No tiene ajustes por defecto", action="", folder=False, thumbnail=channel.thumbnail)) continue # logger.info(channel.channel + " SALTADO!") # Se cargan los ajustes del archivo json del canal file_settings = os.path.join(config.get_data_path(), "settings_channels", channel.channel + "_data.json") dict_settings = {} dict_file = {} if filetools.exists(file_settings): # logger.info(channel.channel + " Tiene archivo _data.json") channeljson_exists = "true" # Obtenemos configuracion guardada de ../settings/channel_data.json try: dict_file = jsontools.load_json(open(file_settings, "rb").read()) if isinstance(dict_file, dict) and 'settings' in dict_file: dict_settings = dict_file['settings'] except EnvironmentError: logger.info("ERROR al leer el archivo: %s" % file_settings) else: # logger.info(channel.channel + " No tiene archivo _data.json") channeljson_exists = "false" if channeljson_exists == "true": try: datajson_size = filetools.getsize(file_settings) except: import traceback logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc()) else: datajson_size = None # Si el _data.json esta vacio o no existe... if (len(dict_settings) and datajson_size) == 0 or channeljson_exists == "false": # Obtenemos controles del archivo ../channels/channel.xml needsfix = "true" try: # Se cargan los ajustes por defecto list_controls, default_settings = channeltools.get_channel_controls_settings(channel.channel) # logger.info(channel.title + " | Default: %s" % default_settings) except: import traceback logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc()) # default_settings = {} # Si _data.json necesita ser reparado o no existe... if needsfix == "true" or channeljson_exists == "false": if default_settings is not None: # Creamos el channel_data.json default_settings.update(dict_settings) dict_settings = default_settings dict_file['settings'] = dict_settings # Creamos el archivo ../settings/channel_data.json json_data = jsontools.dump_json(dict_file) try: open(file_settings, "wb").write(json_data) # logger.info(channel.channel + " - Archivo _data.json GUARDADO!") # El channel_data.json se ha creado/modificado list_status = " - [COLOR red] CORREGIDO!![/COLOR]" except EnvironmentError: logger.info("ERROR al salvar el archivo: %s" % file_settings) else: if default_settings is None: list_status = " - [COLOR red] Imposible cargar los ajustes por defecto![/COLOR]" else: # logger.info(channel.channel + " - NO necesita correccion!") needsfix = "false" # Si se ha establecido el estado del canal se añade a la lista if needsfix is not None: if needsfix == "true": if channeljson_exists == "false": list_status = " - Ajustes creados" list_colour = "red" else: list_status = " - No necesita correccion" list_colour = "green" else: # Si "needsfix" es "false" y "datjson_size" es None habra # ocurrido algun error if datajson_size is None: list_status = " - Ha ocurrido algun error" list_colour = "red" else: list_status = " - No necesita correccion" list_colour = "green" if list_status is not None: itemlist.append(Item(channel=CHANNELNAME, title=channel.title + list_status, action="", folder=False, thumbnail=channel.thumbnail, text_color=list_colour)) else: logger.info("Algo va mal con el canal %s" % channel.channel) # Si el canal esta en la lista de exclusiones lo saltamos else: continue except: import traceback logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_notification("Error", "Se ha producido un error con el canal %s" % channel.title) return itemlist else: platformtools.dialog_notification("pelisalacarta", "Error!") platformtools.itemlist_update(Item(channel=CHANNELNAME, action="submenu_tools"))
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(item=None): logger.info() if not item: # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info(item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("Item without action") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector config.set_setting("plugin_updates_available", 0) itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "update": from core import updater updater.update(item) config.set_setting("plugin_updates_available", 0) if config.get_system_platform() != "xbox": import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting( "adult_pin") != "": tecleado = platformtools.dialog_input( "", "Password for adult channels", True) if tecleado is None or tecleado != config.get_setting( "adult_pin"): return # Update the individual channel if (item.action == "mainlist" and item.channel != "channelselector" and config.get_setting("check_for_channel_updates") == True): from core import updater updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info("channel_file=%s" % channel_file) channel = None if item.channel in [ "personal", "personal2", "personal3", "personal4", "personal5" ]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels." + item.channel + " as channel" logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("dss", "There is nothing to play") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) itemlist = servertools.filter_servers(itemlist) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "biblioteca") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import descargas item.action = item.extra del item.extra descargas.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) last_search = "" last_search_active = config.get_setting( "last_search", "buscador") if last_search_active: try: current_saved_searches_list = list( config.get_setting("saved_searches_list", "buscador")) last_search = current_saved_searches_list[0] except: pass tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if last_search_active and not tecleado.startswith("http"): from channels import buscador buscador.save_search(tecleado) # TODO revisar 'personal.py' porque no tiene función search y daría problemas itemlist = channel.search(item, tecleado) else: return platformtools.render_items(itemlist, item) # For all other actions else: logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.error("Error reason, code: %s | Reason: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string( 30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("dss", texto) # Grab server response errors elif hasattr(e, 'code'): logger.error("Error code HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok( "dss", config.get_localized_string(30051) % e.code)
'Serie TV': 12 }, 'serietvonline': { 'Film': 25, 'Serie TV': 35 }, 'tantifilm': { 'Film': 20, 'Serie TV': 20 }, } servers = [] channels = [] channel_list = channelselector.filterchannels("all") if 'KOD_TST_CH' not in os.environ else [Item(channel=os.environ['KOD_TST_CH'], action="mainlist")] logger.info([c.channel for c in channel_list]) results = [] logger.record = True for chItem in channel_list: ch = chItem.channel if ch not in chBlackList: hasChannelConfig = False mainlist = [] module = None error = None menuItemlist = {} serversFound = {} firstContent = None # to check search logMenu = {}
def menu_channels(item): logger.info() itemlist = list() itemlist.append( Item(channel=CHANNELNAME, title="Activar/desactivar canales", action="conf_tools", folder=False, extra="channels_onoff", thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Ajustes por canales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) # Inicio - Canales configurables import channelselector from core import channeltools channel_list = channelselector.filterchannels("all") for channel in channel_list: channel_parameters = channeltools.get_channel_parameters( channel.channel) if channel_parameters["has_settings"]: itemlist.append( Item(channel=CHANNELNAME, title=" Configuración del canal '%s'" % channel.title, action="channel_config", config=channel.channel, folder=False, thumbnail=channel.thumbnail)) # Fin - Canales configurables itemlist.append( Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Herramientas de canales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_canales.png"))) itemlist.append( Item(channel=CHANNELNAME, title=" Comprobar archivos *_data.json", action="conf_tools", folder=True, extra="lib_check_datajson", thumbnail=get_thumbnail_path("thumb_canales.png"))) return itemlist
def conf_tools(item): logger.info() # Activar o desactivar canales if item.extra == "channels_onoff": import channelselector from core import channeltools channel_list = channelselector.filterchannels("allchannelstatus") excluded_channels = [ 'tengourl', 'buscador', 'biblioteca', 'configuracion', 'novedades', 'personal', 'ayuda', 'descargas' ] list_controls = [] try: list_controls.append({ 'id': "all_channels", 'type': "list", 'label': "Todos los canales", 'default': 0, 'enabled': True, 'visible': True, 'lvalues': [ '', 'Activar todos', 'Desactivar todos', 'Establecer estado por defecto' ] }) for channel in channel_list: # Si el canal esta en la lista de exclusiones lo saltamos if channel.channel not in excluded_channels: channel_parameters = channeltools.get_channel_parameters( channel.channel) status_control = "" status = config.get_setting("enabled", channel.channel) # si status no existe es que NO HAY valor en _data.json if status is None: status = channel_parameters["active"] logger.debug("%s | Status (XML): %s" % (channel.channel, status)) if not status: status_control = " [COLOR grey](Desactivado por defecto)[/COLOR]" else: logger.debug("%s | Status: %s" % (channel.channel, status)) control = { 'id': channel.channel, 'type': "bool", 'label': channel_parameters["title"] + status_control, 'default': status, 'enabled': True, 'visible': True } list_controls.append(control) else: continue except: import traceback logger.error("Error: %s" % traceback.format_exc()) else: return platformtools.show_channel_settings( list_controls=list_controls, item=item.clone(channel_list=channel_list), caption="Canales", callback="channel_status", custom_button={"visible": False}) # Comprobacion de archivos channel_data.json elif item.extra == "lib_check_datajson": itemlist = [] import channelselector from core import channeltools channel_list = channelselector.filterchannels("allchannelstatus") # Tener una lista de exclusion no tiene mucho sentido por que se comprueba si # el xml tiene "settings", pero por si acaso se deja excluded_channels = ['tengourl', 'configuracion', 'personal', 'ayuda'] try: import os from core import jsontools for channel in channel_list: list_status = None default_settings = None # Se comprueba si el canal esta en la lista de exclusiones if channel.channel not in excluded_channels: # Se comprueba que tenga "settings", sino se salta jsonchannel = channeltools.get_channel_json( channel.channel) if not jsonchannel.get("settings"): itemlist.append( Item(channel=CHANNELNAME, title=channel.title + " - No tiene ajustes por defecto", action="", folder=False, thumbnail=channel.thumbnail)) continue # logger.info(channel.channel + " SALTADO!") # Se cargan los ajustes del archivo json del canal file_settings = os.path.join( config.get_data_path(), "settings_channels", channel.channel + "_data.json") dict_settings = {} dict_file = {} if filetools.exists(file_settings): # logger.info(channel.channel + " Tiene archivo _data.json") channeljson_exists = True # Obtenemos configuracion guardada de ../settings/channel_data.json try: dict_file = jsontools.load_json( open(file_settings, "rb").read()) if isinstance(dict_file, dict) and 'settings' in dict_file: dict_settings = dict_file['settings'] except EnvironmentError: logger.error("ERROR al leer el archivo: %s" % file_settings) else: # logger.info(channel.channel + " No tiene archivo _data.json") channeljson_exists = False if channeljson_exists == True: try: datajson_size = filetools.getsize(file_settings) except: import traceback logger.error(channel.title + " | Detalle del error: %s" % traceback.format_exc()) else: datajson_size = None # Si el _data.json esta vacio o no existe... if (len(dict_settings) and datajson_size) == 0 or channeljson_exists == False: # Obtenemos controles del archivo ../channels/channel.xml needsfix = True try: # Se cargan los ajustes por defecto list_controls, default_settings = channeltools.get_channel_controls_settings( channel.channel) # logger.info(channel.title + " | Default: %s" % default_settings) except: import traceback logger.error(channel.title + " | Detalle del error: %s" % traceback.format_exc()) # default_settings = {} # Si _data.json necesita ser reparado o no existe... if needsfix == True or channeljson_exists == False: if default_settings is not None: # Creamos el channel_data.json default_settings.update(dict_settings) dict_settings = default_settings dict_file['settings'] = dict_settings # Creamos el archivo ../settings/channel_data.json json_data = jsontools.dump_json(dict_file) try: open(file_settings, "wb").write(json_data) # logger.info(channel.channel + " - Archivo _data.json GUARDADO!") # El channel_data.json se ha creado/modificado list_status = " - [COLOR red] CORREGIDO!![/COLOR]" except EnvironmentError: logger.error( "ERROR al salvar el archivo: %s" % file_settings) else: if default_settings is None: list_status = " - [COLOR red] Imposible cargar los ajustes por defecto![/COLOR]" else: # logger.info(channel.channel + " - NO necesita correccion!") needsfix = False # Si se ha establecido el estado del canal se añade a la lista if needsfix is not None: if needsfix == True: if channeljson_exists == False: list_status = " - Ajustes creados" list_colour = "red" else: list_status = " - No necesita corrección" list_colour = "green" else: # Si "needsfix" es "false" y "datjson_size" es None habra # ocurrido algun error if datajson_size is None: list_status = " - Ha ocurrido algun error" list_colour = "red" else: list_status = " - No necesita corrección" list_colour = "green" if list_status is not None: itemlist.append( Item(channel=CHANNELNAME, title=channel.title + list_status, action="", folder=False, thumbnail=channel.thumbnail, text_color=list_colour)) else: logger.error("Algo va mal con el canal %s" % channel.channel) # Si el canal esta en la lista de exclusiones lo saltamos else: continue except: import traceback logger.error("Error: %s" % traceback.format_exc()) return itemlist
def mainlist(item): logger.info() itemlist = list() itemlist.append( Item(channel=CHANNELNAME, title="Preferencias", action="settings", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) if config.get_setting("plugin_updates_available") == "0": nuevas = "" elif config.get_setting("plugin_updates_available") == "1": nuevas = " (1 nueva)" else: nuevas = " (" + config.get_setting( "plugin_updates_available") + " nuevas)" itemlist.append( Item(channel=CHANNELNAME, title="Descargar e instalar otras versiones" + nuevas, action="get_all_versions", folder=True)) itemlist.append( Item(channel=CHANNELNAME, title="", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Ajustes especiales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append( Item(channel="novedades", title=" Ajustes de la sección 'Novedades'", action="menu_opciones", folder=True, thumbnail=get_thumbnail_path("thumb_novedades.png"))) itemlist.append( Item(channel="buscador", title=" Ajustes del buscador global", action="opciones", folder=True, thumbnail=get_thumbnail_path("thumb_buscar.png"))) if config.get_library_support(): itemlist.append( Item(channel="biblioteca", title=" Ajustes de la biblioteca", action="channel_config", folder=True, thumbnail=get_thumbnail_path("thumb_biblioteca.png"))) itemlist.append( Item(channel="biblioteca", action="update_biblio", folder=False, thumbnail=get_thumbnail_path("thumb_biblioteca.png"), title=" Buscar nuevos episodios y actualizar biblioteca")) itemlist.append( Item(channel=CHANNELNAME, title=" Añadir o Actualizar canal/conector desde una URL", action="menu_addchannels")) itemlist.append( Item(channel=item.channel, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Ajustes por canales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) import channelselector from core import channeltools channel_list = channelselector.filterchannels("all") for channel in channel_list: jsonchannel = channeltools.get_channel_json(channel.channel) if jsonchannel.get("settings"): setting = jsonchannel["settings"] if type(setting) == list: if len([ s for s in setting if "id" in s and "include_in_" not in s["id"] ]): itemlist.append( Item(channel=CHANNELNAME, title=" Configuración del canal '%s'" % channel.title, action="channel_config", config=channel.channel, folder=False, thumbnail=channel.thumbnail)) return itemlist
def run(): logger.info("deportesalacarta.platformcode.launcher run") # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if item.action != "actualiza": logger.info("deportesalacarta.platformcode.launcher " + item.tostring()) try: if item.action == "editor_keymap": from platformcode import editor_keymap return editor_keymap.start() # If item has no action, stops here if item.action == "": logger.info( "deportesalacarta.platformcode.launcher Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() # Check for updates only on first screen if config.get_setting("updatecheck") == "true": logger.info("Check for plugin updates enabled") from core import updater try: update, version_publicada, message, url_repo, serv = updater.check( ) if update: new_item = Item( title="Descargar versión " + version_publicada, channel="updater", action="actualiza", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png", version=version_publicada, url=url_repo, server=serv) if config.get_setting("updateauto") == "true": updater.actualiza(new_item) new_item = Item( title= "Info para ver los cambios en la nueva versión instalada", plot=message, action="", channel="", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png", text_color="red") itemlist.insert(0, new_item) else: platformtools.dialog_ok( "Versión " + version_publicada + " disponible", message) itemlist.insert(0, new_item) except: import traceback logger.info(traceback.format_exc()) logger.info( "deportesalacarta.platformcode.launcher Fallo al verificar la actualización" ) else: logger.info( "deportesalacarta.platformcode.launcher Check for plugin updates disabled" ) if not config.get_setting("primer_uso_matchcenter"): config.set_setting("primer_uso_matchcenter", "true") platformtools.dialog_ok( "MatchCenter activado", "Reinicia Kodi para usarlo (pulsar tecla U)", "La tecla, botones y otras opciones pueden cambiarse en Configuración -> Preferencias -> MatchCenter" ) file_keyboard = xbmc.translatePath( "special://profile/keymaps/deportesalacarta.xml") if config.get_setting( "matchcenter_enabled" ) == "true" and not os.path.exists(file_keyboard): tecla = "61525" tecla_guardada = config.get_setting("keymap_edit", "editor_keymap") if tecla_guardada: tecla = tecla_guardada from core import filetools data = '<keymap><global><keyboard><key id="%s">' % tecla + 'runplugin(plugin://plugin.video.deportesalacarta/?ewogICAgImFjdGlvbiI6ICJzdGFydCIsIAogICAgImNoYW5uZWwiOiAibWF0Y2hjZW50ZXIiLCAKICAgICJpbmZvTGFiZWxzIjoge30KfQ%3D%3D))</key></keyboard></global></keymap>' filetools.write(file_keyboard, data) elif config.get_setting( "matchcenter_enabled") == "false" and os.path.exists( file_keyboard): from core import filetools try: filetools.remove(file_keyboard) except: pass platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "actualiza": from core import updater updater.actualiza(item) xbmc.executebuiltin("Container.Refresh") # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Action in certain channel specified in "action" and "channel" parameters else: can_open_channel = True # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info( "deportesalacarta.platformcode.launcher channel_file=%s" % channel_file) channel = None if os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels." + item.channel + " as channel" logger.info( "deportesalacarta.platformcode.launcher running channel " + channel.__name__ + " " + channel.__file__) # Special play action if item.action == "play": logger.info("deportesalacarta.platformcode.launcher play") # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info( "deportesalacarta.platformcode.launcher executing channel 'play' method" ) itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) #Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info( "deportesalacarta.platformcode.launcher executing core 'play' method" ) platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info( "deportesalacarta.platformcode.launcher no channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) platformtools.render_items(itemlist, item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("deportesalacarta.platformcode.launcher search") tecleado = platformtools.dialog_input("") if tecleado is not None: tecleado = tecleado.replace(" ", "+") # TODO revisar 'personal.py' porque no tiene función search y daría problemas itemlist = channel.search(item, tecleado) else: itemlist = [] platformtools.render_items(itemlist, item) # For all other actions else: logger.info( "deportesalacarta.platformcode.launcher executing channel '" + item.action + "' method") itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error("deportesalacarta.platformcode.launcher " + traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info( "deportesalacarta.platformcode.launcher Razon del error, codigo: " + str(e.reason[0]) + ", Razon: " + str(e.reason[1])) texto = config.get_localized_string( 30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("plugin", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info( "deportesalacarta.platformcode.launcher codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok( "plugin", config.get_localized_string(30051) % e.code)
def run(): logger.info("pelisalacarta.platformcode.launcher run") # The start() function is not always executed on old platforms (XBMC versions under 12.0) if config.OLD_PLATFORM: config.verify_directories_created() # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(action="selectchannel", viewmode="movie") logger.info("pelisalacarta.platformcode.launcher "+item.tostring()) # Set server filters server_white_list = [] server_black_list = [] if config.get_setting('filter_servers') == 'true': server_white_list, server_black_list = set_server_list() try: # If item has no action, stops here if item.action == "": logger.info("pelisalacarta.platformcode.launcher Item sin accion") return # Action for main menu in channelselector if ( item.action=="selectchannel" ): import channelselector itemlist = channelselector.getmainlist() # Check for updates only on first screen if config.get_setting("updatecheck2") == "true": logger.info("pelisalacarta.platformcode.launcher Check for plugin updates enabled") from core import updater try: version = updater.checkforupdates() if version: import xbmcgui advertencia = xbmcgui.Dialog() advertencia.ok("Versión "+version+" disponible","Ya puedes descargar la nueva versión del plugin\ndesde el listado principal") itemlist.insert(0,Item(title="Descargar version "+version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png")) except: import xbmcgui advertencia = xbmcgui.Dialog() advertencia.ok("No se puede conectar","No ha sido posible comprobar","si hay actualizaciones") logger.info("cpelisalacarta.platformcode.launcher Fallo al verificar la actualización") else: logger.info("pelisalacarta.platformcode.launcher Check for plugin updates disabled") xbmctools.renderItems(itemlist, item) # Action for updating plugin elif (item.action=="update"): from core import updater updater.update(item) if config.get_system_platform()!="xbox": import xbmc xbmc.executebuiltin( "Container.Refresh" ) # Action for channel types on channelselector: movies, series, etc. elif (item.action=="channeltypes"): import channelselector itemlist = channelselector.getchanneltypes() xbmctools.renderItems(itemlist, item) # Action for channel listing on channelselector elif (item.action=="listchannels"): import channelselector itemlist = channelselector.filterchannels(item.category) xbmctools.renderItems(itemlist, item) # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action=="mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_pin")!="": 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 # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py") logger.info("pelisalacarta.platformcode.launcher channel_file=%s" % channel_file) if item.channel in ["personal","personal2","personal3","personal4","personal5"]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, fromlist=["channels.%s" % item.channel]) except: exec "import channels."+item.channel+" as channel" logger.info("pelisalacarta.platformcode.launcher running channel "+channel.__name__+" "+channel.__file__) # Special play action if item.action == "play": logger.info("pelisalacarta.platformcode.launcher play") #item.show, item.fulltitle = item.fulltitle, item.show # intecambia los valores para que muestre el título de la peli # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method") itemlist = channel.play(item) # Play should return a list of playable URLS if len(itemlist) > 0: item = itemlist[0] xbmctools.play_video(item) # If not, shows user an error message else: import xbmcgui ventana_error = xbmcgui.Dialog() ok = ventana_error.ok("plugin", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from xbmctools else: logger.info("pelisalacarta.platformcode.launcher executing core 'play' method") xbmctools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": if item.strm: # Special action for playing a video from the library play_from_library(item, channel, server_white_list, server_black_list) # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist, server_white_list, server_black_list) from platformcode import subtitletools subtitletools.saveSubtitleName(item) # Show xbmc items as "movies", so plot is visible import xbmcplugin handle = sys.argv[1] xbmcplugin.setContent(int( handle ),"movies") # Add everything to XBMC item list if type(itemlist) == list and itemlist: xbmctools.renderItems(itemlist, item) # If not, it shows an empty list # FIXME: Aquí deberíamos mostrar alguna explicación del tipo "No hay elementos, esto pasa por bla bla bla" else: xbmctools.renderItems([], item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": downloadtools.download_all_episodes(item, channel) # Special action for searching, first asks for the words then call the "search" function elif item.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, item) # For all other actions else: logger.info("pelisalacarta.platformcode.launcher executing channel '"+item.action+"' method") itemlist = getattr(channel, item.action)(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 if type(itemlist) == list and itemlist: xbmctools.renderItems(itemlist, item) # If not, it shows an empty list # FIXME: Aquí deberíamos mostrar alguna explicación del tipo "No hay elementos, esto pasa por bla bla bla" else: xbmctools.renderItems([], item) except urllib2.URLError,e: import traceback logger.error("pelisalacarta.platformcode.launcher "+traceback.format_exc()) import xbmcgui ventana_error = xbmcgui.Dialog() # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("pelisalacarta.platformcode.launcher Razon del error, codigo: "+str(e.reason[0])+", Razon: "+str(e.reason[1])) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" ok = ventana_error.ok ("plugin", texto) # Grab server response errors elif hasattr(e,'code'): logger.info("pelisalacarta.platformcode.launcher 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 run(): logger.info("deportesalacarta.platformcode.launcher run") # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info("deportesalacarta.platformcode.launcher "+item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("deportesalacarta.platformcode.launcher Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() # Check for updates only on first screen if config.get_setting("updatecheck2") == "true": logger.info("deportesalacarta.platformcode.launcher Check for plugin updates enabled") from core import updater try: update, version_publicada, message = updater.check() if update: platformtools.dialog_ok("Versión "+version_publicada+" disponible", message) itemlist.insert(0, Item(title="Descargar versión "+version_publicada, channel="updater", action="actualiza", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png", version=version_publicada)) except: import traceback logger.info(traceback.format_exc()) logger.info("deportesalacarta.platformcode.launcher Fallo al verificar la actualización") else: logger.info("deportesalacarta.platformcode.launcher Check for plugin updates disabled") platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "actualiza": from core import updater updater.actualiza(item) import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Action in certain channel specified in "action" and "channel" parameters else: can_open_channel = True # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py") logger.info("deportesalacarta.platformcode.launcher channel_file=%s" % channel_file) channel = None if os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels."+item.channel+" as channel" logger.info("deportesalacarta.platformcode.launcher running channel "+channel.__name__+" "+channel.__file__) # Special play action if item.action == "play": logger.info("deportesalacarta.platformcode.launcher play") # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("deportesalacarta.platformcode.launcher executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0: item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("deportesalacarta.platformcode.launcher executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info("deportesalacarta.platformcode.launcher no channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) platformtools.render_items(itemlist, item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("deportesalacarta.platformcode.launcher search") tecleado = platformtools.dialog_input("") if tecleado is not None: tecleado = tecleado.replace(" ", "+") # TODO revisar 'personal.py' porque no tiene función search y daría problemas itemlist = channel.search(item, tecleado) else: itemlist = [] platformtools.render_items(itemlist, item) # For all other actions else: logger.info("deportesalacarta.platformcode.launcher executing channel '"+item.action+"' method") itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error("deportesalacarta.platformcode.launcher "+traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("deportesalacarta.platformcode.launcher Razon del error, codigo: "+str(e.reason[0])+", Razon: " + str(e.reason[1])) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("plugin", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info("deportesalacarta.platformcode.launcher codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
def run(): logger.info("pelisalacarta.platformcode.launcher run") # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info("pelisalacarta.platformcode.launcher "+item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("pelisalacarta.platformcode.launcher Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() # Check for updates only on first screen if config.get_setting("updatecheck2") == "true": logger.info("pelisalacarta.platformcode.launcher Check for plugin updates enabled") from core import updater try: version = updater.checkforupdates() if version: platformtools.dialog_ok("Versión "+version+" disponible", "Ya puedes descargar la nueva versión del plugin\n" "desde el listado principal") itemlist.insert(0, Item(title="Descargar version "+version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png")) except: platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar", "si hay actualizaciones") logger.info("cpelisalacarta.platformcode.launcher Fallo al verificar la actualización") else: logger.info("pelisalacarta.platformcode.launcher Check for plugin updates disabled") platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "update": from core import updater updater.update(item) if config.get_system_platform() != "xbox": import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_pin") != "": tecleado = platformtools.dialog_input("", "PIN para canales de adultos", True) if tecleado is not None: if tecleado == config.get_setting("adult_pin"): can_open_channel = True # All the other cases can open the channel else: can_open_channel = True if not can_open_channel: return # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py") logger.info("pelisalacarta.platformcode.launcher channel_file=%s" % channel_file) channel = None if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels."+item.channel+" as channel" logger.info("pelisalacarta.platformcode.launcher running channel "+channel.__name__+" "+channel.__file__) # Special play action if item.action == "play": logger.info("pelisalacarta.platformcode.launcher play") # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0: item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("pelisalacarta.platformcode.launcher executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import descargas item.action = item.extra del item.extra descargas.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("pelisalacarta.platformcode.launcher search") tecleado = platformtools.dialog_input("") if tecleado is not None: tecleado = tecleado.replace(" ", "+") # TODO revisar 'personal.py' porque no tiene función search y daría problemas itemlist = channel.search(item, tecleado) else: itemlist = [] platformtools.render_items(itemlist, item) # For all other actions else: logger.info("pelisalacarta.platformcode.launcher executing channel '"+item.action+"' method") itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error("pelisalacarta.platformcode.launcher "+traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("pelisalacarta.platformcode.launcher Razon del error, codigo: "+str(e.reason[0])+", Razon: " + str(e.reason[1])) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("plugin", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info("pelisalacarta.platformcode.launcher codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
def 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 = '<?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 run(): logger.info("streamondemand.platformcode.launcher run") # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info("streamondemand.platformcode.launcher " + item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("streamondemand.platformcode.launcher Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector # Check for updates only on first screen if config.get_setting("check_for_plugin_updates") == "true": logger.info( "streamondemand.platformcode.launcher Check for plugin updates enabled" ) from core import updater try: config.set_setting("plugin_updates_available", "0") version = updater.checkforupdates() itemlist = channelselector.getmainlist() if version: config.set_setting("plugin_updates_available", "1") platformtools.dialog_ok( "Versione " + version + " disponible", "E' possibile fare il download della nuova versione\n" "selezionare la relativa voce nel menu principale") itemlist = channelselector.getmainlist() itemlist.insert( 0, Item(title="Download versione " + version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumb( "squares", "thumb_actualizar.png"))) except: import traceback logger.info(traceback.format_exc()) platformtools.dialog_ok( "Impossibile connettersi", "Non è stato possibile verificare", "aggiornamenti") logger.info( "cpelisalacarta.platformcode.launcher Fallo al verificar la actualización" ) config.set_setting("plugin_updates_available", "0") itemlist = channelselector.getmainlist() else: logger.info( "streamondemand.platformcode.launcher Check for plugin updates disabled" ) config.set_setting("plugin_updates_available", "0") itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "update": from core import updater updater.update(item) config.set_setting("plugin_updates_available", "0") if config.get_system_platform() != "xbox": import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting( "adult_pin") != "": tecleado = platformtools.dialog_input( "", "PIN per canali per adulti", True) if tecleado is not None: if tecleado == config.get_setting("adult_pin"): can_open_channel = True # All the other cases can open the channel else: can_open_channel = True if not can_open_channel: return # Actualiza el canal individual if item.action == "mainlist" and item.channel != "channelselector" and config.get_setting( "check_for_channel_updates") == "true": from core import updater updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info( "streamondemand.platformcode.launcher channel_file=%s" % channel_file) channel = None if item.channel in [ "personal", "personal2", "personal3", "personal4", "personal5" ]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels." + item.channel + " as channel" logger.info( "streamondemand.platformcode.launcher running channel " + channel.__name__ + " " + channel.__file__) # Special play action if item.action == "play": logger.info("streamondemand.platformcode.launcher play") # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info( "streamondemand.platformcode.launcher executing channel 'play' method" ) itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0: item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) #Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("plugin", "Niente da riprodurre") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info( "streamondemand.platformcode.launcher executing core 'play' method" ) platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info( "streamondemand.platformcode.launcher no channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import descargas item.action = item.extra del item.extra descargas.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("streamondemand.platformcode.launcher search") last_search = "" last_search_active = config.get_setting( "last_search", "buscador") if last_search_active: try: current_saved_searches_list = list( config.get_setting("saved_searches_list", "buscador")) last_search = current_saved_searches_list[0] except: pass tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if last_search_active: from channels import buscador buscador.save_search(tecleado) # TODO revisar 'personal.py' porque no tiene función search y daría problemas # DrZ3r0 itemlist = channel.search(item, tecleado.replace(" ", "+")) else: itemlist = [] platformtools.render_items(itemlist, item) # For all other actions else: logger.info( "streamondemand.platformcode.launcher executing channel '" + item.action + "' method") itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error("streamondemand.platformcode.launcher " + traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info( "streamondemand.platformcode.launcher Razon del error, codigo: " + str(e.reason[0]) + ", Razon: " + str(e.reason[1])) texto = config.get_localized_string( 30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("plugin", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info( "streamondemand.platformcode.launcher codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok( "plugin", config.get_localized_string(30051) % e.code)
def run(item=None): logger.info() if not item: # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: if config.get_setting("start_page"): if not config.get_setting("custom_start"): dictCategory = { config.get_localized_string(70137): 'peliculas', config.get_localized_string(30123): 'series', config.get_localized_string(30124): 'anime', config.get_localized_string(70018): 'infantiles', config.get_localized_string(60513): 'documentales', config.get_localized_string(70013): 'terror', config.get_localized_string(30124): 'castellano', config.get_localized_string(59976): 'latino', config.get_localized_string(70171): 'torrent', } category = dictCategory[config.get_setting("category")] item = Item(channel="news", action="novedades", extra=category, mode = 'silent') else: from specials import side_menu item= Item() item = side_menu.check_user_home(item) item.start = True else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): if not os.path.isdir(config.get_runtime_path() + '/.git'): logger.info("DEV MODE OFF") from platformcode import updater updater.calcCurrHash() from platformcode import xbmc_videolibrary xbmc_videolibrary.ask_set_content(1, config.get_setting('videolibrary_kodi_force')) config.set_setting('show_once', True) logger.info(item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() elif item.action == "delete_key": from platformcode import keymaptools return keymaptools.delete_key() elif item.action == "script": from core import tmdb if tmdb.drop_bd(): platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": #updater.checkforupdates() beta version checking for update, still disabled # Parental control # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_request_password"): tecleado = platformtools.dialog_input("", config.get_localized_string(60334), True) if tecleado is None or tecleado != config.get_setting("adult_password"): return # # Actualiza el canal individual # if (item.action == "mainlist" and item.channel != "channelselector" and # config.get_setting("check_for_channel_updates") == True): # from core import updater # updater.update_channel(item.channel) # Checks if channel exists if os.path.isfile(os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py")): CHANNELS = 'channels' else: CHANNELS ='specials' channel_file = os.path.join(config.get_runtime_path(), CHANNELS, item.channel + ".py") logger.info("channel_file= " + channel_file) channel = None if os.path.exists(channel_file): try: channel = __import__(CHANNELS + item.channel, None, None, [CHANNELS + item.channel]) except ImportError: importer = "import " + CHANNELS + "." + item.channel + " as channel" exec(importer) logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": #define la info para trakt try: trakt_tools.set_trakt_info(item) except: pass logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(60339)) # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) itemlist = servertools.filter_servers(itemlist) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from specials import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) last_search = "" last_search_active = config.get_setting("last_search", "search") if last_search_active: try: current_saved_searches_list = list(config.get_setting("saved_searches_list", "search")) last_search = current_saved_searches_list[0] except: pass tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if last_search_active and not tecleado.startswith("http"): from specials import search search.save_search(tecleado) itemlist = channel.search(item, tecleado) else: return platformtools.render_items(itemlist, item) # For all other actions else: # import web_pdb; web_pdb.set_trace() logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) if config.get_setting('trakt_sync'): token_auth = config.get_setting("token_trakt", "trakt") if not token_auth: trakt_tools.auth_trakt() else: import xbmc if not xbmc.getCondVisibility('System.HasAddon(script.trakt)') and config.get_setting( 'install_trakt'): trakt_tools.ask_install_script() itemlist = trakt_tools.trakt_check(itemlist) else: config.set_setting('install_trakt', True) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.error("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("alfa", texto) # Grab server response errors elif hasattr(e, 'code'): logger.error("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("alfa", config.get_localized_string(30051) % e.code)
def mainlist(item): logger.info() itemlist = list() itemlist.append( Item(channel=CHANNELNAME, title="Preferencias", action="settings", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) if config.get_setting("plugin_updates_available") == "0": nuevas = "" elif config.get_setting("plugin_updates_available") == "1": nuevas = " (1 nueva)" else: nuevas = " (" + config.get_setting( "plugin_updates_available") + " nuevas)" thumb_configuracion = "thumb_configuracion_" + config.get_setting( "plugin_updates_available") + ".png" itemlist.append( Item(channel=CHANNELNAME, title="Descargar e instalar otras versiones" + nuevas, action="get_all_versions", folder=True, thumbnail=get_thumbnail_path(thumb_configuracion))) itemlist.append( Item(channel=CHANNELNAME, title="", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Ajustes especiales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append( Item(channel="novedades", title=" Ajustes de la sección 'Novedades'", action="menu_opciones", folder=True, thumbnail=get_thumbnail_path("thumb_novedades.png"))) itemlist.append( Item(channel="buscador", title=" Ajustes del buscador global", action="opciones", folder=True, thumbnail=get_thumbnail_path("thumb_buscar.png"))) itemlist.append( Item(channel=CHANNELNAME, title=" Ajustes de descargas", action="channel_config", config="descargas", folder=True, thumbnail=get_thumbnail_path("thumb_descargas.png"))) if config.get_library_support(): itemlist.append( Item(channel="biblioteca", title=" Ajustes de la biblioteca", action="channel_config", folder=True, thumbnail=get_thumbnail_path("thumb_biblioteca.png"))) itemlist.append( Item(channel="biblioteca", action="update_biblio", folder=False, thumbnail=get_thumbnail_path("thumb_biblioteca.png"), title=" Buscar nuevos episodios y actualizar biblioteca")) itemlist.append( Item(channel=CHANNELNAME, title=" Añadir o Actualizar canal/conector desde una URL", action="menu_addchannels")) itemlist.append( Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Activar/desactivar canales", action="conf_tools", folder=False, extra="channels_onoff", thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Ajustes por canales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) # Inicio - Canales configurables import channelselector from core import channeltools channel_list = channelselector.filterchannels("all") for channel in channel_list: channel_parameters = channeltools.get_channel_parameters( channel.channel) if channel_parameters["has_settings"]: itemlist.append( Item(channel=CHANNELNAME, title=" Configuración del canal '%s'" % channel.title, action="channel_config", config=channel.channel, folder=False, thumbnail=channel.thumbnail)) # Fin - Canales configurables itemlist.append( Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Otras herramientas", action="submenu_tools", folder=True, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) return itemlist
def get_next_items( item ): plugintools.log("navigation.get_next_items item="+item.tostring()) try: # ---------------------------------------------------------------- # Main menu # ---------------------------------------------------------------- if item.channel=="navigation": 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") else: if item.action=="": item.action="mainlist" plugintools.log("navigation.get_next_items Channel code ("+item.channel+"."+item.action+")") try: exec "import channels."+item.channel+" as channel" except: exec "import core."+item.channel+" as channel" from platformcode import platformtools 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("navigation.get_next_items play 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: platformtools.play_video(item) except: pass else: import xbmcgui ventana_error = xbmcgui.Dialog() ok = ventana_error.ok ("plugin", "No hay nada para reproducir") else: plugintools.log("navigation.get_next_items play 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: platformtools.play_video(item) except: import traceback plugintools.log(traceback.format_exc()) 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("navigation.get_next_items play Channel has its own 'findvideos' method") itemlist = channel.findvideos(item) else: itemlist = [] if len(itemlist)==0: from core import servertools itemlist = servertools.find_video_items(item) if len(itemlist)==0: itemlist = [ Item(title="No se han encontrado vídeos", thumbnail="http://media.tvalacarta.info/pelisalacarta/thumb_error.png") ] 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 = "http://media.tvalacarta.info/pelisalacarta/thumb_folder.png" else: loaded_item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_nofolder.png" if len(itemlist)==0: itemlist = [ Item(title="No hay elementos para mostrar", thumbnail="http://media.tvalacarta.info/pelisalacarta/thumb_error.png" ) ] except: import traceback plugintools.log("navigation.get_next_items "+traceback.format_exc()) itemlist = [ Item(title="Se ha producido un error", thumbnail="http://media.tvalacarta.info/pelisalacarta/thumb_error.png") ] return itemlist
def runchannel(sender, channel, action="mainlist", category=""): Log("[__init__.py] runchannel") Log("channel=" + channel) Log("action=" + action) dir = MediaContainer(viewGroup="InfoList") # Importa el canal y obtiene los items try: exec "from tvalacarta.channels import " + channel except: try: exec "from core import " + channel except: exec "import " + channel if channel != "channelselector": exec "itemlist = " + channel + "." + action + "(None)" elif action == "channeltypes": itemlist = channelselector.getchanneltypes() elif action == "listchannels": itemlist = channelselector.filterchannels(category) Log("itemlist %d items" % len(itemlist)) for item in itemlist: Log("item=" + item.tostring() + " channel=[" + item.channel + "]") category = "" if category != "": category = category[:-2] if not item.thumbnail.startswith("http://"): item.thumbnail = "http://tvalacarta.mimediacenter.info/posters/" + item.channel + ".png" # Log("category=%s" % category) # thumbnail = 'images/posters/'+item.channel+'.png' # Log("thumbnail=%s" % thumbnail) # Opciones de menú if item.channel == "channelselector": dir.Append( Function( DirectoryItem(runchannel, title=item.title, subtitle="", thumb=item.thumbnail, art=R(ART)), channel=item.channel, action=item.action, category=item.category, ) ) # Los canales else: if item.type == "generic" and item.extra != "rtmp" and item.extra != "background": dir.Append( Function( DirectoryItem(actionexecute, title=item.title, subtitle=category, thumb=item.thumbnail), itemtext=item.serialize(), ) ) return dir
def get_next_items(item): plugintools.log("navigation.get_next_items item=" + item.tostring()) try: # ---------------------------------------------------------------- # Main menu # ---------------------------------------------------------------- if item.channel == "navigation": if item.action == "mainlist": plugintools.log("navigation.get_next_items Main menu") itemlist = channelselector.getmainlist("bannermenu") elif item.channel == "channelselector": if item.action == "getchanneltypes": plugintools.log("navigation.get_next_items Channel types menu") itemlist = channelselector.getchanneltypes("bannermenu") elif item.action == "filterchannels": plugintools.log( "navigation.get_next_items Channel list menu, channel_type=" + item.channel_type) itemlist = channelselector.filterchannels( item.channel_type, "bannermenu") else: if item.action == "": item.action = "mainlist" plugintools.log("navigation.get_next_items Channel code (" + item.channel + "." + item.action + ")") try: exec "import channels." + item.channel + " as channel" except: exec "import core." + item.channel + " as channel" from platformcode import platformtools 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( "navigation.get_next_items play 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: platformtools.play_video(item) except: pass else: import xbmcgui ventana_error = xbmcgui.Dialog() ok = ventana_error.ok("plugin", "No hay nada para reproducir") else: plugintools.log( "navigation.get_next_items play 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: platformtools.play_video(item) except: import traceback plugintools.log(traceback.format_exc()) 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( "navigation.get_next_items play Channel has its own 'findvideos' method" ) itemlist = channel.findvideos(item) else: itemlist = [] if len(itemlist) == 0: from core import servertools itemlist = servertools.find_video_items(item) if len(itemlist) == 0: itemlist = [ Item( title="No se han encontrado vídeos", thumbnail= "http://media.tvalacarta.info/pelisalacarta/thumb_error.png" ) ] 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)" if itemlist is None: itemlist = [] for loaded_item in itemlist: if loaded_item.thumbnail == "": if loaded_item.folder: loaded_item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_folder.png" else: loaded_item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/thumb_nofolder.png" if len(itemlist) == 0: itemlist = [ Item( title="No hay elementos para mostrar", thumbnail= "http://media.tvalacarta.info/pelisalacarta/thumb_error.png" ) ] except: import traceback plugintools.log("navigation.get_next_items " + traceback.format_exc()) itemlist = [ Item(title="Se ha producido un error", thumbnail= "http://media.tvalacarta.info/pelisalacarta/thumb_error.png") ] plugintools.log("navigation.get_next_items " + str(len(itemlist)) + " channels") return itemlist
def runchannel(sender, channel, action="mainlist", category=""): Log("[__init__.py] runchannel") Log("channel=" + channel) Log("action=" + action) dir = MediaContainer(viewGroup="InfoList") # Importa el canal y obtiene los items try: exec "from tvalacarta.channels import " + channel except: try: exec "from core import " + channel except: exec "import " + channel if channel != "channelselector": exec "itemlist = " + channel + "." + action + "(None)" elif action == "channeltypes": itemlist = channelselector.getchanneltypes() elif action == "listchannels": itemlist = channelselector.filterchannels(category) Log("itemlist %d items" % len(itemlist)) for item in itemlist: Log("item=" + item.tostring() + " channel=[" + item.channel + "]") category = "" if category != "": category = category[:-2] if not item.thumbnail.startswith("http://"): item.thumbnail = 'http://tvalacarta.mimediacenter.info/posters/' + item.channel + '.png' #Log("category=%s" % category) #thumbnail = 'images/posters/'+item.channel+'.png' #Log("thumbnail=%s" % thumbnail) # Opciones de menú if item.channel == "channelselector": dir.Append( Function(DirectoryItem(runchannel, title=item.title, subtitle="", thumb=item.thumbnail, art=R(ART)), channel=item.channel, action=item.action, category=item.category)) # Los canales else: if item.type == "generic" and item.extra != "rtmp" and item.extra != "background": dir.Append( Function(DirectoryItem(actionexecute, title=item.title, subtitle=category, thumb=item.thumbnail), itemtext=item.serialize())) return dir
def mainlist(item): logger.info() itemlist = list() itemlist.append( Item(channel=CHANNELNAME, title="Preferenze", action="settings", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append( Item(channel=CHANNELNAME, title="", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Impostazioni speciali", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append( Item(channel="novedades", title=" Impostazioni 'Novità'", action="menu_opciones", folder=True, thumbnail=get_thumbnail_path("thumb_novedades.png"))) itemlist.append( Item(channel="buscador", title=" Impostazioni della ricerca globale", action="opciones", folder=True, thumbnail=get_thumbnail_path("thumb_buscar.png"))) if config.get_library_support(): itemlist.append( Item(channel="biblioteca", title=" Impostazioni libreria", action="channel_config", folder=True, thumbnail=get_thumbnail_path("thumb_biblioteca.png"))) itemlist.append( Item(channel="biblioteca", action="update_biblio", folder=False, thumbnail=get_thumbnail_path("thumb_biblioteca.png"), title=" Recupera nuovi episodi e aggiorna la libreria")) itemlist.append( Item(channel=CHANNELNAME, title="Avvia aggiornamenti", action="check_for_updates", folder=False)) itemlist.append( Item(channel=item.channel, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append( Item(channel=CHANNELNAME, title="Impostazioni canali", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) import channelselector from core import channeltools channel_list = channelselector.filterchannels("all") for channel in channel_list: try: jsonchannel = channeltools.get_channel_json(channel.channel) except: continue if jsonchannel.get("settings"): setting = jsonchannel["settings"] if type(setting) == list: if len([ s for s in setting if "id" in s and "include_in_" not in s["id"] ]): active_status = None if config.get_setting("enabled", channel.channel): active_status = config.get_setting( "enabled", channel.channel) else: channel_parameters = channeltools.get_channel_parameters( channel.channel) active_status = channel_parameters['active'] if active_status == "true": itemlist.append( Item(channel=CHANNELNAME, title=" Configurazione canale '%s'" % channel.title, action="channel_config", config=channel.channel, folder=False, thumbnail=channel.thumbnail)) return itemlist
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 setting_channel_new(item): import xbmcgui # Load list of options (active user channels that allow global search) lista = [] ids = [] lista_lang = [] lista_ctgs = [] channels_list = channelselector.filterchannels('all') for channel in channels_list: if channel.action == '': continue channel_parameters = channeltools.get_channel_parameters(channel.channel) # Do not include if "include_in_global_search" does not exist in the channel configuration if not channel_parameters['include_in_global_search']: continue lbl = '%s' % channel_parameters['language'] lbl += ' %s' % ', '.join(config.get_localized_category(categ) for categ in channel_parameters['categories']) it = xbmcgui.ListItem(channel.title, lbl) it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart}) lista.append(it) ids.append(channel.channel) lista_lang.append(channel_parameters['language']) lista_ctgs.append(channel_parameters['categories']) # Pre-select dialog preselecciones = [ config.get_localized_string(70570), config.get_localized_string(70571), 'Modificar partiendo de Recomendados', 'Modificar partiendo de Frecuentes', config.get_localized_string(70572), config.get_localized_string(70573), config.get_localized_string(70574), config.get_localized_string(70575) ] presel_values = ['skip', 'actual', 'recom', 'freq', 'all', 'none', 'cast', 'lat'] categs = ['movie', 'tvshow', 'documentary', 'anime', 'vos', 'direct', 'torrent'] if config.get_setting('adult_mode') > 0: categs.append('adult') for c in categs: preselecciones.append(config.get_localized_string(70577) + config.get_localized_category(c)) presel_values.append(c) if item.action == 'setting_channel': # Configuración de los canales incluídos en la búsqueda del preselecciones[0] del presel_values[0] # else: # Call from "search on other channels" (you can skip the selection and go directly to the search) ret = platformtools.dialog_select(config.get_localized_string(59994), preselecciones) if ret == -1: return False # order cancel if presel_values[ret] == 'skip': return True # continue unmodified elif presel_values[ret] == 'none': preselect = [] elif presel_values[ret] == 'all': preselect = list(range(len(ids))) elif presel_values[ret] in ['cast', 'lat']: preselect = [] for i, lg in enumerate(lista_lang): if presel_values[ret] in lg or '*' in lg: preselect.append(i) elif presel_values[ret] == 'actual': preselect = [] for i, canal in enumerate(ids): channel_status = config.get_setting('include_in_global_search', canal) if channel_status: preselect.append(i) elif presel_values[ret] == 'recom': preselect = [] for i, canal in enumerate(ids): _not, set_canal_list = channeltools.get_channel_controls_settings(canal) if set_canal_list.get('include_in_global_search', False): preselect.append(i) elif presel_values[ret] == 'freq': preselect = [] for i, canal in enumerate(ids): frequency = channeltools.get_channel_setting('frequency', canal, 0) if frequency > 0: preselect.append(i) else: preselect = [] for i, ctgs in enumerate(lista_ctgs): if presel_values[ret] in ctgs: preselect.append(i) # Dialog to select ret = xbmcgui.Dialog().multiselect(config.get_localized_string(59994), lista, preselect=preselect, useDetails=True) if not ret: return False # order cancel seleccionados = [ids[i] for i in ret] # Save changes to search channels for canal in ids: channel_status = config.get_setting('include_in_global_search', canal) if channel_status and canal not in seleccionados: config.set_setting('include_in_global_search', False, canal) elif not channel_status and canal in seleccionados: config.set_setting('include_in_global_search', True, canal) return True
def mainlist(item): logger.info() itemlist = list() itemlist.append(Item(channel=CHANNELNAME, title="Preferencias", action="settings", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) if config.get_setting("plugin_updates_available") == "0": nuevas = "" elif config.get_setting("plugin_updates_available") == "1": nuevas = " (1 nueva)" else: nuevas = " (" + config.get_setting("plugin_updates_available") + " nuevas)" thumb_configuracion = "thumb_configuracion_" + config.get_setting("plugin_updates_available") + ".png" itemlist.append(Item(channel=CHANNELNAME, title="Descargar e instalar otras versiones" + nuevas, action="get_all_versions", folder=True, thumbnail=get_thumbnail_path(thumb_configuracion))) itemlist.append(Item(channel=CHANNELNAME, title="", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append(Item(channel=CHANNELNAME, title="Ajustes especiales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append(Item(channel="novedades", title=" Ajustes de la sección 'Novedades'", action="menu_opciones", folder=True, thumbnail=get_thumbnail_path("thumb_novedades.png"))) itemlist.append(Item(channel="buscador", title=" Ajustes del buscador global", action="opciones", folder=True, thumbnail=get_thumbnail_path("thumb_buscar.png"))) itemlist.append(Item(channel=CHANNELNAME, title=" Ajustes de descargas", action="channel_config", config="descargas", folder=True, thumbnail=get_thumbnail_path("thumb_descargas.png"))) if config.get_library_support(): itemlist.append(Item(channel="biblioteca", title=" Ajustes de la biblioteca", action="channel_config", folder=True, thumbnail=get_thumbnail_path("thumb_biblioteca.png"))) itemlist.append(Item(channel="biblioteca", action="update_biblio", folder=False, thumbnail=get_thumbnail_path("thumb_biblioteca.png"), title=" Buscar nuevos episodios y actualizar biblioteca")) itemlist.append(Item(channel=CHANNELNAME, title=" Añadir o Actualizar canal/conector desde una URL", action="menu_addchannels")) itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append(Item(channel=CHANNELNAME, title="Activar/desactivar canales", action="conf_tools", folder=False, extra="channels_onoff", thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append(Item(channel=CHANNELNAME, title="Ajustes por canales", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) # Inicio - Canales configurables import channelselector from core import channeltools channel_list = channelselector.filterchannels("all") for channel in channel_list: channel_parameters = channeltools.get_channel_parameters(channel.channel) if channel_parameters["has_settings"]: itemlist.append(Item(channel=CHANNELNAME, title=" Configuración del canal '%s'" % channel.title, action="channel_config", config=channel.channel, folder=False, thumbnail=channel.thumbnail)) # Fin - Canales configurables itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) itemlist.append(Item(channel=CHANNELNAME, title="Otras herramientas", action="submenu_tools", folder=True, thumbnail=get_thumbnail_path("thumb_configuracion_0.png"))) return itemlist
def run(item): itemlist = [] # Muestra el item en el log: print_items(item) # Control Parental, comprueba si es adulto o no if item.action == "mainlist": # Parental control if channeltools.is_adult( item.channel) and config.get_setting("adult_request_password"): tecleado = platformtools.dialog_input( "", "Contraseña para canales de adultos", True) if tecleado is None or tecleado != config.get_setting( "adult_password"): platformtools.render_items(None, item) return channelmodule = None # Importa el canal para el item, todo item debe tener un canal, sino sale de la función if item.channel: channelmodule = import_channel(item) # If item has no action, stops here if item.action == "": logger.info("Item sin accion") itemlist = None # Action Play, para mostrar el menú con las opciones de reproduccion. elif item.action == "play": logger.info("play") # Si el canal tiene una acción "play" tiene prioridad if hasattr(channelmodule, 'play'): logger.info("executing channel 'play' method") itemlist = channelmodule.play(item) b_favourite = item.isFavourite if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True play_menu(item) elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist play_menu(item) else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") else: logger.info("no channel 'play' method, executing core method") play_menu(item) itemlist = None # Action Search, para mostrar el teclado y lanzar la busqueda con el texto indicado. elif item.action == "search": logger.info("search") tecleado = platformtools.dialog_input() if tecleado: itemlist = channelmodule.search(item, tecleado) else: itemlist = [] elif item.channel == "channelselector": import channelselector if item.action == "mainlist": itemlist = channelselector.getmainlist("banner_") if item.action == "getchanneltypes": itemlist = channelselector.getchanneltypes("banner_") if item.action == "filterchannels": itemlist = channelselector.filterchannels(item.channel_type, "banner_") elif item.action == "script": from core import tmdb if tmdb.drop_bd(): platformtools.dialog_notification("Alfa", "caché eliminada", time=2000, sound=False) # Todas las demas las intenta ejecturaren el siguiente orden: # 1. En el canal # 2. En el launcher # 3. Si no existe en el canal ni en el launcher guarda un error en el log else: # Si existe la funcion en el canal la ejecuta if hasattr(channelmodule, item.action): logger.info("Ejectuando accion: " + item.channel + "." + item.action + "(item)") exec "itemlist = channelmodule." + item.action + "(item)" # Si existe la funcion en el launcher la ejecuta elif hasattr(sys.modules[__name__], item.action): logger.info("Ejectuando accion: " + item.action + "(item)") exec "itemlist =" + item.action + "(item)" # Si no existe devuelve un error else: logger.info("No se ha encontrado la accion [" + item.action + "] en el canal [" + item.channel + "] ni en el launcher") # Llegados a este punto ya tenemos que tener el itemlist con los resultados correspondientes # Pueden darse 3 escenarios distintos: # 1. la función ha generado resultados y estan en el itemlist # 2. la función no ha generado resultados y por tanto el itemlist contiene 0 items, itemlist = [] # 3. la función realiza alguna accion con la cual no se generan nuevos items, en ese caso el resultado deve ser: itemlist = None para que no modifique el listado # A partir de aquí ya se ha ejecutado la funcion en el lugar adecuado, si queremos realizar alguna acción sobre los resultados, este es el lugar. # Filtrado de Servers if item.action == "findvideos": itemlist = servertools.filter_servers(itemlist) # Si la accion no ha devuelto ningún resultado, añade un item con el texto "No hay elementos para mostrar" if type(itemlist) == list: if len(itemlist) == 0: from channelselector import get_thumb itemlist = [ Item(title="No hay elementos para mostrar", thumbnail=get_thumb("error.png")) ] # Imprime en el log el resultado print_items(itemlist) # Muestra los resultados en pantalla platformtools.render_items(itemlist, item)
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 setting_channel_new(item): import channelselector, xbmcgui from core import channeltools # Cargar lista de opciones (canales activos del usuario y que permitan búsqueda global) # ------------------------ lista = [] ids = [] lista_lang = [] lista_ctgs = [] channels_list = channelselector.filterchannels('all') for channel in channels_list: if channel.action == '': continue channel_parameters = channeltools.get_channel_parameters( channel.channel) # No incluir si en la configuracion del canal no existe "include_in_global_search" if not channel_parameters['include_in_global_search']: continue lbl = '%s' % channel_parameters['language'] lbl += ' %s' % ', '.join( config.get_localized_category(categ) for categ in channel_parameters['categories']) it = xbmcgui.ListItem(channel.title, lbl) it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart}) lista.append(it) ids.append(channel.channel) lista_lang.append(channel_parameters['language']) lista_ctgs.append(channel_parameters['categories']) # Diálogo para pre-seleccionar # ---------------------------- preselecciones = [ 'Buscar con la selección actual', 'Modificar selección actual', 'Modificar partiendo de Frecuentes', 'Modificar partiendo de Todos', 'Modificar partiendo de Ninguno', 'Modificar partiendo de Castellano', 'Modificar partiendo de Latino' ] presel_values = ['skip', 'actual', 'freq', 'all', 'none', 'cast', 'lat'] categs = [ 'movie', 'tvshow', 'documentary', 'anime', 'vos', 'direct', 'torrent' ] if config.get_setting('adult_mode') > 0: categs.append('adult') for c in categs: preselecciones.append('Modificar partiendo de %s' % config.get_localized_category(c)) presel_values.append(c) if item.action == 'setting_channel': # Configuración de los canales incluídos en la búsqueda del preselecciones[0] del presel_values[0] #else: # Llamada desde "buscar en otros canales" (se puede saltar la selección e ir directo a la búsqueda) ret = platformtools.dialog_select(config.get_localized_string(59994), preselecciones) logger.debug(presel_values[ret]) if ret == -1: return False # pedido cancel if presel_values[ret] == 'skip': return True # continuar sin modificar elif presel_values[ret] == 'none': preselect = [] elif presel_values[ret] == 'all': preselect = range(len(ids)) elif presel_values[ret] in ['cast', 'lat']: preselect = [] for i, lg in enumerate(lista_lang): if presel_values[ret] in lg or '*' in lg: preselect.append(i) elif presel_values[ret] == 'actual': preselect = [] for i, canal in enumerate(ids): channel_status = config.get_setting('include_in_global_search', canal) if channel_status: preselect.append(i) elif presel_values[ret] == 'freq': preselect = [] for i, canal in enumerate(ids): logger.debug('el canal: %s' % canal) frequency = channeltools.get_channel_setting('frequency', canal, 0) if frequency > 0: logger.debug(ids) preselect.append(i) logger.debug(preselect) else: preselect = [] for i, ctgs in enumerate(lista_ctgs): if presel_values[ret] in ctgs: preselect.append(i) # Diálogo para seleccionar # ------------------------ ret = xbmcgui.Dialog().multiselect(config.get_localized_string(59994), lista, preselect=preselect, useDetails=True) if ret == None: return False # pedido cancel seleccionados = [ids[i] for i in ret] # Guardar cambios en canales para la búsqueda # ------------------------------------------- for canal in ids: channel_status = config.get_setting('include_in_global_search', canal) if channel_status is None: channel_status = True if channel_status and canal not in seleccionados: config.set_setting('include_in_global_search', False, canal) elif not channel_status and canal in seleccionados: config.set_setting('include_in_global_search', True, canal) return True
def mainlist(item): logger.info() itemlist = list() itemlist.append(Item(channel=CHANNELNAME, title="Preferenze", action="settings", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append(Item(channel=CHANNELNAME, title="", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append(Item(channel=CHANNELNAME, title="Impostazioni speciali", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append(Item(channel="novedades", title=" Impostazioni 'Novità'", action="menu_opciones", folder=True, thumbnail=get_thumbnail_path("thumb_novedades.png"))) itemlist.append(Item(channel="buscador", title=" Impostazioni della ricerca globale", action="opciones", folder=True, thumbnail=get_thumbnail_path("thumb_buscar.png"))) if config.get_library_support(): itemlist.append(Item(channel="biblioteca", title=" Impostazioni libreria", action="channel_config", folder=True, thumbnail=get_thumbnail_path("thumb_biblioteca.png"))) itemlist.append(Item(channel="biblioteca", action="update_biblio", folder=False, thumbnail=get_thumbnail_path("thumb_biblioteca.png"), title=" Recupera nuovi episodi e aggiorna la libreria")) itemlist.append(Item(channel=CHANNELNAME, title="Avvia aggiornamenti", action="check_for_updates", folder=False)) itemlist.append(Item(channel=item.channel, action="", title="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) itemlist.append(Item(channel=CHANNELNAME, title="Impostazioni canali", action="", folder=False, thumbnail=get_thumbnail_path("thumb_configuracion.png"))) import channelselector from core import channeltools channel_list = channelselector.filterchannels("all") for channel in channel_list: try: jsonchannel = channeltools.get_channel_json(channel.channel) except: continue if jsonchannel.get("settings"): setting = jsonchannel["settings"] if type(setting) == list: if len([s for s in setting if "id" in s and "include_in_" not in s["id"]]): active_status = None if config.get_setting("enabled", channel.channel): active_status = config.get_setting("enabled", channel.channel) else: channel_parameters = channeltools.get_channel_parameters(channel.channel) active_status = channel_parameters['active'] if active_status == "true": itemlist.append(Item(channel=CHANNELNAME, title=" Configurazione canale '%s'" % channel.title, action="channel_config", config=channel.channel, folder=False, thumbnail=channel.thumbnail)) return itemlist
def run(item=None): logger.info() if not item: # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: if config.get_setting("start_page"): if not config.get_setting("custom_start"): category = config.get_setting("category").lower() item = Item(channel="news", action="novedades", extra=category, mode = 'silent') else: from channels import side_menu item= Item() item = side_menu.check_user_home(item) item.start = True; else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): from platformcode import xbmc_videolibrary xbmc_videolibrary.ask_set_content(1) config.set_setting('show_once', True) logger.info(item.tostring()) try: if not config.get_setting('tmdb_active'): config.set_setting('tmdb_active', True) # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() elif item.action == "script": from core import tmdb if tmdb.drop_bd(): platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_request_password"): tecleado = platformtools.dialog_input("", config.get_localized_string(60334), True) if tecleado is None or tecleado != config.get_setting("adult_password"): return # # Actualiza el canal individual # if (item.action == "mainlist" and item.channel != "channelselector" and # config.get_setting("check_for_channel_updates") == True): # from core import updater # updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info("channel_file=%s" % channel_file) channel = None if os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec("import channels." + item.channel + " as channel") logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": #define la info para trakt try: trakt_tools.set_trakt_info(item) except: pass logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(60339)) # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) itemlist = servertools.filter_servers(itemlist) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) # last_search = "" # last_search_active = config.get_setting("last_search", "search") # if last_search_active: # try: # current_saved_searches_list = list(config.get_setting("saved_searches_list", "search")) # last_search = current_saved_searches_list[0] # except: # pass last_search = channeltools.get_channel_setting('Last_searched', 'search', '') tecleado = platformtools.dialog_input(last_search) if tecleado is not None: channeltools.set_channel_setting('Last_searched', tecleado, 'search') itemlist = channel.search(item, tecleado) else: return platformtools.render_items(itemlist, item) # For all other actions else: logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) if config.get_setting('trakt_sync'): token_auth = config.get_setting("token_trakt", "trakt") if not token_auth: trakt_tools.auth_trakt() else: import xbmc if not xbmc.getCondVisibility('System.HasAddon(script.trakt)') and config.get_setting( 'install_trakt'): trakt_tools.ask_install_script() itemlist = trakt_tools.trakt_check(itemlist) else: config.set_setting('install_trakt', True) platformtools.render_items(itemlist, item) except urllib2.URLError as e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.error("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("alfa", texto) # Grab server response errors elif hasattr(e, 'code'): logger.error("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("alfa", config.get_localized_string(30051) % e.code) except WebErrorException as e: import traceback logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + '([^.]+)\.py"' canal = scrapertools.find_single_match(traceback.format_exc(), patron) platformtools.dialog_ok( config.get_localized_string(59985) + canal, config.get_localized_string(60013) %(e)) except: import traceback logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + '([^.]+)\.py"' canal = scrapertools.find_single_match(traceback.format_exc(), patron) try: import xbmc if config.get_platform(True)['num_version'] < 14: log_name = "xbmc.log" else: log_name = "kodi.log" log_message = config.get_localized_string(50004) + xbmc.translatePath("special://logpath") + log_name except: log_message = "" if canal: platformtools.dialog_ok( config.get_localized_string(60087) %canal, config.get_localized_string(60014), log_message) else: platformtools.dialog_ok( config.get_localized_string(60038), config.get_localized_string(60015), log_message)
def run(item): itemlist = [] #Muestra el item en el log: PrintItems(item) #Control Parental, comprueba si es adulto o no if item.action=="mainlist": # Parental control if channeltools.is_adult(item.channel) and config.get_setting("adult_pin")!="": tecleado = platformtools.dialog_input("","PIN para canales de adultos",True) if not tecleado==config.get_setting("adult_pin"): return #Importa el canal para el item, todo item debe tener un canal, sino sale de la función if item.channel: channelmodule = ImportarCanal(item) # If item has no action, stops here if item.action == "": logger.info("pelisalacarta.platformcode.launcher Item sin accion") itemlist = None #Action Play, para mostrar el menú con las opciones de reproduccion. elif item.action=="play": logger.info("pelisalacarta.platformcode.launcher play") # Si el canal tiene una acción "play" tiene prioridad if hasattr(channelmodule, 'play'): logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method") itemlist = channelmodule.play(item) b_favourite = item.isFavourite if len(itemlist)>0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True play_menu(item) elif len(itemlist)>0 and isinstance(itemlist[0], list): item.video_urls = itemlist play_menu(item) else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") else: logger.info("pelisalacarta.platformcode.launcher no channel 'play' method, executing core method") play_menu(item) itemlist = None #Action Search, para mostrar el teclado y lanzar la busqueda con el texto indicado. elif item.action=="search": logger.info("pelisalacarta.platformcode.launcher search") tecleado = platformtools.dialog_input() if not tecleado is None: itemlist = channelmodule.search(item,tecleado) else: itemlist = [] elif item.channel == "channelselector": import channelselector if item.action =="mainlist": itemlist = channelselector.getmainlist("bannermenu") if config.get_setting("check_for_plugin_updates") == "true": logger.info("channelselector.mainlist Verificar actualizaciones activado") from core import updater try: version = updater.checkforupdates() if version: platformtools.dialog_ok("Versión "+version+" disponible","Ya puedes descargar la nueva versión del plugin\ndesde el listado principal") itemlist.insert(0,Item(title="Actualizadr pelisalacarta a la versión "+version, version=version, channel="updater", action="update", thumbnail=os.path.join(config.get_runtime_path(),"resources","images","bannermenu","thumb_update.png"))) except: platformtools.dialog_ok("No se puede conectar","No ha sido posible comprobar","si hay actualizaciones") logger.info("channelselector.mainlist Fallo al verificar la actualización") else: logger.info("channelselector.mainlist Verificar actualizaciones desactivado") if item.action =="getchanneltypes": itemlist = channelselector.getchanneltypes("bannermenu") if item.action =="filterchannels": itemlist = channelselector.filterchannels(item.channel_type, "bannermenu") #Todas las demas las intenta ejecturaren el siguiente orden: # 1. En el canal # 2. En el launcher # 3. Si no existe en el canal ni en el launcher guarda un error en el log else: #Si existe la funcion en el canal la ejecuta if hasattr(channelmodule, item.action): logger.info("Ejectuando accion: " + item.channel + "." + item.action + "(item)") exec "itemlist = channelmodule." + item.action + "(item)" #Si existe la funcion en el launcher la ejecuta elif hasattr(sys.modules[__name__], item.action): logger.info("Ejectuando accion: " + item.action + "(item)") exec "itemlist =" + item.action + "(item)" #Si no existe devuelve un error else: logger.info("No se ha encontrado la accion ["+ item.action + "] en el canal ["+item.channel+"] ni en el launcher") #Llegados a este punto ya tenemos que tener el itemlist con los resultados correspondientes #Pueden darse 3 escenarios distintos: # 1. la función ha generado resultados y estan en el itemlist # 2. la función no ha generado resultados y por tanto el itemlist contiene 0 items, itemlist = [] # 3. la función realiza alguna accion con la cual no se generan nuevos items, en ese caso el resultado deve ser: itemlist = None para que no modifique el listado #A partir de aquí ya se ha ejecutado la funcion en el lugar adecuado, si queremos realizar alguna acción sobre los resultados, este es el lugar. #Filtrado de Servers if item.action== "findvideos" and config.get_setting('filter_servers') == 'true': server_white_list, server_black_list = set_server_list() itemlist = filtered_servers(itemlist, server_white_list, server_black_list) #Si la accion no ha devuelto ningún resultado, añade un item con el texto "No hay elementos para mostrar" if type(itemlist)==list: if len(itemlist) ==0: itemlist = [Item(title="No hay elementos para mostrar", thumbnail="http://media.tvalacarta.info/pelisalacarta/thumb_error.png")] #Imprime en el log el resultado PrintItems(itemlist) #Muestra los resultados en pantalla platformtools.render_items(itemlist, item)
def run(item): itemlist = [] #Muestra el item en el log: PrintItems(item) #Control Parental, comprueba si es adulto o no if item.action == "mainlist": # Parental control if channeltools.is_adult( item.channel) and config.get_setting("adult_pin") != "": tecleado = platformtools.dialog_input( "", "PIN para canales de adultos", True) if not tecleado == config.get_setting("adult_pin"): return #Importa el canal para el item, todo item debe tener un canal, sino sale de la función if item.channel: channelmodule = ImportarCanal(item) # If item has no action, stops here if item.action == "": logger.info("pelisalacarta.platformcode.launcher Item sin accion") itemlist = None #Action Play, para mostrar el menú con las opciones de reproduccion. elif item.action == "play": logger.info("pelisalacarta.platformcode.launcher play") # Si el canal tiene una acción "play" tiene prioridad if hasattr(channelmodule, 'play'): logger.info( "pelisalacarta.platformcode.launcher executing channel 'play' method" ) itemlist = channelmodule.play(item) b_favourite = item.isFavourite if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True play_menu(item) elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist play_menu(item) else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") else: logger.info( "pelisalacarta.platformcode.launcher no channel 'play' method, executing core method" ) play_menu(item) itemlist = None #Action Search, para mostrar el teclado y lanzar la busqueda con el texto indicado. elif item.action == "search": logger.info("pelisalacarta.platformcode.launcher search") tecleado = platformtools.dialog_input() if not tecleado is None: itemlist = channelmodule.search(item, tecleado) else: itemlist = [] elif item.channel == "channelselector": import channelselector if item.action == "mainlist": itemlist = channelselector.getmainlist("bannermenu") if config.get_setting("check_for_plugin_updates") == "true": logger.info( "channelselector.mainlist Verificar actualizaciones activado" ) from core import updater try: version = updater.checkforupdates() if version: platformtools.dialog_ok( "Versión " + version + " disponible", "Ya puedes descargar la nueva versión del plugin\ndesde el listado principal" ) itemlist.insert( 0, Item( title="Actualizadr pelisalacarta a la versión " + version, version=version, channel="updater", action="update", thumbnail=os.path.join( config.get_runtime_path(), "resources", "images", "bannermenu", "thumb_update.png"))) except: platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar", "si hay actualizaciones") logger.info( "channelselector.mainlist Fallo al verificar la actualización" ) else: logger.info( "channelselector.mainlist Verificar actualizaciones desactivado" ) if item.action == "getchanneltypes": itemlist = channelselector.getchanneltypes("bannermenu") if item.action == "filterchannels": itemlist = channelselector.filterchannels(item.channel_type, "bannermenu") #Todas las demas las intenta ejecturaren el siguiente orden: # 1. En el canal # 2. En el launcher # 3. Si no existe en el canal ni en el launcher guarda un error en el log else: #Si existe la funcion en el canal la ejecuta if hasattr(channelmodule, item.action): logger.info("Ejectuando accion: " + item.channel + "." + item.action + "(item)") exec "itemlist = channelmodule." + item.action + "(item)" #Si existe la funcion en el launcher la ejecuta elif hasattr(sys.modules[__name__], item.action): logger.info("Ejectuando accion: " + item.action + "(item)") exec "itemlist =" + item.action + "(item)" #Si no existe devuelve un error else: logger.info("No se ha encontrado la accion [" + item.action + "] en el canal [" + item.channel + "] ni en el launcher") #Llegados a este punto ya tenemos que tener el itemlist con los resultados correspondientes #Pueden darse 3 escenarios distintos: # 1. la función ha generado resultados y estan en el itemlist # 2. la función no ha generado resultados y por tanto el itemlist contiene 0 items, itemlist = [] # 3. la función realiza alguna accion con la cual no se generan nuevos items, en ese caso el resultado deve ser: itemlist = None para que no modifique el listado #A partir de aquí ya se ha ejecutado la funcion en el lugar adecuado, si queremos realizar alguna acción sobre los resultados, este es el lugar. #Filtrado de Servers if item.action == "findvideos" and config.get_setting( 'filter_servers') == 'true': server_white_list, server_black_list = set_server_list() itemlist = filtered_servers(itemlist, server_white_list, server_black_list) #Si la accion no ha devuelto ningún resultado, añade un item con el texto "No hay elementos para mostrar" if type(itemlist) == list: if len(itemlist) == 0: itemlist = [ Item( title="No hay elementos para mostrar", thumbnail= "http://media.tvalacarta.info/pelisalacarta/thumb_error.png" ) ] #Imprime en el log el resultado PrintItems(itemlist) #Muestra los resultados en pantalla platformtools.render_items(itemlist, item)
def get_next_items( item ): plugintools.log("navigation.get_next_items item="+item.tostring()) try: # ---------------------------------------------------------------- # Main menu # ---------------------------------------------------------------- if item.channel=="navigation": 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+")") 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("pelisalacarta.platformcode.launcher 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("pelisalacarta.platformcode.launcher 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("pelisalacarta.platformcode.launcher 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" )) ] 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 setting_channel_new(item): import channelselector, xbmcgui from core import channeltools # Cargar lista de opciones (canales activos del usuario y que permitan búsqueda global) # ------------------------ lista = [] ids = [] lista_lang = [] channels_list = channelselector.filterchannels('all') for channel in channels_list: channel_parameters = channeltools.get_channel_parameters( channel.channel) # No incluir si en la configuracion del canal no existe "include_in_global_search" if not channel_parameters['include_in_global_search']: continue lbl = '%s' % channel_parameters['language'] lbl += ' %s' % ', '.join( config.get_localized_category(categ) for categ in channel_parameters['categories']) it = xbmcgui.ListItem(channel.title, lbl) it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart}) lista.append(it) ids.append(channel.channel) lista_lang.append(channel_parameters['language']) # Diálogo para pre-seleccionar # ---------------------------- preselecciones_std = [ 'Modificar selección actual', 'Modificar partiendo de Todos', 'Modificar partiendo de Ninguno', 'Modificar partiendo de Castellano', 'Modificar partiendo de Latino' ] if item.action == 'setting_channel': # Configuración de los canales incluídos en la búsqueda preselecciones = preselecciones_std presel_values = [1, 2, 3, 4, 5] else: # Llamada desde "buscar en otros canales" (se puede saltar la selección e ir directo a la búsqueda) preselecciones = ['Buscar con la selección actual' ] + preselecciones_std presel_values = [0, 1, 2, 3, 4, 5] ret = platformtools.dialog_select(config.get_localized_string(59994), preselecciones) if ret == -1: return False # pedido cancel if presel_values[ret] == 0: return True # continuar sin modificar elif presel_values[ret] == 3: preselect = [] elif presel_values[ret] == 2: preselect = range(len(ids)) elif presel_values[ret] in [4, 5]: busca = 'cast' if presel_values[ret] == 4 else 'lat' preselect = [] for i, lg in enumerate(lista_lang): if busca in lg or '*' in lg: preselect.append(i) else: preselect = [] for i, canal in enumerate(ids): channel_status = config.get_setting('include_in_global_search', canal) if channel_status: preselect.append(i) # Diálogo para seleccionar # ------------------------ ret = xbmcgui.Dialog().multiselect(config.get_localized_string(59994), lista, preselect=preselect, useDetails=True) if ret == None: return False # pedido cancel seleccionados = [ids[i] for i in ret] # Guardar cambios en canales para la búsqueda # ------------------------------------------- for canal in ids: channel_status = config.get_setting('include_in_global_search', canal) if channel_status is None: channel_status = True if channel_status and canal not in seleccionados: config.set_setting('include_in_global_search', False, canal) elif not channel_status and canal in seleccionados: config.set_setting('include_in_global_search', True, canal) return True
def run(): logger.info("pelisalacarta.platformcode.launcher run") # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(action="selectchannel", viewmode="movie") logger.info("pelisalacarta.platformcode.launcher "+item.tostring()) # Set server filters server_white_list = [] server_black_list = [] if config.get_setting('filter_servers') == 'true': server_white_list, server_black_list = set_server_list() try: # If item has no action, stops here if item.action == "": logger.info("pelisalacarta.platformcode.launcher Item sin accion") return # Action for main menu in channelselector if ( item.action=="selectchannel" ): import channelselector itemlist = channelselector.getmainlist() # Check for updates only on first screen if config.get_setting("updatecheck2") == "true": logger.info("pelisalacarta.platformcode.launcher Check for plugin updates enabled") from core import updater try: version = updater.checkforupdates() if version: import xbmcgui advertencia = xbmcgui.Dialog() advertencia.ok("Versión "+version+" disponible","Ya puedes descargar la nueva versión del plugin\ndesde el listado principal") itemlist.insert(0,Item(title="Descargar version "+version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png")) except: import xbmcgui advertencia = xbmcgui.Dialog() advertencia.ok("No se puede conectar","No ha sido posible comprobar","si hay actualizaciones") logger.info("cpelisalacarta.platformcode.launcher Fallo al verificar la actualización") else: logger.info("pelisalacarta.platformcode.launcher Check for plugin updates disabled") xbmctools.renderItems(itemlist, item) # Action for updating plugin elif (item.action=="update"): from core import updater updater.update(item) if config.get_system_platform()!="xbox": import xbmc xbmc.executebuiltin( "Container.Refresh" ) # Action for channel types on channelselector: movies, series, etc. elif (item.action=="channeltypes"): import channelselector itemlist = channelselector.getchanneltypes() xbmctools.renderItems(itemlist, item) # Action for channel listing on channelselector elif (item.action=="listchannels"): import channelselector itemlist = channelselector.filterchannels(item.category) xbmctools.renderItems(itemlist, item) # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action=="mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_pin")!="": 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 # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py") logger.info("pelisalacarta.platformcode.launcher channel_file=%s" % channel_file) if item.channel in ["personal","personal2","personal3","personal4","personal5"]: import channels.personal as channel elif os.path.exists(channel_file): channel = __import__('channels.%s' % item.channel, fromlist=["channels.%s" % item.channel]) logger.info("pelisalacarta.platformcode.launcher running channel {0} {1}".format(channel.__name__, channel.__file__)) # Special play action if item.action == "play": logger.info("pelisalacarta.platformcode.launcher play") # Mark as watched item on Library channel id_video = 0 category = '' if 'infoLabels' in item: if 'episodeid' in item.infoLabels and item.infoLabels['episodeid']: category = 'Series' id_video = item.infoLabels['episodeid'] elif 'movieid' in item.infoLabels and item.infoLabels['movieid']: category = 'Movies' id_video = item.infoLabels['movieid'] # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method") itemlist = channel.play(item) # Play should return a list of playable URLS if len(itemlist) > 0: item = itemlist[0] xbmctools.play_video(item) if id_video != 0: library.mark_as_watched(category, id_video) # If not, shows user an error message else: import xbmcgui ventana_error = xbmcgui.Dialog() ok = ventana_error.ok("plugin", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from xbmctools else: logger.info("pelisalacarta.platformcode.launcher executing core 'play' method") xbmctools.play_video(item) if id_video != 0: library.mark_as_watched(category, id_video) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist, server_white_list, server_black_list) # If not, uses the generic findvideos function else: logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist, server_white_list, server_black_list) # Copy infolabels from parent item if 'infoLabels' in item: # All but title if 'title' in item.infoLabels: item.infoLabels.pop('title') new_itemlist = itemlist[:] itemlist = [] for i in new_itemlist: itemlist.append(i.clone(infoLabels=item.infoLabels)) from platformcode import subtitletools subtitletools.saveSubtitleName(item) # Show xbmc items as "movies", so plot is visible import xbmcplugin handle = sys.argv[1] xbmcplugin.setContent(int( handle ),"movies") # Add everything to XBMC item list if type(itemlist) == list and itemlist: xbmctools.renderItems(itemlist, item) # If not, it shows an empty list # FIXME: Aquí deberíamos mostrar alguna explicación del tipo "No hay elementos, esto pasa por bla bla bla" else: xbmctools.renderItems([], item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item, channel, server_white_list, server_black_list) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": downloadtools.download_all_episodes(item, channel) # Special action for searching, first asks for the words then call the "search" function elif item.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, item) # For all other actions else: logger.info("pelisalacarta.platformcode.launcher executing channel '"+item.action+"' method") itemlist = getattr(channel, item.action)(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 if type(itemlist) == list and itemlist: xbmctools.renderItems(itemlist, item) # If not, it shows an empty list # FIXME: Aquí deberíamos mostrar alguna explicación del tipo "No hay elementos, esto pasa por bla bla bla" else: xbmctools.renderItems([], item) except urllib2.URLError,e: import traceback logger.error("pelisalacarta.platformcode.launcher "+traceback.format_exc()) import xbmcgui ventana_error = xbmcgui.Dialog() # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("pelisalacarta.platformcode.launcher Razon del error, codigo: {0}, Razon: {1}".format(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) # Grab server response errors elif hasattr(e,'code'): logger.info("pelisalacarta.platformcode.launcher 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 get_next_items( item ): plugintools.log("navigation.get_next_items item="+item.tostring()) try: # ---------------------------------------------------------------- # Main menu # ---------------------------------------------------------------- if item.channel=="navigation": 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+")") 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("navigation.get_next_items play 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, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot) except: pass else: import xbmcgui ventana_error = xbmcgui.Dialog() ok = ventana_error.ok ("plugin", "No hay nada para reproducir") else: plugintools.log("navigation.get_next_items play 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, hasContentDetails=item.hasContentDetails, contentTitle=item.contentTitle, contentThumbnail=item.contentThumbnail, contentPlot=item.contentPlot) 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("navigation.get_next_items play 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" )) ] 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