def findvideos(item): logger.info() # logger.debug("item:\n" + item.tostring('\n')) itemlist = [] list_canales = {} item_local = None if not item.contentTitle or not item.strm_path: logger.debug("No se pueden buscar videos por falta de parametros") return [] content_title = filter(lambda c: c not in ":*?<>|\/", item.contentTitle.strip().lower()) if item.contentType == 'movie': item.strm_path = filetools.join(videolibrarytools.MOVIES_PATH, item.strm_path) path_dir = os.path.dirname(item.strm_path) item.nfo = filetools.join(path_dir, os.path.basename(path_dir) + ".nfo") else: item.strm_path = filetools.join(videolibrarytools.TVSHOWS_PATH, item.strm_path) path_dir = os.path.dirname(item.strm_path) item.nfo = filetools.join(path_dir, 'tvshow.nfo') for fd in filetools.listdir(path_dir): if fd.endswith('.json'): contenido, nom_canal = fd[:-6].split('[') if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in \ list_canales.keys(): list_canales[nom_canal] = filetools.join(path_dir, fd) num_canales = len(list_canales) # logger.debug(str(list_canales)) if 'downloads' in list_canales: json_path = list_canales['downloads'] item_json = Item().fromjson(filetools.read(json_path)) item_json.contentChannel = "local" # Soporte para rutas relativas en descargas if filetools.is_relative(item_json.url): item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH, item_json.url) del list_canales['downloads'] # Comprobar q el video no haya sido borrado if filetools.exists(item_json.url): item_local = item_json.clone(action='play') itemlist.append(item_local) else: num_canales -= 1 filtro_canal = '' if num_canales > 1 and config.get_setting("ask_channel", "videolibrary"): opciones = [ "Mostrar solo los enlaces de %s" % k.capitalize() for k in list_canales.keys() ] opciones.insert(0, "Mostrar todos los enlaces") if item_local: opciones.append(item_local.title) from platformcode import platformtools index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index < 0: return [] elif item_local and index == len(opciones) - 1: filtro_canal = 'downloads' platformtools.play_video(item_local) elif index > 0: filtro_canal = opciones[index].replace( "Mostrar solo los enlaces de ", "") itemlist = [] for nom_canal, json_path in list_canales.items(): if filtro_canal and filtro_canal != nom_canal.capitalize(): continue # Importamos el canal de la parte seleccionada try: channel = __import__('channels.%s' % nom_canal, fromlist=["channels.%s" % nom_canal]) except ImportError: exec "import channels." + nom_canal + " as channel" item_json = Item().fromjson(filetools.read(json_path)) list_servers = [] try: # FILTERTOOLS # si el canal tiene filtro se le pasa el nombre que tiene guardado para que filtre correctamente. if "list_language" in item_json: # si se viene desde la videoteca del addon if "library_filter_show" in item: item_json.show = item.library_filter_show.get( nom_canal, "") # Ejecutamos find_videos, del canal o común item_json.contentChannel = 'videolibrary' if hasattr(channel, 'findvideos'): from core import servertools list_servers = getattr(channel, 'findvideos')(item_json) list_servers = servertools.filter_servers(list_servers) else: from core import servertools list_servers = servertools.find_video_items(item_json) except Exception, ex: logger.error("Ha fallado la funcion findvideos para el canal %s" % nom_canal) template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) # Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y # las infoLabels y las imagenes del item si el server no tiene for server in list_servers: if not server.action: # Ignorar las etiquetas continue server.contentChannel = server.channel server.channel = "videolibrary" server.nfo = item.nfo server.strm_path = item.strm_path # Se añade el nombre del canal si se desea if config.get_setting("quit_channel_name", "videolibrary") == 0: server.title = "%s: %s" % (nom_canal.capitalize(), server.title) server.infoLabels = item_json.infoLabels if not server.thumbnail: server.thumbnail = item.thumbnail # logger.debug("server:\n%s" % server.tostring('\n')) itemlist.append(server)
def get_links(list_item, item, list_language, list_quality=None, global_filter_lang_id="filter_languages"): """ Returns a list of filtered links. @param list_item: list of links @type list_item: list[Item] @param item: element to filter @type item: item @param list_language: list of possible languages @type list_language: list[str] @param list_quality: list of possible qualities @type list_quality: list[str] @param global_filter_lang_id: id of the filtering variable by language that is in settings @type global_filter_lang_id: str @return: lista de Item @rtype: list[Item] """ logger.info() # if the required fields are None we leave if list_item is None or item is None: return [] # if list_item is empty we go back, no platform validation is added so Plex can do global filter if len(list_item) == 0: return list_item second_lang = config.get_setting('second_language') # Sort by favorite servers, delete blacklist servers and disabled from core import servertools list_item= servertools.filter_servers(list_item) logger.debug("total de items : %s" % len(list_item)) new_itemlist = [] quality_count = 0 language_count = 0 _filter = Filter(item, global_filter_lang_id).result logger.debug("filter: '%s' datos: '%s'" % (item.show, _filter)) if _filter and _filter.active: for item in list_item: new_itemlist, quality_count, language_count, first_lang = check_conditions(_filter, new_itemlist, item, list_language, list_quality, quality_count, language_count) #2nd lang if second_lang and second_lang != 'No' and first_lang.lower() != second_lang.lower() : second_list= [] _filter2 = _filter _filter2.language = second_lang for it in new_itemlist: if isinstance(it.language, list): if not second_lang in it.language: second_list.append(it) else: second_list = new_itemlist break for item in list_item: new_itemlist, quality_count, language_count, second_lang = check_conditions(_filter2, second_list, item, list_language, list_quality, quality_count, language_count) logger.debug("FILTERED ITEMS: %s/%s, language [%s]: %s, allowed quality %s: %s" % (len(new_itemlist), len(list_item), _filter.language, language_count, _filter.quality_allowed, quality_count)) if len(new_itemlist) == 0: list_item_all = [] for i in list_item: list_item_all.append(i.tourl()) _context = [{"title": config.get_localized_string(60430) % _filter.language, "action": "delete_from_context", "channel": "filtertools", "to_channel": item.channel}] if _filter.quality_allowed: msg_quality_allowed = " y calidad %s" % _filter.quality_allowed else: msg_quality_allowed = "" msg_lang = ' %s' % first_lang.upper() if second_lang and second_lang != 'No': msg_lang = 's %s ni %s' % (first_lang.upper(), second_lang.upper()) new_itemlist.append(Item(channel=__channel__, action="no_filter", list_item_all=list_item_all, show=item.show, title=config.get_localized_string(60432) % (_filter.language, msg_quality_allowed), context=_context)) else: for item in list_item: item.list_language = list_language if list_quality: item.list_quality = list_quality item.context = context(item) new_itemlist = list_item return new_itemlist
def get_links(list_item, item, list_language, list_quality=None, global_filter_lang_id="filter_languages"): """ Devuelve una lista de enlaces filtrados. @param list_item: lista de enlaces @type list_item: list[Item] @param item: elemento a filtrar @type item: item @param list_language: listado de idiomas posibles @type list_language: list[str] @param list_quality: listado de calidades posibles @type list_quality: list[str] @param global_filter_lang_id: id de la variable de filtrado por idioma que está en settings @type global_filter_lang_id: str @return: lista de Item @rtype: list[Item] """ logger.info() # si los campos obligatorios son None salimos if list_item is None or item is None: return [] # si list_item está vacío volvemos, no se añade validación de plataforma para que Plex pueda hacer filtro global if len(list_item) == 0: return list_item second_lang = config.get_setting('second_language') #Ordena segun servidores favoritos, elima servers de blacklist y desactivados from core import servertools list_item= servertools.filter_servers(list_item) logger.debug("total de items : %s" % len(list_item)) new_itemlist = [] quality_count = 0 language_count = 0 _filter = Filter(item, global_filter_lang_id).result logger.debug("filter: '%s' datos: '%s'" % (item.show, _filter)) if _filter and _filter.active: for item in list_item: new_itemlist, quality_count, language_count, first_lang = check_conditions(_filter, new_itemlist, item, list_language, list_quality, quality_count, language_count) #2nd lang if second_lang and second_lang != 'No' and first_lang.lower() != second_lang.lower() : second_list= [] _filter2 = _filter _filter2.language = second_lang for it in new_itemlist: if isinstance(it.language, list): if not second_lang in it.language: second_list.append(it) else: second_list = new_itemlist break for item in list_item: new_itemlist, quality_count, language_count, second_lang = check_conditions(_filter2, second_list, item, list_language, list_quality, quality_count, language_count) logger.debug("ITEMS FILTRADOS: %s/%s, idioma [%s]: %s, calidad_permitida %s: %s" % (len(new_itemlist), len(list_item), _filter.language, language_count, _filter.quality_allowed, quality_count)) if len(new_itemlist) == 0: list_item_all = [] for i in list_item: list_item_all.append(i.tourl()) _context = [{"title": "FILTRO: Borrar '%s'" % _filter.language, "action": "delete_from_context", "channel": "filtertools", "to_channel": item.channel}] if _filter.quality_allowed: msg_quality_allowed = " y calidad %s" % _filter.quality_allowed else: msg_quality_allowed = "" msg_lang = ' %s' % first_lang.upper() if second_lang and second_lang != 'No': msg_lang = 's %s ni %s' % (first_lang.upper(), second_lang.upper()) new_itemlist.append(Item(channel=__channel__, action="no_filter", list_item_all=list_item_all, show=item.show, title="[COLOR %s]No hay elementos con idioma%s%s, pulsa para mostrar " "sin filtro[/COLOR]" % (COLOR.get("error", "auto"), msg_lang, msg_quality_allowed), context=_context)) else: for item in list_item: item.list_language = list_language if list_quality: item.list_quality = list_quality item.context = context(item) new_itemlist = list_item return new_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 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("Alfa", "caché eliminada", 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( "", "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": #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("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) 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 run(item=None): logger.info() if not item: # Extract item from sys.argv if sys.argv[2]: sp = sys.argv[2].split('&') url = sp[0] item = Item().fromurl(url) if len(sp) > 1: for e in sp[1:]: key, val = e.split('=') item.__setattr__(key, val) # If no item, this is mainlist else: if config.get_setting("start_page"): if not config.get_setting("custom_start"): category = config.get_setting("category") if isinstance(category, int): category = config.get_localized_string( config.get_setting("category")).lower() item = Item(channel="news", action="news", news=category.lower(), startpage=True) else: from channels import side_menu item = Item() item = side_menu.check_user_home(item) item.startpage = True else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): from platformcode import configurator configurator.show_window() logger.info(item.tostring()) # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Cleans infoLabels["playcount"] if set by generictools if item.video_path: item.infoLabels["playcount"] = 1 del item.infoLabels["playcount"] try: if not config.get_setting('tmdb_active'): config.set_setting('tmdb_active', True) # Special action for playing a video from the library if item.action == "play_from_library": play_from_library(item) return elif item.channel == 'channelselector': import channelselector # Action for addon install on channelselector if item.action == "install_alfa": channelselector.install_alfa() else: # Action for main menu in channelselector if item.action == "getmainlist": itemlist = channelselector.getmainlist() # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": itemlist = channelselector.getchanneltypes() # Action for channel listing on channelselector elif item.action == "filterchannels": itemlist = channelselector.filterchannels( item.channel_type) platformtools.render_items(itemlist, item) 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) elif item.action == "function": """ { "action": "function", "folder": "lib", "function": "alfa_assistant", "method": "install_alfa_assistant", "options": "auto" } """ # Checks if function file exists function_file = os.path.join(config.get_runtime_path(), item.folder, item.function + ".py") logger.info("function_file=%s" % function_file) function = None if os.path.exists(function_file): try: function = __import__( '%s.%s' % (item.folder, item.function), None, None, ["%s.%s" % (item.folder, item.function)]) except ImportError: exec("import %s." + item.function + " as function") logger.info( "Running function %s(%s) | %s" % (function.__name__, item.options, function.__file__)) getattr(function, item.method)(item.options) else: logger.error( "ERROR Running function %s(%s) | %s" % (function.__name__, item.options, function.__file__)) # 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__)) if item.channel == "test" and item.contentChannel: if item.parameters == "test_channel": getattr(channel, item.action)(item.contentChannel) # Calls redirection if Alfavorites findvideos, episodios, seasons if item.context and 'alfavorites' in str(item.context) \ and item.action in ['findvideos', 'episodios', 'seasons', 'play']: try: from lib import generictools item, it, overwrite = generictools.redirect_clone_newpct1( item) except: import traceback logger.error(traceback.format_exc()) # 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: if "http" not in tecleado: 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) elif not config.get_setting('install_trakt'): 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: if config.get_platform(True)['num_version'] < 14: log_name = "xbmc.log" else: log_name = "kodi.log" log_message = config.get_localized_string( 50004) + config.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( "", "Contraseña para canales de adultos", True) if tecleado is None or tecleado != config.get_setting("adult_pin"): platformtools.render_items(None, item) 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("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 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("Fallo al verificar la actualización") else: logger.info("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": 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: 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: 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( "", config.get_localized_string(60334), 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 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 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) # 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 # 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("", "Contraseña para canales de adultos", True) if tecleado is None or tecleado != config.get_setting("adult_pin"): 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 canal(channel_name="", action="", id=None, caller_item_serialized=None, itemlist=""): global LAST_ID global LAST_RESULT if id == LAST_ID and LAST_RESULT: return LAST_RESULT LAST_ID = id oc = ObjectContainer(view_group="List") try: if caller_item_serialized is None: Log.Info("caller_item_serialized=None") caller_item = Item() else: Log.Info("caller_item_serialized=" + caller_item_serialized) caller_item = Item() caller_item.fromurl(caller_item_serialized) Log.Info("caller_item=" + str(caller_item)) Log.Info("Importando...") channelmodule = channeltools.get_channel_module(channel_name) Log.Info("Importado") Log.Info("Antes de hasattr") if hasattr(channelmodule, action): Log.Info("El módulo " + caller_item.channel + " tiene una funcion " + action) itemlist = getattr(channelmodule, action)(caller_item) if action == "findvideos": itemlist = servertools.filter_servers(itemlist) if action == "play" and len(itemlist) > 0 and isinstance( itemlist[0], Item): itemlist = play_video(itemlist[0]) if action == "play" and len(itemlist) > 0 and isinstance( itemlist[0], list): item.video_urls = itemlist itemlist = play_video(item) else: Log.Info("El módulo " + caller_item.channel + " *NO* tiene una funcion " + action) if action == "findvideos": Log.Info("Llamando a la funcion findvideos comun") itemlist = findvideos(caller_item) elif action == "play": itemlist = play_video(caller_item) elif action == "menu_principal": LAST_RESULT = mainlist() return LAST_RESULT Log.Info("Tengo un itemlist con %d elementos" % len(itemlist)) for item in itemlist: if item.action == "search" and item.thumbnail == "": item.thumbnail = "http://media.tvalacarta.info/pelisalacarta/squares/thumb_buscar.png" try: Log.Info("item=" + unicode(item.tostring(), "utf-8", errors="replace")) except: pass if action != "play": #if "type" in item and item.type == "input": if item.action == "control_text_click" or item.action == "search": Log.Info("Canal: item tipo input") if 'value' in item: value = item.value else: value = "" if Client.Product in DumbKeyboard.clients: DumbKeyboard("/video/pelisalacarta", oc, get_input, dktitle=unicode(item.title, "utf-8", errors="replace"), dkitem=item, dkplaceholder=value, dkthumb=item.thumbnail) else: dkitem = item.tourl() oc.add( InputDirectoryObject(key=Callback(get_input, dkitem=dkitem), title=unicode( item.title, "utf-8", errors="replace"), prompt=value, thumb=item.thumbnail)) else: import random id = "%032x" % (random.getrandbits(128)) oc.add( DirectoryObject(key=Callback( canal, channel_name=item.channel, action=item.action, id=id, caller_item_serialized=item.tourl()), title=unicode(item.title, "utf-8", errors="replace"), thumb=item.thumbnail)) else: Log.Info("Llamando a la funcion play comun") videoClipObject = VideoClipObject( title=unicode(item.title, "utf-8", errors="replace"), thumb=item.thumbnail, url="pelisalacarta://" + item.url) oc.add(videoClipObject) except: Log.Info("Excepcion al ejecutar " + channel_name + "." + action) import traceback Log.Info("Detalles: " + traceback.format_exc()) LAST_RESULT = oc return oc
def findvideos(item): from channels import autoplay logger.info() # logger.debug("item:\n" + item.tostring('\n')) itemlist = [] list_canales = {} item_local = None # Desactiva autoplay autoplay.set_status(False) if not item.contentTitle or not item.strm_path: logger.debug("No se pueden buscar videos por falta de parametros") return [] #content_title = [c for c in item.contentTitle.strip().lower() if c not in ":*?<>|\/"] content_title = "".join(c for c in item.contentTitle.strip().lower() if c not in ":*?<>|\/") if item.contentType == 'movie': item.strm_path = filetools.join(videolibrarytools.MOVIES_PATH, item.strm_path) path_dir = filetools.dirname(item.strm_path) item.nfo = filetools.join(path_dir, filetools.basename(path_dir) + ".nfo") else: item.strm_path = filetools.join(videolibrarytools.TVSHOWS_PATH, item.strm_path) path_dir = filetools.dirname(item.strm_path) item.nfo = filetools.join(path_dir, 'tvshow.nfo') for fd in filetools.listdir(path_dir): if fd.endswith('.json'): contenido, nom_canal = fd[:-6].split('[') if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in \ list(list_canales.keys()): list_canales[nom_canal] = filetools.join(path_dir, fd) num_canales = len(list_canales) if 'downloads' in list_canales: json_path = list_canales['downloads'] item_json = Item().fromjson(filetools.read(json_path)) ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial try: if item_json: item_json, it, overwrite = generictools.redirect_clone_newpct1( item_json) except: logger.error(traceback.format_exc()) item_json.contentChannel = "local" # Soporte para rutas relativas en descargas if filetools.is_relative(item_json.url): item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH, item_json.url) del list_canales['downloads'] # Comprobar q el video no haya sido borrado if filetools.exists(item_json.url): item_local = item_json.clone(action='play') itemlist.append(item_local) else: num_canales -= 1 filtro_canal = '' if num_canales > 1 and config.get_setting("ask_channel", "videolibrary"): opciones = [ config.get_localized_string(70089) % k.capitalize() for k in list(list_canales.keys()) ] opciones.insert(0, config.get_localized_string(70083)) if item_local: opciones.append(item_local.title) from platformcode import platformtools index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index < 0: return [] elif item_local and index == len(opciones) - 1: filtro_canal = 'downloads' platformtools.play_video(item_local) elif index > 0: filtro_canal = opciones[index].replace( config.get_localized_string(70078), "").strip() itemlist = [] for nom_canal, json_path in list(list_canales.items()): if filtro_canal and filtro_canal != nom_canal.capitalize(): continue item_canal = Item() item_canal.channel = nom_canal ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial try: item_canal, it, overwrite = generictools.redirect_clone_newpct1( item_canal) except: logger.error(traceback.format_exc()) nom_canal = item_canal.channel # Importamos el canal de la parte seleccionada try: channel = __import__('channels.%s' % nom_canal, fromlist=["channels.%s" % nom_canal]) except ImportError: exec("import channels." + nom_canal + " as channel") item_json = Item().fromjson(filetools.read(json_path)) item_json.nfo = item.nfo ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial try: if item_json: item_json, it, overwrite = generictools.redirect_clone_newpct1( item_json) except: logger.error(traceback.format_exc()) list_servers = [] try: # FILTERTOOLS # si el canal tiene filtro se le pasa el nombre que tiene guardado para que filtre correctamente. if "list_language" in item_json: # si se viene desde la videoteca del addon if "library_filter_show" in item: item_json.show = item.library_filter_show.get( nom_canal, "") # Ejecutamos find_videos, del canal o común item_json.contentChannel = 'videolibrary' if hasattr(channel, 'findvideos'): from core import servertools if item_json.videolibray_emergency_urls: del item_json.videolibray_emergency_urls list_servers = getattr(channel, 'findvideos')(item_json) list_servers = servertools.filter_servers(list_servers) elif item_json.action == 'play': from platformcode import platformtools autoplay.set_status(True) item_json.contentChannel = item_json.channel item_json.channel = "videolibrary" platformtools.play_video(item_json) return '' else: from core import servertools list_servers = servertools.find_video_items(item_json) except Exception as ex: logger.error("Ha fallado la funcion findvideos para el canal %s" % nom_canal) template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) logger.error(traceback.format_exc()) # Cambiarle el titulo a los servers añadiendoles el nombre del canal delante y # las infoLabels y las imagenes del item si el server no tiene y = -1 z_torrent_url = '' for x, server in enumerate(list_servers): #if not server.action: # Ignorar/PERMITIR las etiquetas # continue server.contentChannel = server.channel server.channel = "videolibrary" server.nfo = item.nfo server.strm_path = item.strm_path # Para downloads de Torrents desde ventana flotante (sin context menu) if server.contentChannel == 'downloads' and not server.sub_action: y = x if server.server == 'torrent' and server.contentChannel != 'downloads' and not z_torrent_url: z_torrent_url = server.url if server.contentChannel == 'downloads': server.channel = server.contentChannel #### Compatibilidad con Kodi 18: evita que se quede la ruedecedita dando vueltas en enlaces Directos if server.action == 'play': server.folder = False # Se añade el nombre del canal si se desea if config.get_setting("quit_channel_name", "videolibrary") == 0: server.title = "%s: %s" % (nom_canal.capitalize(), server.title) #server.infoLabels = item_json.infoLabels if not server.thumbnail: server.thumbnail = item.thumbnail # logger.debug("server:\n%s" % server.tostring('\n')) itemlist.append(server) #Pego la url del primer torrent en el pseudo-context "Descargar" if y >= 0: itemlist[y].url = z_torrent_url # return sorted(itemlist, key=lambda it: it.title.lower()) autoplay.play_multi_channel(item, itemlist) from inspect import stack from channels import nextep if nextep.check(item) and stack()[1][3] == 'run': nextep.videolibrary(item) return itemlist
def run(item=None): logger.info() print "UUUUUUUUUUUUUUUUUUUUU" print sys.argv params = dict(urlparse.parse_qsl(sys.argv[2].replace('?', ''))) action = params.get('action') if not item: # Extract item from sys.argv if sys.argv[2] and action != "sod": 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() # Check for updates only on first screen if config.get_setting("check_for_plugin_updates"): try: from core import update_channels except: logger.info("Stefano.library_service Error in update_channels") # ---------------------------------------------------------------------- # -- Update servertools and servers from repository Stefano ------ try: from core import update_servers except: logger.info("Stefano.library_service Error in update_servers") 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("", "PIN per canali per adulti", True) if tecleado is None or tecleado != config.get_setting("adult_pin"): 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 o riprova (de-link)") # 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 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.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("plugin", 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("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]: sp = sys.argv[2].split('&') url = sp[0] item = Item().fromurl(url) if len(sp) > 1: for e in sp[1:]: key, val = e.split('=') item.__setattr__(key, val) # If no item, this is mainlist else: if config.get_setting("start_page"): if not config.get_setting("custom_start"): dictCategory = { config.get_localized_string(70137): 'peliculas', config.get_localized_string(30123): 'series', config.get_localized_string(30124): 'anime', config.get_localized_string(70018): 'infantiles', config.get_localized_string(60513): 'documentales', config.get_localized_string(70013): 'terror', config.get_localized_string(70014): 'castellano', config.get_localized_string(59976): 'latino', config.get_localized_string(70171): 'torrent', } if not config.get_setting( "category") in dictCategory.keys(): config.set_setting('category', config.get_localized_string(70137)) category = dictCategory[config.get_setting("category")] item = Item(channel="news", action="novedades", extra=category, mode='silent') else: from specials import side_menu item = Item() item = side_menu.check_user_home(item) item.start = True else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): from platformcode import xbmc_videolibrary xbmc_videolibrary.ask_set_content(silent=False) config.set_setting('show_once', True) logger.info(item.tostring()) try: if not config.get_setting('tmdb_active'): config.set_setting('tmdb_active', True) # If item has no action, stops here if item.action == "": logger.info("Item without action") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() elif item.action == "delete_key": from platformcode import keymaptools return keymaptools.delete_key() elif item.action == "script": from core import tmdb if tmdb.drop_bd(): platformtools.dialog_notification( config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) elif item.action == "itemInfo": import base64 platformtools.dialog_textviewer('Item info', item.parent) elif item.action == "open_browser": import webbrowser if not webbrowser.open(item.url): import xbmc if xbmc.getCondVisibility( 'system.platform.linux') and xbmc.getCondVisibility( 'system.platform.android'): # android xbmc.executebuiltin( 'StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")' % (item.url)) else: try: import urllib.request as urllib except ImportError: import urllib short = urllib.urlopen( 'https://u.nu/api.php?action=shorturl&format=simple&url=' + item.url).read().decode('utf-8') platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(70740) % short) # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": from core import channeltools #updater.checkforupdates() beta version checking for update, still disabled # Parental control # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting( "adult_request_password"): tecleado = platformtools.dialog_input( "", config.get_localized_string(60334), True) if tecleado is None or tecleado != config.get_setting( "adult_password"): return # # Actualiza el canal individual # if (item.action == "mainlist" and item.channel != "channelselector" and # config.get_setting("check_for_channel_updates") == True): # from core import updater # updater.update_channel(item.channel) # Checks if channel exists if os.path.isfile( os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py")): CHANNELS = 'channels' elif os.path.isfile( os.path.join(config.get_runtime_path(), 'channels', 'p**n', item.channel + ".py")): CHANNELS = 'channels.p**n' else: CHANNELS = 'specials' if CHANNELS != 'channels.p**n': channel_file = os.path.join(config.get_runtime_path(), CHANNELS, item.channel + ".py") else: channel_file = os.path.join(config.get_runtime_path(), 'channels', 'p**n', item.channel + ".py") logger.info("channel_file= " + channel_file + ' - ' + CHANNELS + ' - ' + item.channel) channel = None if os.path.exists(channel_file): try: channel = __import__('%s.%s' % (CHANNELS, item.channel), None, None, ['%s.%s' % (CHANNELS, item.channel)]) except ImportError: exec("import " + CHANNELS + "." + item.channel + " as channel") logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": #define la info para trakt try: from core import trakt_tools trakt_tools.set_trakt_info(item) except: pass logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(60339)) # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": from core import servertools # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) itemlist = servertools.filter_servers(itemlist) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": from core import videolibrarytools videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": from core import videolibrarytools videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from specials import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) from core import channeltools # last_search = "" # last_search_active = config.get_setting("last_search", "search") # if last_search_active: # try: # current_saved_searches_list = list(config.get_setting("saved_searches_list", "search")) # last_search = current_saved_searches_list[0] # except: # pass # last_search = channeltools.get_channel_setting('Last_searched', 'search', '') if channeltools.get_channel_setting('last_search', 'search'): last_search = channeltools.get_channel_setting( 'Last_searched', 'search', '') else: last_search = '' tecleado = platformtools.dialog_input(last_search) if tecleado is not None: channeltools.set_channel_setting('Last_searched', tecleado, 'search') if 'search' in dir(channel): itemlist = channel.search(item, tecleado) else: from core import support itemlist = support.search(channel, item, tecleado) else: return platformtools.render_items(itemlist, item) # For all other actions else: # import web_pdb; web_pdb.set_trace() logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) if config.get_setting('trakt_sync'): from core import trakt_tools token_auth = config.get_setting("token_trakt", "trakt") if not token_auth: trakt_tools.auth_trakt() else: import xbmc if not xbmc.getCondVisibility( 'System.HasAddon(script.trakt)' ) and config.get_setting('install_trakt'): trakt_tools.ask_install_script() itemlist = trakt_tools.trakt_check(itemlist) else: config.set_setting('install_trakt', True) platformtools.render_items(itemlist, item) except urllib2.URLError as e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.error("Reason for the error, code: %s | Reason: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string( 30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok(config.get_localized_string(20000), texto) # Grab server response errors elif hasattr(e, 'code'): logger.error("HTTP error code: %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(30051) % e.code) except WebErrorException as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + '([^.]+)\.py"' canal = scrapertools.find_single_match(traceback.format_exc(), patron) platformtools.dialog_ok( config.get_localized_string(59985) + canal, config.get_localized_string(60013) % (e)) except: import traceback from core import scrapertools logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + '([^.]+)\.py"' canal = scrapertools.find_single_match(traceback.format_exc(), patron) try: import xbmc if config.get_platform(True)['num_version'] < 14: log_name = "xbmc.log" else: log_name = "kodi.log" log_message = config.get_localized_string( 50004) + xbmc.translatePath("special://logpath") + log_name except: log_message = "" if canal: if item.url: if platformtools.dialog_yesno( config.get_localized_string(60087) % canal, config.get_localized_string(60014), log_message, nolabel='ok', yeslabel=config.get_localized_string(70739)): run(Item(action="open_browser", url=item.url)) else: platformtools.dialog_ok( config.get_localized_string(60087) % canal, config.get_localized_string(60014), log_message) else: platformtools.dialog_ok(config.get_localized_string(60038), config.get_localized_string(60015), log_message)
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)