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 channel_status(item, dict_values): try: for k in dict_values: if k == "all_channels": logger.info("Todos los canales | Estado seleccionado: %s" % dict_values[k]) if dict_values[k] != 0: excluded_channels = ['tengourl', 'buscador', 'biblioteca', 'configuracion', 'novedades', 'personal', 'ayuda', 'descargas'] for channel in item.channel_list: if channel.channel not in excluded_channels: from core import channeltools channel_parameters = channeltools.get_channel_parameters(channel.channel) new_status_all = None new_status_all_default = channel_parameters["active"] # Opcion Activar todos if dict_values[k] == 1: new_status_all = True # Opcion Desactivar todos if dict_values[k] == 2: new_status_all = False # Opcion Recuperar estado por defecto if dict_values[k] == 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" % (k, dict_values[k])) config.set_setting("enabled", dict_values[k], k) logger.info("el valor esta como %s " % config.get_setting("enabled", k)) platformtools.itemlist_update(Item(channel=CHANNELNAME, action="mainlist")) except: import traceback logger.error("Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_notification("Error", "Se ha producido un error al guardar")
def channel_status(item, dict_values): try: for k in dict_values: if k == "all_channels": logger.info("Todos los canales | Estado seleccionado: %s" % dict_values[k]) if dict_values[k] != 0: excluded_channels = ['url', 'search', 'videolibrary', 'setting', 'news', 'help', 'downloads'] for channel in item.channel_list: if channel.channel not in excluded_channels: from core import channeltools channel_parameters = channeltools.get_channel_parameters(channel.channel) new_status_all = None new_status_all_default = channel_parameters["active"] # Opcion Activar todos if dict_values[k] == 1: new_status_all = True # Opcion Desactivar todos if dict_values[k] == 2: new_status_all = False # Opcion Recuperar estado por defecto if dict_values[k] == 3: # Si tiene "enabled" en el _data.json es porque el estado no es el del channel.json if config.get_setting("enabled", channel.channel): new_status_all = new_status_all_default # Si el canal no tiene "enabled" en el _data.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" % (k, dict_values[k])) config.set_setting("enabled", dict_values[k], k) logger.info("el valor esta como %s " % config.get_setting("enabled", k)) platformtools.itemlist_update(Item(channel=CHANNELNAME, action="mainlist")) except: import traceback logger.error("Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_notification(config.get_localized_string(60579), config.get_localized_string(60580))
def activar_lista(item): logger.info() fullfilename = filetools.join(trackingtools.get_tracking_path(), item.lista) if not filetools.exists(fullfilename): platformtools.dialog_ok(config.__addon_name, 'Error, no se encuentra la lista!', item.lista) return False trackingtools.set_current_dbname(item.lista) # ~ platformtools.itemlist_refresh() # mejor con replace=True para que no haya problemas si se vuelve atrás item_inicio = Item( channel='tracking', action='mainlist', title='Seguimiento', thumbnail=config.get_thumb('videolibrary') ) platformtools.itemlist_update(item_inicio, replace=True) return True
def activar_lista(item): logger.info() fullfilename = os.path.join(config.get_data_path(), item.lista) if not os.path.exists(fullfilename): platformtools.dialog_ok('Alfa', 'Error, no se encuentra la lista!', item.lista) return False config.set_setting('lista_activa', item.lista) from channelselector import get_thumb item_inicio = Item(title=config.get_localized_string(70527), channel="alfavorites", action="mainlist", thumbnail=get_thumb("mylink.png"), category=config.get_localized_string(70527), viewmode="thumbnails") platformtools.itemlist_update(item_inicio, replace=True) return True
"El sitio web no funciona correctamente (error http %d)" % e.code) except WebErrorException, e: import traceback logger.error(traceback.format_exc()) # Ofrecer buscar en otros canales o en el mismo canal, si está activado en la configuración if item.contentType in [ 'movie', 'tvshow', 'season', 'episode' ] and config.get_setting('tracking_weberror_dialog', default=True): if item.action == 'findvideos': platformtools.play_fake() item_search = platformtools.dialogo_busquedas_por_fallo_web(item) if item_search is not None: platformtools.itemlist_update(item_search) else: platformtools.dialog_ok( 'Error en el canal ' + item.channel, 'La web de la que depende parece no estar disponible, puede volver a intentarlo, si el problema persiste verifique mediante un navegador la web: %s' % (e)) except: import traceback logger.error(traceback.format_exc()) platformtools.dialog_ok( "Error inesperado en el canal " + item.channel, "Puede deberse a un fallo de conexión, la web del canal ha cambiado su estructura, o un error interno del addon. Para saber más detalles, consulta el log." )
def setting_torrent(item): logger.info() LIBTORRENT_PATH = config.get_setting("libtorrent_path", server="torrent", default="") LIBTORRENT_ERROR = config.get_setting("libtorrent_error", server="torrent", default="") default = config.get_setting("torrent_client", server="torrent", default=0) BUFFER = config.get_setting("mct_buffer", server="torrent", default="50") DOWNLOAD_PATH = config.get_setting( "mct_download_path", server="torrent", default=config.get_setting("downloadpath")) if not DOWNLOAD_PATH: DOWNLOAD_PATH = filetools.join(config.get_data_path(), 'downloads') BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True) RAR = config.get_setting("mct_rar_unpack", server="torrent", default=True) DOWNLOAD_LIMIT = config.get_setting("mct_download_limit", server="torrent", default="") BUFFER_BT = config.get_setting("bt_buffer", server="torrent", default="50") DOWNLOAD_PATH_BT = config.get_setting( "bt_download_path", server="torrent", default=config.get_setting("downloadpath")) if not DOWNLOAD_PATH_BT: DOWNLOAD_PATH_BT = filetools.join(config.get_data_path(), 'downloads') MAGNET2TORRENT = config.get_setting("magnet2torrent", server="torrent", default=False) CAPTURE_THRU_ROWSER_PATH = config.get_setting("capture_thru_browser_path", server="torrent", default="") ALLOW_SEEDING = config.get_setting('allow_seeding', server='torrent', default=True) torrent_options = [ config.get_localized_string(30006), config.get_localized_string(70254), config.get_localized_string(70255) ] torrent_options.extend(platformtools.torrent_client_installed()) if len(torrent_options) < default + 1: default = 0 list_controls = [{ "id": "libtorrent_path", "type": "text", "label": "Libtorrent path", "default": LIBTORRENT_PATH, "enabled": True, "visible": False }, { "id": "libtorrent_error", "type": "text", "label": "libtorrent error", "default": LIBTORRENT_ERROR, "enabled": True, "visible": False }, { "id": "list_torrent", "type": "list", "label": config.get_localized_string(70256), "default": default, "enabled": True, "visible": True, "lvalues": torrent_options }, { "id": "mct_buffer", "type": "text", "label": "MCT - Tamaño del Buffer a descargar antes de la reproducción", "default": BUFFER, "enabled": True, "visible": "eq(-1,%s)" % torrent_options[2] }, { "id": "mct_download_path", "type": "text", "label": "MCT - Ruta de la carpeta de descarga", "default": DOWNLOAD_PATH, "enabled": True, "visible": "eq(-2,%s)" % torrent_options[2] }, { "id": "bt_buffer", "type": "text", "label": "BT - Tamaño del Buffer a descargar antes de la reproducción", "default": BUFFER_BT, "enabled": True, "visible": "eq(-3,%s)" % torrent_options[1] }, { "id": "bt_download_path", "type": "text", "label": "BT - Ruta de la carpeta de descarga", "default": DOWNLOAD_PATH_BT, "enabled": True, "visible": "eq(-4,%s)" % torrent_options[1] }, { "id": "mct_download_limit", "type": "text", "label": "Límite (en Kb's) de la velocidad de descarga en segundo plano (NO afecta a RAR)", "default": DOWNLOAD_LIMIT, "enabled": True, "visible": "eq(-5,%s) | eq(-5,%s)" % (torrent_options[1], torrent_options[2]) }, { "id": "mct_rar_unpack", "type": "bool", "label": "¿Quiere que se descompriman los archivos RAR y ZIP para su reproducción?", "default": RAR, "enabled": True, "visible": True }, { "id": "mct_background_download", "type": "bool", "label": "¿Se procesa la descompresión de RARs en segundo plano?", "default": BACKGROUND, "enabled": True, "visible": True }, { "id": "magnet2torrent", "type": "bool", "label": "¿Quiere convertir los Magnets a Torrents para ver tamaños y almacenarlos?", "default": MAGNET2TORRENT, "enabled": True, "visible": True }, { "id": "capture_thru_browser_path", "type": "text", "label": "Path para descargar con un browser archivos .torrent bloqueados", "default": CAPTURE_THRU_ROWSER_PATH, "enabled": True, "visible": True }, { "id": "allow_seeding", "type": "bool", "label": "¿Quiere permitir el semillado de los torrents descargados?", "default": ALLOW_SEEDING, "enabled": True, "visible": True }] platformtools.show_channel_settings( list_controls=list_controls, callback='save_setting_torrent', item=item, caption=config.get_localized_string(70257), custom_button={'visible': False}) if item.item_org: item_org = Item().fromurl(item.item_org) if item_org.torrent_info: del item_org.torrent_info platformtools.itemlist_update(item_org)
def run(item=None): logger.debug() # Extract item from sys.argv if not item: item = makeItem() # Load or Repare Settings if not config.get_setting('show_once'): showOnce() # Acrions logger.debug(item.tostring()) try: # Active tmdb if not config.get_setting('tmdb_active'): config.set_setting('tmdb_active', True) # If item has no action, stops here if item.action == '': logger.debug('Item without action') return # Channel Selector if item.channel == 'channelselector': itemlist = [] import channelselector if item.action == 'getmainlist': # Action for main menu in channelselector itemlist = channelselector.getmainlist() elif item.action == 'getchanneltypes': # Action for channel types on channelselector: movies, series, etc. itemlist = channelselector.getchanneltypes() elif item.action == 'filterchannels': # Action for channel listing on 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': return playFromLibrary(item) # Special play action elif item.action == 'play': play(item) # Special findvideos Action elif item.action == 'findvideos': findvideos(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == 'search': search(item) ######## Following shares must be improved ######## # Special itemInfo Action elif item.action == "itemInfo": platformtools.dialog_textviewer('Item info', item.parent) # Special action for open item.url in browser 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: platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(70740) % "\n".join([item.url[j:j+57] for j in range(0, len(item.url), 57)])) # Special gotopage Action elif item.action == "gotopage": page = platformtools.dialog_numeric(0, config.get_localized_string(70513)) if page: import xbmc item.action = item.real_action if item.page: item.page = int(page) else: import re item.url = re.sub('([=/])[0-9]+(/?)$', '\g<1>' + page + '\g<2>', item.url) xbmc.executebuiltin("Container.Update(%s?%s)" % (sys.argv[0], item.tourl())) # 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": channel = importChannel(item) from core import videolibrarytools videolibrarytools.add_tvshow(item, channel) # Special action for adding a undefined to the library elif item.action == "add_to_library": channel = importChannel(item) from core import videolibrarytools videolibrarytools.add_to_videolibrary(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) # keymaptools special actions 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() # delete tmdb cache elif item.action == "script": from core import tmdb tmdb.clean_cache() platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) ################################################ # For all other actions else: actions(item) except WebErrorException as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) platformtools.dialog_ok( config.get_localized_string(59985) % e.channel, config.get_localized_string(60013) % e.url) except Exception as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) patron = r'File "{}([^.]+)\.py"'.format(filetools.join(config.get_runtime_path(), 'channels', '').replace('\\', '\\\\')) Channel = scrapertools.find_single_match(traceback.format_exc(), patron) if Channel or e.__class__ == logger.ChannelScraperException: if item.url: if platformtools.dialog_yesno(config.get_localized_string(60087) % Channel, config.get_localized_string(60014), nolabel='ok', yeslabel=config.get_localized_string(70739)): run(Item(action='open_browser', url=item.url)) else: platformtools.dialog_ok(config.get_localized_string(60087) % Channel, config.get_localized_string(60014)) else: if platformtools.dialog_yesno(config.get_localized_string(60038), config.get_localized_string(60015)): platformtools.itemlist_update(Item(channel='setting', action='report_menu'), True) finally: # db need to be closed when not used, it will cause freezes from core import db db.close() import threading logger.debug(threading.enumerate())
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 conf_tools(item): logger.info() # Activar/Desactivar canales if item.extra == "channels_onoff": import channelselector from core import channeltools from platformcode import platformtools 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'] 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") == "false"): continue # No incluir si el canal es en un idioma filtrado if (channel_language != "all" and channel_parameters["language"] != channel_language): continue xml_status = None status = None xml_status = channel_parameters["active"] status_control = "" if config.get_setting("enabled", channel.channel): status = config.get_setting("enabled", channel.channel) # logger.info(channel.channel + " | Status: " + str(status)) else: status = xml_status # logger.info(channel.channel + " | Status (XML): " + str(status)) # Se establece el estado if status == "false" or status is False: status = False elif status == "true" or status is True: status = True if xml_status == "false": 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="Activar/Desactivar canales", callback="channel_status") except: import traceback from platformcode import platformtools logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_notification("Error", "Se ha producido un error con el canal" + 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: {0}".format(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: {0}".format(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 = " - [COLOR red] Ajustes creados!![/COLOR]" else: list_status = " - [COLOR green] No necesita correccion[/COLOR]" else: # Si "needsfix" es "false" y "datjson_size" es None habra # ocurrido algun error if datajson_size is None: list_status = " - [COLOR red] Ha ocurrido algun error[/COLOR]" else: list_status = " - [COLOR green] No necesita correccion[/COLOR]" if list_status is not None: itemlist.append(Item(channel=CHANNELNAME, title=channel.title + list_status, action="", folder=False, thumbnail=channel.thumbnail)) else: logger.info("Algo va mal con el canal " + channel.channel) # Si el canal esta en la lista de exclusiones lo saltamos else: continue except: import traceback from platformcode import platformtools logger.info(channel.title + " | Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_notification("Error", "Se ha producido un error con el canal" + channel.title) return itemlist else: from platformcode import platformtools platformtools.dialog_notification("pelisalacarta", "Error!") platformtools.itemlist_update(Item(channel=CHANNELNAME, action="submenu_tools"))
def run(item=None): logger.debug() if not item: # Extract item from sys.argv if sys.argv[2]: sp = sys.argv[2].split('&') url = sp[0] item = Item().fromurl(url) if len(sp) > 1: for e in sp[1:]: key, val = e.split('=') item.__setattr__(key, val) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): if not config.get_all_settings_addon(): logger.error('corrupted settings.xml!!') settings_xml = os.path.join(config.get_data_path(), "settings.xml") settings_bak = os.path.join(config.get_data_path(), "settings.bak") if filetools.exists(settings_bak): filetools.copy(settings_bak, settings_xml, True) logger.info('restored settings.xml from backup') else: filetools.write(settings_xml, '<settings version="2">\n</settings>') # resetted settings else: from platformcode import xbmc_videolibrary xbmc_videolibrary.ask_set_content(silent=False) config.set_setting('show_once', True) logger.info(item.tostring()) try: if not config.get_setting('tmdb_active'): config.set_setting('tmdb_active', True) # If item has no action, stops here if item.action == "": logger.debug("Item without action") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() elif item.channel == "infoplus": from platformcode import infoplus return infoplus.Main(item) elif item.channel == "backup": from platformcode import backup return getattr(backup, item.action)(item) elif item.channel == "elementum_download": from platformcode import elementum_download return getattr(elementum_download, item.action)(item) elif item.channel == "shortcuts": from platformcode import shortcuts return getattr(shortcuts, item.action)(item) elif item.channel == "autorenumber": from platformcode import autorenumber return getattr(autorenumber, item.action)(item) elif item.action == "delete_key": from platformcode import keymaptools return keymaptools.delete_key() elif item.action == "script": from core import tmdb tmdb.clean_cache() platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) elif item.action == "itemInfo": platformtools.dialog_textviewer('Item info', item.parent) elif item.action == "open_browser": import webbrowser if not webbrowser.open(item.url): import xbmc if xbmc.getCondVisibility('system.platform.linux') and xbmc.getCondVisibility('system.platform.android'): # android xbmc.executebuiltin('StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")' % (item.url)) else: try: import urllib.request as urllib except ImportError: import urllib short = urllib.urlopen('https://u.nu/api.php?action=shorturl&format=simple&url=' + item.url).read().decode('utf-8') platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(70740) % short) else: # Checks if channel exists if os.path.isfile(os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py")): CHANNELS = 'channels' else: CHANNELS = 'specials' channel_file = os.path.join(config.get_runtime_path(), CHANNELS, item.channel + ".py") logger.debug("channel_file= " + channel_file + ' - ' + CHANNELS + ' - ' + item.channel) channel = None if os.path.exists(channel_file): try: channel = __import__('%s.%s' % (CHANNELS, item.channel), None, None, ['%s.%s' % (CHANNELS, item.channel)]) except ImportError: exec("import " + CHANNELS + "." + item.channel + " as channel") logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": # define la info para trakt try: from core import trakt_tools trakt_tools.set_trakt_info(item) except: pass logger.debug("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.debug("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el Channel elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(60339)) # If player don't have a "play" function, not uses the standard play from platformtools else: logger.debug("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": from core import servertools # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.debug("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": from core import videolibrarytools videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": from core import videolibrarytools videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from specials import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": # from core.support import dbg;dbg() if filetools.isfile(temp_search_file) and config.get_setting('videolibrary_kodi'): itemlist = [] f = filetools.read(temp_search_file) strList = f.split(',') if strList[0] == '[V]' and strList[1] == item.channel: for it in strList: if it and it not in ['[V]', item.channel]: itemlist.append(Item().fromurl(it)) filetools.write(temp_search_file, f[4:]) return platformtools.render_items(itemlist, item) else: filetools.remove(temp_search_file) logger.debug("item.action=%s" % item.action.upper()) from core import channeltools if config.get_setting('last_search'): last_search = channeltools.get_channel_setting('Last_searched', 'search', '') else: last_search = '' search_text = platformtools.dialog_input(last_search) if search_text is not None: channeltools.set_channel_setting('Last_searched', search_text, 'search') itemlist = new_search(item.clone(text=search_text), channel) else: return platformtools.render_items(itemlist, item) # For all other actions else: # import web_pdb; web_pdb.set_trace() logger.debug("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) if config.get_setting('trakt_sync'): from core import trakt_tools token_auth = config.get_setting("token_trakt", "trakt") if not token_auth: trakt_tools.auth_trakt() else: import xbmc if not xbmc.getCondVisibility('System.HasAddon(script.trakt)') and config.get_setting('install_trakt'): trakt_tools.ask_install_script() itemlist = trakt_tools.trakt_check(itemlist) else: config.set_setting('install_trakt', True) platformtools.render_items(itemlist, item) except WebErrorException as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) platformtools.dialog_ok( config.get_localized_string(59985) % e.channel, config.get_localized_string(60013) % e.url) except Exception as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + r'([^.]+)\.py"' Channel = scrapertools.find_single_match(traceback.format_exc(), patron) if Channel or e.__class__ == logger.ChannelScraperException: if item.url: if platformtools.dialog_yesno(config.get_localized_string(60087) % Channel, config.get_localized_string(60014), nolabel='ok', yeslabel=config.get_localized_string(70739)): run(Item(action="open_browser", url=item.url)) else: platformtools.dialog_ok(config.get_localized_string(60087) % Channel, config.get_localized_string(60014)) else: if platformtools.dialog_yesno(config.get_localized_string(60038), config.get_localized_string(60015)): platformtools.itemlist_update(Item(channel="setting", action="report_menu"), True) finally: # db need to be closed when not used, it will cause freezes from core import db db.close()