def mainlist_listas(item): logger.info() itemlist = [] item.category = 'Listas' lista_activa = get_lista_activa() import glob path = os.path.join(config.get_data_path(), PREFIJO_LISTA+'*.json') for fichero in glob.glob(path): lista = os.path.basename(fichero) nombre = get_name_from_filename(lista) titulo = nombre if lista != lista_activa else '[COLOR gold]%s[/COLOR] [lista activa]' % nombre itemlist.append(item.clone(action='acciones_lista', lista=lista, title=titulo, folder=False)) itemlist.append(item.clone(action='acciones_nueva_lista', title='Crear/descargar lista / Info ...', folder=False)) return itemlist
def save_results(channel_id, list_result, category): menu_cache_path = os.path.join(config.get_data_path(), "settings_channels", 'menu_cache_data.json') list_newest = list() list_newest_tourl = list() if os.path.exists(menu_cache_path): cache_node = jsontools.get_node_from_file('menu_cache_data.json', 'cached') else: cache_node = dict() for item in list_result: item.channel = channel_id list_newest.append(item) list_newest_tourl.append(item.tourl()) if category not in cache_node: cache_node[category] = list() cache_node[category].extend(list_newest_tourl) jsontools.update_node(cache_node, 'menu_cache_data.json', "cached")
def question_update_external_addon(addon_name): logger.info(addon_name) #Verificamos que el addon está instalado stat = False if xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % addon_name): #Si es la primera vez que se pregunta por la actualización del addon externo, recogemos la respuesta, # guardaos un .json en userdat/alfa para no volver a preguntar otra vez, y se actualiza el setting en Alfa. stat = platformtools.dialog_yesno('Actualización de %s' % addon_name.capitalize(), '¿Quiere que actualicemos Quasar para que sea compatible con las últimas versiones de Kodi? (recomendado: SÍ)', '', 'Si actualiza Quasar, reinicie Kodi en un par de minutos') #Con la respuesta actualizamos la variable en Alfa settings.xml. Se puede cambiar en Ajustes de Alfa, Otros if stat: config.set_setting('addon_quasar_update', True) else: config.set_setting('addon_quasar_update', False) #Creamos un .json en userdata para no volver a preguntar otra vez create_json(config.get_data_path(), "%s.json" % addon_name) return stat
def remove_channel(item): support.log() path = filetools.join(config.get_data_path(), 'community_channels.json') community_json = open(path, "r") community_json = jsontools.load(community_json.read()) id = item.channel_id to_delete = community_json['channels'][id]['channel_name'] del community_json['channels'][id] with open(path, "w") as file: file.write(jsontools.dump(community_json)) file.close() platformtools.dialog_notification( config.get_localized_string(20000), config.get_localized_string(70684) % to_delete) platformtools.itemlist_refresh() return
def mainlist_listas(item): logger.debug() itemlist = [] item.category = 'Listas' lista_activa = get_lista_activa() import glob path = os.path.join(config.get_data_path(), PREFIJO_LISTA+'*.json') for fichero in glob.glob(path): lista = os.path.basename(fichero) nombre = get_name_from_filename(lista) titulo = nombre if lista != lista_activa else nombre itemlist.append(item.clone(action='acciones_lista', lista=lista, title=titulo, folder=False)) itemlist.append(item.clone(action='acciones_nueva_lista', title=config.get_localized_string(70642), folder=False)) return itemlist
def save_sub(data): import os try: ficherosubtitulo = os.path.join(config.get_data_path(), 'subtitulo_pelispedia.srt') if os.path.exists(ficherosubtitulo): try: os.remove(ficherosubtitulo) except IOError: logger.error("Error al eliminar el archivo " + ficherosubtitulo) raise fichero = open(ficherosubtitulo, "wb") fichero.write(data) fichero.close() subtitle = ficherosubtitulo except: subtitle = "" logger.error("Error al descargar el subtítulo") return subtitle
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('KoD', config.get_localized_string(70630), 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="kodfavorites", action="mainlist", thumbnail=get_thumb("mylink.png"), category=config.get_localized_string(70527), viewmode="thumbnails") platformtools.itemlist_update(item_inicio, replace=True) return True
def remove_channel(item): logger.info() import xbmc import xbmcgui path = os.path.join(config.get_data_path(), 'community_channels.json') community_json = open(path, "r") community_json = jsontools.load(community_json.read()) id = item.channel_id to_delete = community_json['channels'][id]['channel_name'] del community_json['channels'][id] with open(path, "w") as file: file.write(jsontools.dump(community_json)) file.close() platformtools.dialog_notification('Alfa', '%s ha sido eliminado' % to_delete) platformtools.itemlist_refresh() return
def submenu_tools(item): logger.info() itemlist = list() # Herramientas personalizadas import os channel_custom = os.path.join(config.get_runtime_path(), 'channels', 'custom.py') if not filetools.exists(channel_custom): user_custom = os.path.join(config.get_data_path(), 'custom.py') if filetools.exists(user_custom): filetools.copy(user_custom, channel_custom, silent=True) if filetools.exists(channel_custom): itemlist.append(Item(channel='custom', action='mainlist', title='Custom Channel')) #Disabilitato il menu degli aggiornamenti #itemlist.append(Item(channel=CHANNELNAME, action="check_quickfixes", folder=False, # title=config.get_localized_string(30001), plot="Versión actual: %s" % config.get_addon_version() )) itemlist.append(Item(channel=CHANNELNAME, action="update_quasar", folder=False, title=config.get_localized_string(70569))) itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumb("setting_0.png"))) itemlist.append(Item(channel=CHANNELNAME, title=config.get_localized_string(60564) + ":", action="", folder=False, text_bold=True, thumbnail=get_thumb("channels.png"))) itemlist.append(Item(channel=CHANNELNAME, title=config.get_localized_string(60565), action="conf_tools", folder=True, extra="lib_check_datajson", thumbnail=get_thumb("channels.png"))) if config.get_videolibrary_support(): itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumb("setting_0.png"))) itemlist.append(Item(channel=CHANNELNAME, title=config.get_localized_string(60566) + ":", action="", folder=False, text_bold=True, thumbnail=get_thumb("videolibrary.png"))) itemlist.append(Item(channel=CHANNELNAME, action="overwrite_tools", folder=False, thumbnail=get_thumb("videolibrary.png"), title="- " + config.get_localized_string(60567))) itemlist.append(Item(channel="videolibrary", action="update_videolibrary", folder=False, thumbnail=get_thumb("videolibrary.png"), title="- " + config.get_localized_string(60568))) return itemlist
def decrypt_subs(iv, data, id): import jscrypto data = base64.b64decode(data.encode('utf-8')) iv = base64.b64decode(iv.encode('utf-8')) id = int(id) def obfuscate_key_aux(count, modulo, start): output = list(start) for _ in range(count): output.append(output[-1] + output[-2]) # cut off start values output = output[2:] output = list([x % modulo + 33 for x in output]) return output def obfuscate_key(key): from math import pow, sqrt, floor num1 = int(floor(pow(2, 25) * sqrt(6.9))) num2 = (num1 ^ key) << 5 num3 = key ^ num1 num4 = num3 ^ (num3 >> 3) ^ num2 prefix = obfuscate_key_aux(20, 97, (1, 2)) prefix = struct.pack('B' * len(prefix), *prefix) shaHash = sha1(prefix + str(num4).encode('ascii')).digest() decshaHash = [] for char in shaHash: decshaHash.append(ord(char)) # Extend 160 Bit hash to 256 Bit return decshaHash + [0] * 12 key = obfuscate_key(id) key = struct.pack('B' * len(key), *key) decryptor = jscrypto.new(key, 2, iv) decrypted_data = decryptor.decrypt(data) data = zlib.decompress(decrypted_data) import xml.etree.ElementTree as ET raiz = ET.fromstring(data) ass_sub = convert_to_ass(raiz) file_sub = filetools.join(config.get_data_path(), 'crunchyroll_sub.ass') filetools.write(file_sub, ass_sub) return file_sub
def load_and_check(item): support.log() path = filetools.join(config.get_data_path(), 'community_channels.json') file = open(path, "r") json = jsontools.load(file.read()) for key, channel in json['channels'].items(): if not 'checked' in channel: response = httptools.downloadpage(channel['path'], follow_redirects=True, timeout=5) if response.sucess: channel['path'] = response.url channel['channel_name'] = re.sub(r'\[[^\]]+\]', '', channel['channel_name']) channel['check'] = True with open(path, "w") as file: file.write(jsontools.dump(json)) file.close() return json
def crear_lista(item): logger.info() titulo = platformtools.dialog_input(default='', heading='Nombre de la lista') if titulo is None or titulo == '': return False titulo = text_clean(titulo, blank_char='_') filename = get_filename_from_name(titulo) fullfilename = os.path.join(config.get_data_path(), filename) # Comprobar que el fichero no exista ya if os.path.exists(fullfilename): platformtools.dialog_ok('Alfa', 'Error, ya existe una lista con este nombre!', fullfilename) return False # Provocar que se guarde con las carpetas vacías por defecto alfav = AlfavoritesData(filename) platformtools.itemlist_refresh() return True
def crear_lista(item): logger.debug() titulo = platformtools.dialog_input(default='', heading=config.get_localized_string(70612)) if titulo is None or titulo == '': return False titulo = text_clean(titulo, blank_char='_') filename = get_filename_from_name(titulo) fullfilename = os.path.join(config.get_data_path(), filename) # Check that the file does not already exist if os.path.exists(fullfilename): platformtools.dialog_ok('KoD', config.get_localized_string(70613) + '\n' + fullfilename) return False # Cause it to be saved with empty folders by default alfav = KodfavouritesData(filename) platformtools.itemlist_refresh() return True
def obtener_data(url, referer=''): headers = {} if referer != '': headers['Referer'] = referer data = httptools.downloadpage(url, headers=headers).data if "Javascript is required" in data: ck = decodificar_cookie(data) logger.info("Javascript is required. Cookie necesaria %s" % ck) headers['Cookie'] = ck data = httptools.downloadpage(url, headers=headers).data # Guardar la cookie y eliminar la que pudiera haber anterior cks = ck.split("=") cookie_file = filetools.join(config.get_data_path(), 'cookies.dat') cookie_data = filetools.read(cookie_file) cookie_data = re.sub(r"www\.pelispedia\.tv\tFALSE\t/\tFALSE\t\tsucuri_(.*)\n", "", cookie_data) cookie_data += "www.pelispedia.tv\tFALSE\t/\tFALSE\t\t%s\t%s\n" % (cks[0], cks[1]) filetools.write(cookie_file, cookie_data) logger.info("Añadida cookie %s con valor %s" % (cks[0], cks[1])) return data
def update(item): logger.info() # Valores por defecto published_version_url = "" published_version_filename = "" # Lee la versión remota from core import api latest_packages = api.plugins_get_latest_packages() for latest_package in latest_packages["body"]: if latest_package["package"] == "plugin": published_version_url = latest_package["url"] published_version_filename = latest_package["filename"] published_version_number = latest_package["version"] break # La URL viene del API, y lo descarga en "userdata" remotefilename = published_version_url localfilename = os.path.join(config.get_data_path(), published_version_filename) download_and_install(remotefilename, localfilename)
def MostrarInfo(): os.system('cls' if os.name == 'nt' else 'clear') print ("--------------------------------------------------------------------") print ("Alfa Iniciado") print ("La URL para acceder es http://%s:%s" % (myip, http_port)) print ("WebSocket Server iniciado en ws://%s:%s" % (myip, websocket_port)) print ("--------------------------------------------------------------------") print ("Runtime Path : " + config.get_runtime_path()) print ("Data Path : " + config.get_data_path()) print ("Download Path : " + config.get_setting("downloadpath")) print ("DownloadList Path : " + config.get_setting("downloadlistpath")) print ("Bookmark Path : " + config.get_setting("bookmarkpath")) print ("Videolibrary Path : " + config.get_setting("videolibrarypath")) print ("--------------------------------------------------------------------") conexiones = [] controllers = platformtools.controllers for a in controllers: try: print platformtools.controllers[a].controller.client_ip + " - (" + platformtools.controllers[ a].controller.name + ")" except: pass
def eliminar_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 if item.lista == get_lista_activa(): platformtools.dialog_ok('Alfa', 'La lista activa no se puede eliminar', item.lista) return False if not platformtools.dialog_yesno( 'Eliminar lista', '¿Estás seguro de querer borrar la lista %s ?' % item.lista): return False filetools.remove(fullfilename) platformtools.itemlist_refresh() return True
def start(): logger.info("server init...") config.verify_directories_created() try: HTTPAndWSServer.start(show_info) # Da por levantado el servicio logger.info( "--------------------------------------------------------------------" ) logger.info("Alfa %s Iniciado" % version) logger.info("La URL para acceder es http://%s:%s" % (myip, http_port)) logger.info( "--------------------------------------------------------------------" ) logger.info("Runtime Path : " + config.get_runtime_path()) logger.info("Data Path : " + config.get_data_path()) logger.info("Download Path : " + config.get_setting("downloadpath")) logger.info("DownloadList Path : " + config.get_setting("downloadlistpath")) logger.info("Bookmark Path : " + config.get_setting("bookmarkpath")) logger.info("VideoLibrary Path : " + config.get_setting("videolibrarypath")) logger.info( "--------------------------------------------------------------------" ) show_info() flag = True while flag: time.sleep(1) except KeyboardInterrupt: print 'Deteniendo el servidor HTTP...' HTTPAndWSServer.stop() print 'Alfa Detenido' flag = False
def get_node_from_file(name_file, node, path=None, display=True): """ Obtiene el nodo de un fichero JSON @param name_file: Puede ser el nombre de un canal o server (sin incluir extension) o bien el nombre de un archivo json (con extension) @type name_file: str @param node: nombre del nodo a obtener @type node: str @param path: Ruta base del archivo json. Por defecto la ruta de settings_channels. @return: dict con el nodo a devolver @rtype: dict """ if display: logger.info() from platformcode import config from core import filetools dict_node = {} if not name_file.endswith(".json"): name_file += "_data.json" if not path: path = filetools.join(config.get_data_path(), "settings_channels") fname = filetools.join(path, name_file) if filetools.isfile(fname): data = filetools.read(fname) dict_data = load(data) check_to_backup(data, fname, dict_data, display=display) if node in dict_data: dict_node = dict_data[node] #logger.debug("dict_node: %s" % dict_node) return dict_node
def eliminar_lista(item): logger.info() fullfilename = os.path.join(config.get_data_path(), item.lista) if not os.path.exists(fullfilename): platformtools.dialog_ok('Alfa', config.get_localized_string(70630), item.lista) return False if item.lista == get_lista_activa(): platformtools.dialog_ok('Alfa', config.get_localized_string(70632), item.lista) return False if not platformtools.dialog_yesno( config.get_localized_string(70606), config.get_localized_string(70633) + ' %s ?' % item.lista): return False filetools.remove(fullfilename) platformtools.itemlist_refresh() return True
def informacion_lista(item): logger.debug() fullfilename = os.path.join(config.get_data_path(), item.lista) if not os.path.exists(fullfilename): platformtools.dialog_ok( 'KoD', config.get_localized_string(70630) + '\n' + item.lista) return False alfav = KodfavouritesData(item.lista) txt = 'Lista: %s' % item.lista txt += '[CR]' + config.get_localized_string( 70634 ) + ' ' + alfav.info_lista['created'] + ' ' + config.get_localized_string( 70635) + ' ' + alfav.info_lista['updated'] if 'downloaded_date' in alfav.info_lista: txt += '[CR]' + config.get_localized_string( 70636 ) + ' ' + alfav.info_lista['downloaded_date'] + ' ' + alfav.info_lista[ 'downloaded_from'] + ' ' + config.get_localized_string(70637) if 'tinyupload_date' in alfav.info_lista: txt += '[CR]' + config.get_localized_string( 70638) + ' ' + alfav.info_lista[ 'tinyupload_date'] + ' ' + config.get_localized_string( 70639) + ' [COLOR blue]' + alfav.info_lista[ 'tinyupload_code'] + '[/COLOR]' txt += '[CR]' + config.get_localized_string(70640) + ' ' + str( len(alfav.user_favorites)) for perfil in alfav.user_favorites: txt += '[CR]- %s (%d %s)' % (perfil['title'], len( perfil['items']), config.get_localized_string(70641)) platformtools.dialog_textviewer(config.get_localized_string(70607), txt) return True
def add_url(self, url): dom = '/'.join(url.split('/')[:3]) dom_path = '/'.join(url.split('/')[:-1]) try: # ~ data = httptools.downloadpage(url).data if 'player.openloadpremium.com/m3u8/index_' in url: headers = { 'Referer': url.replace('/m3u8/index_', '/player.php?id=').replace('.m3u8', '') } else: headers = {} data = httptools.downloadpage(url, headers=headers).data # ~ logger.debug(data) if not data or data == 'error html': raise () data_local = '' for lin in data.splitlines(): if lin.startswith('#'): data_local += lin elif lin.startswith('http'): data_local += self.url_base + base64.b64encode(lin) elif lin.startswith('/'): data_local += self.url_base + base64.b64encode(dom + lin) else: data_local += self.url_base + base64.b64encode(dom_path + '/' + lin) data_local += '\n' self.file_local = os.path.join(config.get_data_path(), "m3u8hls.m3u8") with open(self.file_local, 'wb') as f: f.write(data_local) f.close() except: self.file_local = None
def get_node_from_file(name_file, node, path=None): """ Gets the node of a JSON file @param name_file: It can be the name of a channel or server (not including extension) or the name of a json file (with extension) @type name_file: str @param node: name of the node to obtain @type node: str @param path: Base path of the json file. By default the path of settings_channels. @return: dict with the node to return @rtype: dict """ logger.debug() from platformcode import config from core import filetools dict_node = {} if not name_file.endswith(".json"): name_file += "_data.json" if not path: path = filetools.join(config.get_data_path(), "settings_channels") fname = filetools.join(path, name_file) if filetools.isfile(fname): data = filetools.read(fname) dict_data = load(data) check_to_backup(data, fname, dict_data) if node in dict_data: dict_node = dict_data[node] #logger.debug("dict_node: %s" % dict_node) return dict_node
def show_channels(item): logger.info() itemlist = [] context = [{ "title": config.get_localized_string(50005), "action": "remove_channel", "channel": "community" }] path = os.path.join(config.get_data_path(), 'community_channels.json') file = open(path, "r") json = jsontools.load(file.read()) itemlist.append( Item(channel=item.channel, title=config.get_localized_string(70676), action='add_channel', thumbnail=get_thumb('add.png'))) for key, channel in json['channels'].items(): file_path = channel['path'] file_url = httptools.downloadpage(file_path, follow_redirects=True).data json_url = jsontools.load(file_url) thumbnail = json_url['thumbnail'] if 'thumbnail' in json_url else '' fanart = json_url['fanart'] if 'fanart' in json_url else '' itemlist.append( Item(channel=item.channel, title=channel['channel_name'], url=file_path, thumbnail=thumbnail, fanart=fanart, action='show_menu', channel_id=key, context=context)) return itemlist
def show_channels(item): logger.info() itemlist = [] context = [{"title": "Eliminar este canal", "action": "remove_channel", "channel": "community"}] path = filetools.join(config.get_data_path(), 'community_channels.json') json = jsontools.load(filetools.read(path)) itemlist.append(Item(channel=item.channel, title='Agregar un canal', action='add_channel', thumbnail=get_thumb('add.png'))) for key, channel in list(json['channels'].items()): if 'poster' in channel: poster = channel['poster'] else: poster = '' itemlist.append(Item(channel=item.channel, title=channel['channel_name'], url=channel['path'], thumbnail=poster, action='show_menu', channel_id = key, context=context)) return itemlist
def backups(item): logger.info() ruta = filetools.join(config.get_data_path(), 'backups') ruta_split = "" if "ruta" in item.title: heading = "Ruta de copias de seguridad" if not filetools.exists(ruta): folders = "Carpeta no creada" else: folders = str(len(filetools.listdir(ruta))) + " copia/s de seguridad guardadas" if len(ruta) > 55: ruta_split = ruta[55:] ruta = ruta[:55] platformtools.dialog_ok(heading, ruta, ruta_split, folders) else: if not filetools.exists(ruta): platformtools.dialog_ok("La carpeta no existe", "No hay copias de seguridad guardadas") else: dyesno = platformtools.dialog_yesno("Las copias de seguridad se eliminarán", "¿Está seguro?") if dyesno: import shutil shutil.rmtree(ruta, ignore_errors=True)
def get_from_subdivx(sub_url): """ :param sub_url: Url de descarga del subtitulo alojado en suvdivx.com Por Ejemplo: http://www.subdivx.com/bajar.php?id=573942&u=8 :return: La ruta al subtitulo descomprimido """ logger.info() sub = '' sub_dir = os.path.join(config.get_data_path(), 'temp_subs') if os.path.exists(sub_dir): for sub_file in os.listdir(sub_dir): old_sub = os.path.join(sub_dir, sub_file) os.remove(old_sub) else: os.mkdir(sub_dir) sub_url = sub_url.replace("&", "&") sub_data = httptools.downloadpage(sub_url, follow_redirects=False) if 'x-frame-options' not in sub_data.headers: sub_url = '%s' % sub_data.headers['location'] ext = sub_url[-4::] file_id = "subtitle%s" % ext filename = os.path.join(sub_dir, file_id) try: data_dl = httptools.downloadpage(sub_url).data filetools.write(filename, data_dl) sub = extract_file_online(sub_dir, filename) except: logger.info('sub no valido') else: logger.info('sub no valido') return sub
def get_video_url(page_url, premium=False, user="", password="", video_password=""): logger.info("(page_url='%s')" % page_url) v_type = "hls" url = page_url video_urls = list() if "const source = '" in data: url = scrapertools.find_single_match(data, "const source = '([^']+)") v_type = "hls" if '"file": ' in data: url, v_type = scrapertools.find_single_match(data, '"file": "([^"]+)",\s+"type": "([^"]+)"') headers = {"referer": page_url} if v_type == "mp4": url = httptools.downloadpage(url, headers=headers, follow_redirects=False, stream=True).headers["location"] page_url = "%s|Referer=%s&User-Agent=%s" % (url, page_url, httptools.get_user_agent()) elif v_type == "hls": hls_data = httptools.downloadpage(url, headers=headers).data base_url = scrapertools.find_single_match(hls_data, "(https?://[^/]+)") hls_data = hls_data.replace(base_url, 'http://localhost:8781') m3u8 = os.path.join(config.get_data_path(), "op_master.m3u8") outfile = open(m3u8, 'wb') outfile.write(codecs.encode(hls_data, "utf-8")) outfile.close() page_url = m3u8 v_type = "m3u8" servop.start(base_url) else: return video_urls video_urls = [["%s [Oprem]" % v_type, page_url]] return video_urls
def show_info(): os.system('cls' if os.name == 'nt' else 'clear') # os.system('echo Reloading...') print( "--------------------------------------------------------------------") print("Alfa %s Iniciado" % version) print("La URL para acceder es http://%s:%s" % (myip, http_port)) print( "--------------------------------------------------------------------") print("Runtime Path : " + config.get_runtime_path()) print("Data Path : " + config.get_data_path()) print("Download Path : " + config.get_setting("downloadpath")) print("DownloadList Path : " + config.get_setting("downloadlistpath")) print("Bookmark Path : " + config.get_setting("bookmarkpath")) print("Videolibrary Path : " + config.get_setting("videolibrarypath")) print( "--------------------------------------------------------------------") controllers = platformtools.controllers for a in controllers: try: print(platformtools.controllers[a].controller.client_ip + " - (" + platformtools.controllers[a].controller.name + ")") except Exception as e: print(e)
def save_server_stats(stats, type="find_videos"): if not config.get_setting("server_stats"): return stats_file = os.path.join(config.get_data_path(), "server_stats.json") today = datetime.datetime.now().strftime("%Y%m%d") # Leemos el archivo try: server_stats = jsontools.load(open(stats_file, "rb").read()) except: server_stats = {"created": time.time(), "data": {}} # Actualizamos los datos for server in stats: if not server in server_stats["data"]: server_stats["data"][server] = {} if not today in server_stats["data"][server]: server_stats["data"][server][today] = {"find_videos": {"found": 0}, "resolve": {"sucess": 0, "error": 0}} server_stats["data"][server][today][type][stats[server]] += 1 # Guardamos el archivo open(stats_file, "wb").write(jsontools.dump(server_stats)) # Enviamos al servidor return if time.time() - server_stats["created"] > 86400: # 86400: #1 Dia from core import httptools if httptools.downloadpage("url servidor", headers={'Content-Type': 'application/json'}, post=jsontools.dump(server_stats)).sucess: os.remove(stats_file) logger.info("Datos enviados correctamente") else: logger.info("No se han podido enviar los datos")