def backups(item): from platformcode import platformtools logger.info("pelisalacarta.channel.configuracion backups") 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 check_bookmark(readpath): # Crea un listado con las entradas de favoritos itemlist = [] if readpath.startswith("special://") and config.is_xbmc(): import xbmc readpath = xbmc.translatePath(readpath) for fichero in sorted(filetools.listdir(readpath)): # Ficheros antiguos (".txt") if fichero.endswith(".txt"): # Esperamos 0.1 segundos entre ficheros, para que no se solapen los nombres de archivo time.sleep(0.1) # Obtenemos el item desde el .txt canal, titulo, thumbnail, plot, server, url, fulltitle = readbookmark(filetools.join(readpath, fichero)) if canal == "": canal = "favoritos" item = Item(channel=canal, action="play", url=url, server=server, title=fulltitle, thumbnail=thumbnail, plot=plot, fanart=thumbnail, fulltitle=fulltitle, folder=False) filetools.rename(filetools.join(readpath, fichero),fichero[:-4] + ".old") itemlist.append(item) # Si hay Favoritos q guardar if itemlist: favourites_list = read_favourites() for item in itemlist: data = "ActivateWindow(10025,"plugin://plugin.video.pelisalacarta/?" + item.tourl() + "",return)" favourites_list.append((item.title, item.thumbnail, data)) if save_favourites(favourites_list): logger.debug("Conversion de txt a xml correcta")
def move_to_libray(item): try: from platformcode import library except: return # Copiamos el archivo a la biblioteca origen = filetools.join(config.get_setting("downloadpath"), item.downloadFilename) destino = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename)) if not filetools.isdir(filetools.dirname(destino)): filetools.mkdir(filetools.dirname(destino)) if filetools.isfile(destino) and filetools.isfile(origen) : filetools.remove(destino) if filetools.isfile(origen): filetools.move(origen, destino) if len(filetools.listdir(filetools.dirname(origen))) == 0: filetools.rmdir(filetools.dirname(origen)) else: logger.error("No se ha encontrado el archivo: %s" % origen) if filetools.isfile(destino): if item.contentType == "movie" and item.infoLabels["tmdb_id"]: library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino) library.save_library_movie(library_item) elif item.contentType == "episode" and item.infoLabels["tmdb_id"]: library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino) tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]}) library.save_library_tvshow(tvshow, [library_item])
def mainlist(item): logger.info() itemlist = [] item.text_color = color1 logueado, error_message = login("copiapop.com") if not logueado: itemlist.append(item.clone(title=error_message, action="configuracion", folder=False)) else: item.extra = "http://copiapop.com" itemlist.append(item.clone(title="Copiapop", action="", text_color=color2)) itemlist.append(item.clone(title=" Búsqueda", action="search", url="http://copiapop.com/action/SearchFiles")) itemlist.append(item.clone(title=" Colecciones", action="colecciones", url="http://copiapop.com/action/home/MoreNewestCollections?pageNumber=1")) itemlist.append(item.clone(title=" Búsqueda personalizada", action="filtro", url="http://copiapop.com/action/SearchFiles")) itemlist.append(item.clone(title=" Mi cuenta", action="cuenta")) item.extra = "http://diskokosmiko.mx/" itemlist.append(item.clone(title="DiskoKosmiko", action="", text_color=color2)) itemlist.append(item.clone(title=" Búsqueda", action="search", url="http://diskokosmiko.mx/action/SearchFiles")) itemlist.append(item.clone(title=" Colecciones", action="colecciones", url="http://diskokosmiko.mx/action/home/MoreNewestCollections?pageNumber=1")) itemlist.append(item.clone(title=" Búsqueda personalizada", action="filtro", url="http://diskokosmiko.mx/action/SearchFiles")) itemlist.append(item.clone(title=" Mi cuenta", action="cuenta")) itemlist.append(item.clone(action="", title="")) folder_thumb = filetools.join(config.get_data_path(), 'thumbs_copiapop') files = filetools.listdir(folder_thumb) if files: itemlist.append(item.clone(title="Eliminar caché de imágenes (%s)" % len(files), action="delete_cache", text_color="red")) itemlist.append(item.clone(title="Configuración del canal", action="configuracion", text_color="gold")) return itemlist
def eliminar(item): def eliminar_todo(item): filetools.rmdirtree(item.path) if config.is_xbmc(): import xbmc # esperamos 3 segundos para dar tiempo a borrar los ficheros xbmc.sleep(3000) # TODO mirar por qué no funciona al limpiar en la biblioteca de Kodi al añadirle un path # limpiamos la biblioteca de Kodi library.clean() logger.info("Eliminados todos los enlaces") platformtools.itemlist_refresh() logger.info(item.contentTitle) #logger.debug(item.tostring('\n')) if item.contentType == 'movie': heading = "Eliminar película" else: heading = "Eliminar serie" if item.multicanal: # Obtener listado de canales opciones = ["Eliminar solo los enlaces de %s" % k.capitalize() for k in item.library_urls.keys() if k !="descargas"] opciones.insert(0, heading) index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index == 0: # Seleccionado Eliminar pelicula/serie eliminar_todo(item) elif index > 0: # Seleccionado Eliminar canal X canal = opciones[index].replace("Eliminar solo los enlaces de ", "").lower() num_enlaces= 0 for fd in filetools.listdir(item.path): if fd.endswith(canal + '].json'): if filetools.remove(filetools.join(item.path, fd)): num_enlaces += 1 if num_enlaces > 0: # Actualizar .nfo head_nfo, item_nfo = library.read_nfo(item.nfo) del item_nfo.library_urls[canal] filetools.write(item.nfo, head_nfo + item_nfo.tojson()) msg_txt = "Eliminados %s enlaces del canal %s" % (num_enlaces, canal) logger.info(msg_txt) platformtools.dialog_notification(heading, msg_txt) platformtools.itemlist_refresh() else: if platformtools.dialog_yesno(heading, "¿Realmente desea eliminar '%s' de su biblioteca?" % item.infoLabels['title']): eliminar_todo(item)
def clean_all(item): logger.info() for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero))) if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero)) platformtools.itemlist_refresh()
def clean_ready(item): logger.info("pelisalacarta.channels.descargas clean_ready") for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero))) if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): if download_item.downloadStatus == STATUS_CODES.completed: filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero)) platformtools.itemlist_refresh()
def browser(item): logger.info() itemlist = [] for file in filetools.listdir(item.url): if filetools.isdir(filetools.join(item.url, file)) and not file == "list": itemlist.append(Item(channel=item.channel, title=file, action=item.action, url= filetools.join(item.url, file))) else: itemlist.append(Item(channel=item.channel, title=file, action="play", url= filetools.join(item.url, file))) return itemlist
def clean_ready(item): logger.info("pelisalacarta.channels.descargas clean_ready") for fichero in sorted(filetools.listdir(item.url)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(item.url, fichero))) serie_name = "%s [%s]" % (download_item.contentSerieName, download_item.contentChannel) if not item.serie_name or item.serie_name == serie_name: if download_item.downloadStatus == 2: filetools.remove(os.path.join(item.url, fichero)) platformtools.itemlist_refresh()
def download_all(item): time.sleep(0.5) for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): if fichero.endswith(".json"): download_item = Item(path = os.path.join(DOWNLOAD_LIST_PATH, fichero)).fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero))) if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): if download_item.downloadStatus in [STATUS_CODES.stoped, STATUS_CODES.canceled]: res = start_download(download_item) platformtools.itemlist_refresh() # Si se ha cancelado paramos if res == STATUS_CODES.canceled: break
def download_all(item): time.sleep(0.5) for fichero in sorted(filetools.listdir(item.url)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(item.url, fichero))) serie_name = "%s [%s]" % (download_item.contentSerieName, download_item.contentChannel) if not item.serie_name or item.serie_name == serie_name: download_item.path = os.path.join(item.url, fichero) if download_item.downloadStatus in [0, 1]: res = start_download(download_item) platformtools.itemlist_refresh() # Si se ha cancelado paramos if res == 1: break
def restart_error(item): logger.info("pelisalacarta.channels.descargas restart_error") for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero))) if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): if download_item.downloadStatus == STATUS_CODES.error: if filetools.isfile(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)): filetools.remove(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)) update_json(item.path, {"downloadStatus" : STATUS_CODES.stoped, "downloadComplete" : 0 , "downloadProgress" : 0}) platformtools.itemlist_refresh()
def restart_error(item): logger.info("pelisalacarta.channels.descargas restart_error") for fichero in sorted(filetools.listdir(item.url)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(item.url, fichero))) serie_name = "%s [%s]" % (download_item.contentSerieName, download_item.contentChannel) if not item.serie_name or item.serie_name == serie_name: if download_item.downloadStatus == 3: if filetools.isfile(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)): filetools.remove(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)) download_item.downloadStatus = 0 download_item.downloadComplete = 0 download_item.downloadProgress = 0 download_item.downloadUrl = "" filetools.write(os.path.join(item.url, fichero), download_item.tojson()) platformtools.itemlist_refresh()
def elenco_file(item): logger.info("[biblioteca.py] elenco_file") itemlist=[] lista=filetools.listdir(config.get_library_path()) for list in lista: if list.endswith(tuple(['.flv','.mp4','.avi','.mkv'])): itemlist.append(Item(channel=item.channel, action="file", title="[COLOR azure]" + list + "[/COLOR]", url=filetools.join(config.get_library_path(), list), thumbnail="", fanart="", fulltitle=list, show="", folder=False )) return itemlist
def check_bookmark(savepath): from channels import favoritos for fichero in filetools.listdir(savepath): # Ficheros antiguos (".txt") if fichero.endswith(".txt"): # Esperamos 0.1 segundos entre ficheros, para que no se solapen los nombres de archivo time.sleep(0.1) # Obtenemos el item desde el .txt canal, titulo, thumbnail, plot, server, url, fulltitle = favoritos.readbookmark(fichero, savepath) item = Item(channel=canal, action="play", url=url, server=server, title=fulltitle, thumbnail=thumbnail, plot=plot, fanart=thumbnail, extra=os.path.join(savepath, fichero), fulltitle=fulltitle, folder=False) # Eliminamos el .txt os.remove(item.extra) item.extra = "" # Guardamos el archivo filename = os.path.join(savepath, str(time.time()) + ".json") filetools.write(filename, item.tojson())
def backups(item): from platformcode import platformtools logger.info() ruta = filetools.join(config.get_data_path(), 'backups') ruta_split = "" if "ruta" in item.title: heading = "Percorso di backup" if not filetools.exists(ruta): folders = "Directory non creata" else: folders = str(len(filetools.listdir(ruta))) + " copia/e di backup" 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 cartella non esiste", "Nessun backup salvato") else: dyesno = platformtools.dialog_yesno("I backup vengono cancellati", "Sei sicuro?") if dyesno: import shutil shutil.rmtree(ruta, ignore_errors=True)
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(library.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(library.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 'descargas' in list_canales: json_path = list_canales['descargas'] 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(library.LIBRARY_PATH, item_json.url) del list_canales['descargas'] # 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", "biblioteca"): 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 = 'descargas' 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 biblioteca de mitvspain if "library_filter_show" in item: item_json.show = item.library_filter_show.get( nom_canal, "") # Ejecutamos find_videos, del canal o común 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 = "biblioteca" 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", "biblioteca") == 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 delete(item): def delete_all(_item): for file in filetools.listdir(_item.path): if file.endswith(".strm") or file.endswith( ".nfo") or file.endswith(".json"): filetools.remove(filetools.join(_item.path, file)) raiz, carpeta_serie, ficheros = filetools.walk(_item.path).next() if ficheros == []: filetools.rmdir(_item.path) if config.is_xbmc(): import xbmc # esperamos 3 segundos para dar tiempo a borrar los ficheros xbmc.sleep(3000) # TODO mirar por qué no funciona al limpiar en la videoteca de Kodi al añadirle un path # limpiamos la videoteca de Kodi from platformcode import xbmc_videolibrary xbmc_videolibrary.clean() logger.info("Eliminados todos los enlaces") platformtools.itemlist_refresh() # logger.info(item.contentTitle) # logger.debug(item.tostring('\n')) if item.contentType == 'movie': heading = config.get_localized_string(70084) else: heading = config.get_localized_string(70085) if item.multicanal: # Obtener listado de canales opciones = [ config.get_localized_string(70086) % k.capitalize() for k in item.library_urls.keys() if k != "downloads" ] opciones.insert(0, heading) index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index == 0: # Seleccionado Eliminar pelicula/serie delete_all(item) elif index > 0: # Seleccionado Eliminar canal X canal = opciones[index].replace(config.get_localized_string(70079), "").lower() num_enlaces = 0 for fd in filetools.listdir(item.path): if fd.endswith(canal + '].json'): if filetools.remove(filetools.join(item.path, fd)): num_enlaces += 1 if num_enlaces > 0: # Actualizar .nfo head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo) del item_nfo.library_urls[canal] filetools.write(item.nfo, head_nfo + item_nfo.tojson()) msg_txt = config.get_localized_string(70087) % (num_enlaces, canal) logger.info(msg_txt) platformtools.dialog_notification(heading, msg_txt) platformtools.itemlist_refresh() else: if platformtools.dialog_yesno( heading, config.get_localized_string(70088) % item.infoLabels['title']): delete_all(item)
def findvideos(item): from core import autoplay from platformcode import platformtools logger.debug() # logger.debug("item:\n" + item.tostring('\n')) videolibrarytools.check_renumber_options(item) itemlist = [] list_canales = {} item_local = None # Disable autoplay # autoplay.set_status(False) if not item.contentTitle or not item.strm_path: logger.debug("Unable to search for videos due to lack of parameters") return [] if item.contentEpisodeNumber: content_title = str(item.contentSeason) + 'x' + (str(item.contentEpisodeNumber) if item.contentEpisodeNumber > 9 else '0' + str(item.contentEpisodeNumber)) else: content_title = item.contentTitle.strip().lower() 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)) item_json.contentChannel = "local" # Support for relative paths in downloads if filetools.is_relative(item_json.url): item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH, item_json.url) del list_canales['downloads'] # Check that the video has not been deleted 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) 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 = [] all_videolibrary = [] for nom_canal, json_path in list(list_canales.items()): if filtro_canal and filtro_canal != nom_canal.capitalize(): continue item_canal = Item() # We import the channel of the selected part try: if nom_canal == 'community': channel = __import__('specials.%s' % nom_canal, fromlist=["channels.%s" % nom_canal]) else: channel = __import__('channels.%s' % nom_canal, fromlist=["channels.%s" % nom_canal]) except ImportError: exec("import channels." + nom_canal + " as channel") except: dead_list = [] zombie_list = [] if nom_canal not in dead_list and nom_canal not in zombie_list: confirm = platformtools.dialog_yesno(config.get_localized_string(30131), config.get_localized_string(30132) % nom_canal.upper() + '\n' + config.get_localized_string(30133)) elif nom_canal in zombie_list: confirm = False else: confirm = True if confirm: # delete the channel from all movie and tvshow from past.utils import old_div num_enlaces = 0 dialog = platformtools.dialog_progress(config.get_localized_string(30131), config.get_localized_string(60005) % nom_canal) if not all_videolibrary: all_videolibrary = list_movies(Item()) + list_tvshows(Item()) for n, it in enumerate(all_videolibrary): if nom_canal in it.library_urls: dead_item = Item(multichannel=len(it.library_urls) > 1, contentType=it.contentType, dead=nom_canal, path=filetools.split(it.nfo)[0], nfo=it.nfo, library_urls=it.library_urls, infoLabels={'title': it.contentTitle}) num_enlaces += delete(dead_item) dialog.update(old_div(100*n, len(all_videolibrary))) dialog.close() msg_txt = config.get_localized_string(70087) % (num_enlaces, nom_canal) logger.info(msg_txt) platformtools.dialog_notification(config.get_localized_string(30131), msg_txt) platformtools.itemlist_refresh() if nom_canal not in dead_list: dead_list.append(nom_canal) continue else: if nom_canal not in zombie_list: zombie_list.append(nom_canal) if len(dead_list) > 0: for nom_canal in dead_list: if nom_canal in item.library_urls: del item.library_urls[nom_canal] item_json = Item().fromjson(filetools.read(json_path)) list_servers = [] try: # FILTERTOOLS # if the channel has a filter, the name it has saved is passed to it so that it filters correctly. if "list_language" in item_json: # if it comes from the addon video library if "library_filter_show" in item: item_json.show = item.library_filter_show.get(nom_canal, "") # We run find_videos, from the channel or common item_json.contentChannel = 'videolibrary' item_json.play_from = item.play_from item_json.nfo = item.nfo item_json.strm_path = item.strm_path 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) 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("The findvideos function for the channel %s failed" % 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()) # Change the title to the servers adding the name of the channel in front and the infoLabels and the images of the item if the server does not have for server in list_servers: server.contentChannel = server.channel server.channel = "videolibrary" server.nfo = item.nfo server.strm_path = item.strm_path server.play_from = item.play_from # Kodi 18 Compatibility - Prevents wheel from spinning around in Direct Links if server.action == 'play': server.folder = False # Channel name is added if desired if config.get_setting("quit_channel_name", "videolibrary") == 0: server.title = "%s: %s" % (nom_canal.capitalize(), server.title) if not server.thumbnail: server.thumbnail = item.thumbnail # logger.debug("server:\n%s" % server.tostring('\n')) itemlist.append(server) if autoplay.play_multi_channel(item, itemlist): # hideserver return [] add_download_items(item, itemlist) return itemlist
def delete(item): def delete_all(_item): for file in filetools.listdir(_item.path): if file.endswith(".strm") or file.endswith(".nfo") or file.endswith(".json")or file.endswith(".torrent"): filetools.remove(filetools.join(_item.path, file)) if _item.contentType == 'movie': heading = config.get_localized_string(70084) else: heading = config.get_localized_string(70085) if config.is_xbmc() and config.get_setting("videolibrary_kodi"): from platformcode import xbmc_videolibrary if _item.local_episodes_path: platformtools.dialog_ok(heading, config.get_localized_string(80047) % _item.infoLabels['title']) path_list = [_item.extra] xbmc_videolibrary.clean(path_list) raiz, carpeta_serie, ficheros = next(filetools.walk(_item.path)) if ficheros == []: filetools.rmdir(_item.path) elif platformtools.dialog_yesno(heading, config.get_localized_string(70081) % filetools.basename(_item.path)): filetools.rmdirtree(_item.path) logger.info("All links removed") xbmc.sleep(1000) platformtools.itemlist_refresh() # logger.debug(item.tostring('\n')) if item.contentType == 'movie': heading = config.get_localized_string(70084) else: heading = config.get_localized_string(70085) if item.multichannel: # Get channel list channels = [] opciones = [] for k in list(item.library_urls.keys()): if k != "downloads": opciones.append(config.get_localized_string(70086) % k.capitalize()) channels.append(k) if item.dead == '': opciones.insert(0, heading) index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index == 0: # Selected Delete movie / series delete_all(item) return elif index > 0: # Selected Delete channel X canal = opciones[index].replace(config.get_localized_string(70079), "").lower() channels.remove(canal) else: return else: canal = item.dead num_enlaces = 0 path_list = [] for fd in filetools.listdir(item.path): if fd.endswith(canal + '].json') or scrapertools.find_single_match(fd, r'%s]_\d+.torrent' % canal): if filetools.remove(filetools.join(item.path, fd)): num_enlaces += 1 # Remove strm and nfo if no other channel episode = fd.replace(' [' + canal + '].json', '') found_ch = False for ch in channels: if filetools.exists(filetools.join(item.path, episode + ' [' + ch + '].json')): found_ch = True break if found_ch == False: filetools.remove(filetools.join(item.path, episode + '.nfo')) strm_path = filetools.join(item.path, episode + '.strm') # if it is a local episode, do not delete the strm if 'plugin://plugin.video.kod/?' in filetools.read(strm_path): filetools.remove(strm_path) path_list.append(filetools.join(item.extra, episode + '.strm')) if config.is_xbmc() and config.get_setting("videolibrary_kodi") and path_list: from platformcode import xbmc_videolibrary xbmc_videolibrary.clean(path_list) if num_enlaces > 0: # Update .nfo head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo) del item_nfo.library_urls[canal] if item_nfo.emergency_urls and item_nfo.emergency_urls.get(canal, False): del item_nfo.emergency_urls[canal] filetools.write(item.nfo, head_nfo + item_nfo.tojson()) return num_enlaces else: if platformtools.dialog_yesno(heading, config.get_localized_string(70088) % item.infoLabels['title']): delete_all(item) return 1 else: return 0
def execute_sql_kodi(sql): """ Ejecuta la consulta sql contra la base de datos de kodi @param sql: Consulta sql valida @type sql: str @return: Numero de registros modificados o devueltos por la consulta @rtype nun_records: int @return: lista con el resultado de la consulta @rtype records: list of tuples """ logger.info() file_db = "" nun_records = 0 records = None # Buscamos el archivo de la BBDD de videos segun la version de kodi video_db = config.get_platform(True)['video_db'] if video_db: file_db = filetools.join( xbmc.translatePath("special://userdata/Database"), video_db) # metodo alternativo para localizar la BBDD if not file_db or not filetools.exists(file_db): file_db = "" for f in filetools.listdir( xbmc.translatePath("special://userdata/Database")): path_f = filetools.join( xbmc.translatePath("special://userdata/Database"), f) if filetools.isfile(path_f) and f.lower().startswith( 'myvideos') and f.lower().endswith('.db'): file_db = path_f break if file_db: logger.info("Archivo de BD: %s" % file_db) conn = None try: import sqlite3 conn = sqlite3.connect(file_db) cursor = conn.cursor() logger.info("Ejecutando sql: %s" % sql) cursor.execute(sql) conn.commit() records = cursor.fetchall() if sql.lower().startswith("select"): nun_records = len(records) if nun_records == 1 and records[0][0] is None: nun_records = 0 records = [] else: nun_records = conn.total_changes conn.close() logger.info("Consulta ejecutada. Registros: %s" % nun_records) except: logger.error("Error al ejecutar la consulta sql") if conn: conn.close() else: logger.debug("Base de datos no encontrada") return nun_records, records
def execute_sql_kodi(sql): """ Ejecuta la consulta sql contra la base de datos de kodi @param sql: Consulta sql valida @type sql: str @return: Numero de registros modificados o devueltos por la consulta @rtype nun_records: int @return: lista con el resultado de la consulta @rtype records: list of tuples """ logger.info() file_db = "" nun_records = 0 records = None # Buscamos el archivo de la BBDD de videos segun la version de kodi video_db = config.get_platform(True)['video_db'] if video_db: file_db = filetools.join(xbmc.translatePath("special://userdata/Database"), video_db) # metodo alternativo para localizar la BBDD if not file_db or not filetools.exists(file_db): file_db = "" for f in filetools.listdir(xbmc.translatePath("special://userdata/Database")): path_f = filetools.join(xbmc.translatePath("special://userdata/Database"), f) if filetools.isfile(path_f) and f.lower().startswith('myvideos') and f.lower().endswith('.db'): file_db = path_f break if file_db: logger.info("Archivo de BD: %s" % file_db) conn = None try: import sqlite3 conn = sqlite3.connect(file_db) cursor = conn.cursor() logger.info("Ejecutando sql: %s" % sql) cursor.execute(sql) conn.commit() records = cursor.fetchall() if sql.lower().startswith("select"): nun_records = len(records) if nun_records == 1 and records[0][0] is None: nun_records = 0 records = [] else: nun_records = conn.total_changes conn.close() logger.info("Consulta ejecutada. Registros: %s" % nun_records) except: logger.error("Error al ejecutar la consulta sql") if conn: conn.close() else: logger.debug("Base de datos no encontrada") return nun_records, records
def move_to_libray(item): if item.contentType == 'movie': FOLDER = FOLDER_MOVIES path_title = "%s [%s]" % (item.contentTitle.strip(), item.infoLabels['IMDBNumber']) move_path = filetools.join(config.get_videolibrary_path(), FOLDER, path_title) else: FOLDER = FOLDER_TVSHOWS path_title = "%s [%s]" % (item.contentSerieName, item.infoLabels['IMDBNumber']) move_path = filetools.join(config.get_videolibrary_path(), FOLDER) download_path = filetools.join(config.get_setting("downloadpath"), item.downloadFilename) library_path = filetools.join(move_path, *filetools.split(item.downloadFilename)) final_path = download_path if config.get_setting("library_add", "downloads") == True and config.get_setting( "library_move", "downloads") == True: if not filetools.isdir(filetools.dirname(library_path)): filetools.mkdir(filetools.dirname(library_path)) if filetools.isfile(library_path) and filetools.isfile(download_path): filetools.remove(library_path) if filetools.isfile(download_path): if filetools.move(download_path, library_path): final_path = library_path if len(filetools.listdir(filetools.dirname(download_path))) == 0: filetools.rmdir(filetools.dirname(download_path)) logger.info('ITEM = ' + str(item)) name = item.contentTitle if item.contentType == 'movie' else str( item.infoLabels['season']) + 'x' + str( item.infoLabels['episode']).zfill(2) list_item = os.listdir( filetools.join(config.get_videolibrary_path(), FOLDER, path_title)) clean = False for File in list_item: filename = File.lower() name = name.lower() if filename.startswith(name) and (filename.endswith('.strm') or filename.endswith('.json') or filename.endswith('.nfo')): clean = True logger.info('Delete File: ' + str( os.path.join(config.get_videolibrary_path(), FOLDER, path_title, File))) os.remove( os.path.join(config.get_videolibrary_path(), FOLDER, path_title, File)) from platformcode import xbmc_videolibrary xbmc_videolibrary.update(FOLDER) if clean == True: import xbmc while xbmc.getCondVisibility('Library.IsScanningVideo()'): xbmc.sleep(500) xbmc_videolibrary.clean() if config.get_setting("library_add", "downloads") == True and config.get_setting( "library_move", "downloads") == False: if filetools.isfile(final_path): if item.contentType == "movie" and item.infoLabels["tmdb_id"]: library_item = Item(title=config.get_localized_string(70228) % item.downloadFilename, channel="downloads", action="findvideos", infoLabels=item.infoLabels, url=final_path) videolibrarytools.save_movie(library_item) elif item.contentType == "episode" and item.infoLabels["tmdb_id"]: library_item = Item(title=config.get_localized_string(70228) % item.downloadFilename, channel="downloads", action="findvideos", infoLabels=item.infoLabels, url=final_path) tvshow = Item( channel="downloads", contentType="tvshow", infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]}) videolibrarytools.save_tvshow(tvshow, [library_item])
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 = 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) 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: 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_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_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)) ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial try: 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) 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) 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 for server in 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 #### 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)
def rename(File): jsonPath = xbmc.translatePath(config.get_setting('downloadlistpath')) json = jsontools.load(open(filetools.join(jsonPath, File), "r").read()) filePath = filetools.join( xbmc.translatePath(config.get_setting('downloadpath')), json['downloadFilename']) if json['infoLabels']['mediatype'] == 'movie': if filetools.isdir(filePath): extension = '' files = filetools.listdir(filePath) oldName = json['downloadFilename'] newName = json['backupFilename'] for f in files: ext = os.path.splitext(f)[-1] if ext in extensions_list: extension = ext filetools.rename(filetools.join(filePath, f), f.replace(oldName, newName)) filetools.rename(filePath, newName) jsontools.update_node(filetools.join(newName, newName + extension), File, 'downloadFilename', jsonPath) else: oldName = json['downloadFilename'] newName = json['backupFilename'] + os.path.splitext(oldName)[-1] filetools.rename(filePath, newName) jsontools.update_node(newName, File, 'downloadFilename', jsonPath) else: sep = '/' if filePath.lower().startswith("smb://") else os.sep FolderName = json['backupFilename'].split(sep)[0] Title = re.sub(r'(\s*\[[^\]]+\])', '', FolderName) if filetools.isdir(filePath): files = filetools.listdir(filePath) file_dict = {} for f in files: title = process_filename(f, Title, ext=False) ext = os.path.splitext(f)[-1] name = os.path.splitext(f)[0] if title not in file_dict and ext in extensions_list: file_dict[title] = name for title, name in file_dict.items(): for f in files: if name in f: filetools.rename(filetools.join(filePath, f), f.replace(name, title)) filetools.rename(filePath, FolderName) jsontools.update_node(FolderName, File, 'downloadFilename', jsonPath) else: filename = filetools.split(filePath)[-1] title = process_filename(filename, Title) NewFolder = filetools.join(config.get_setting('downloadpath'), FolderName) if not filetools.isdir(NewFolder): filetools.mkdir(NewFolder) from_folder = filetools.join(config.get_setting('downloadpath'), filename) to_folder = filetools.join(config.get_setting('downloadpath'), FolderName, title) filetools.move(from_folder, to_folder) jsontools.update_node(filetools.join(FolderName, title), File, 'downloadFilename', jsonPath)
def update_libtorrent(): logger.info() if not config.get_setting("mct_buffer", server="torrent", default=""): default = config.get_setting("torrent_client", server="torrent", default=0) config.set_setting("torrent_client", default, server="torrent") config.set_setting("mct_buffer", "50", server="torrent") if config.get_setting("mct_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("mct_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_background_download", True, server="torrent") config.set_setting("mct_rar_unpack", True, server="torrent") config.set_setting("bt_buffer", "50", server="torrent") if config.get_setting("bt_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("bt_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_download_limit", "", server="torrent") config.set_setting("magnet2torrent", False, server="torrent") if not filetools.exists( filetools.join( config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')): filetools.mkdir( filetools.join( config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')) if not filetools.exists( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')): filetools.mkdir( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')) filetools.mkdir( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrents')) if not filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) or not \ config.get_setting("unrar_path", server="torrent", default=""): path = filetools.join(config.get_runtime_path(), 'lib', 'rarfiles') creationflags = '' sufix = '' unrar = '' for device in filetools.listdir(path): if xbmc.getCondVisibility( "system.platform.android") and 'android' not in device: continue if xbmc.getCondVisibility( "system.platform.windows") and 'windows' not in device: continue if not xbmc.getCondVisibility("system.platform.windows") and not xbmc.getCondVisibility("system.platform.android") \ and ('android' in device or 'windows' in device): continue if 'windows' in device: creationflags = 0x08000000 sufix = '.exe' else: creationflags = '' sufix = '' unrar = filetools.join(path, device, 'unrar%s') % sufix if not filetools.exists(unrar): unrar = '' if unrar: if not xbmc.getCondVisibility("system.platform.windows"): try: if xbmc.getCondVisibility("system.platform.android"): # Para Android copiamos el binario a la partición del sistema unrar_org = unrar unrar = filetools.join('special://xbmc/', 'files').replace( '/cache/apk/assets', '') if not filetools.exists(unrar): filetools.mkdir(unrar) unrar = filetools.join(unrar, 'unrar') filetools.copy(unrar_org, unrar, silent=True) filetools.chmod(unrar, '777') except: logger.info('######## UnRAR ERROR in path: %s' % str(unrar), force=True) logger.error(traceback.format_exc()) try: if xbmc.getCondVisibility("system.platform.windows"): p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags) else: p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() if p.returncode != 0 or error_cmd: logger.info('######## UnRAR returncode in module %s: %s, %s in %s' % \ (device, str(p.returncode), str(error_cmd), unrar), force=True) unrar = '' else: logger.info('######## UnRAR OK in %s: %s' % (device, unrar), force=True) break except: logger.info('######## UnRAR ERROR in module %s: %s' % (device, unrar), force=True) logger.error(traceback.format_exc(1)) unrar = '' if unrar: config.set_setting("unrar_path", unrar, server="torrent") # Ahora descargamos la última versión disponible de Libtorrent para esta plataforma try: version_base = filetools.join(config.get_runtime_path(), 'lib', 'python_libtorrent') if config.get_setting("libtorrent_version", server="torrent", default="") \ and config.get_setting("libtorrent_path", server="torrent", default=""): current_system, current_version = config.get_setting( "libtorrent_version", server="torrent", default="").split('/') else: current_system = '' current_version = '' if '1.1.1' in current_version or 'arm' in current_system or 'aarch64' in current_system: current_version = '' if current_version.startswith('2') and xbmc.getCondVisibility( "system.platform.linux"): current_version = '' version_base = filetools.join(version_base, current_system) if current_version: old_version = current_version new_version = sorted(filetools.listdir(version_base)) new_version_alt = new_version[:] if new_version: for folder in new_version_alt: if not filetools.isdir(filetools.join( version_base, folder)): new_version.remove(folder) if old_version != new_version[-1]: current_version = '' else: current_version = '' except: current_version = '' logger.error(traceback.format_exc(1)) custom_code_json = filetools.exists( filetools.join(config.get_runtime_path(), "custom_code.json")) if custom_code_json and current_version: msg = 'Libtorrent_path: %s' % config.get_setting( "libtorrent_path", server="torrent", default="") if current_version not in msg: msg += ' - Libtorrent_version: %s/%s' % (current_system, current_version) logger.info(msg, force=True) return try: logger.info('Libtorrent stored version: %s, %s' % (config.get_setting("libtorrent_version", \ server="torrent", default=""), str(custom_code_json)), force=True) from lib.python_libtorrent.python_libtorrent import get_libtorrent except Exception as e: logger.error(traceback.format_exc(1)) if not PY3: e = unicode(str(e), "utf8", errors="replace").encode("utf8") config.set_setting("libtorrent_path", "", server="torrent") if not config.get_setting( "libtorrent_error", server="torrent", default=''): config.set_setting("libtorrent_error", str(e), server="torrent") return
def get_environment(): """ Devuelve las variables de entorno del OS, de Kodi y de Alfa más habituales, necesarias para el diagnóstico de fallos """ try: import base64 import ast PLATFORM = config.get_system_platform() environment = config.get_platform(full_version=True) environment['num_version'] = str(environment['num_version']) environment['python_version'] = '%s (%s, %s)' % (str(platform.python_version()), \ str(sys.api_version), str(platform.python_implementation())) environment['os_release'] = str(platform.release()) environment['prod_model'] = '' try: import multiprocessing environment['proc_num'] = ' (%sx)' % str( multiprocessing.cpu_count()) except: environment['proc_num'] = '' if PLATFORM in ['windows', 'xbox']: environment['os_name'] = PLATFORM.capitalize() try: if platform.platform(): environment['os_release'] = str( platform.platform()).replace('Windows-', '') elif platform._syscmd_ver()[2]: environment['os_release'] = str(platform._syscmd_ver()[2]) command = ["wmic", "cpu", "get", "name"] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=0x08000000) output_cmd, error_cmd = p.communicate() if PY3 and isinstance(output_cmd, bytes): output_cmd = output_cmd.decode() output_cmd = re.sub(r'\n|\r|\s{2}', '', output_cmd) environment['prod_model'] = str(scrapertools.find_single_match(output_cmd, \ '\w+.*?(?i)(?:Intel\(R\))?(?:\s*Core\(TM\))\s*(.*?CPU.*?)\s*(?:\@|$)')) except: pass elif PLATFORM in ['android', 'atv2']: environment['os_name'] = PLATFORM.capitalize() try: for label_a in subprocess.check_output('getprop').split(FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'build.version.release' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, ':\s*\[(.*?)\]$')) if 'product.model' in label_a: environment['prod_model'] = str( scrapertools.find_single_match( label_a, ':\s*\[(.*?)\]$')) except: try: for label_a in filetools.read(os.environ['ANDROID_ROOT'] + '/build.prop').split(): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'build.version.release' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, '=(.*?)$')) if 'product.model' in label_a: environment['prod_model'] = str( scrapertools.find_single_match( label_a, '=(.*?)$')) except: pass environment['prod_model'] += ' (%s)' % config.is_rooted( silent=True) elif PLATFORM in ['linux', 'raspberry']: environment['os_name'] = PLATFORM.capitalize( ) if 'linux' in PLATFORM else 'RaspberryPi' try: for label_a in subprocess.check_output('hostnamectl').split( FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'Operating' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, 'Operating\s*S\w+:\s*(.*?)\s*$')) break for label_a in subprocess.check_output( ['cat', '/proc/cpuinfo']).split(FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'model name' in label_a: environment['prod_model'] = str(scrapertools.find_single_match(label_a, \ 'model.*?:\s*(?i)(?:Intel\(R\))?(?:\s*Core\(TM\))\s*(.*?CPU.*?)\s*(?:\@|$)')) break except: pass if 'libreelec' in environment['os_release'].lower( ) and PLATFORM != 'raspberry': environment['os_name'] = 'RaspberryPi' if config.get_setting("caching", default=True): try: PLATFORM = 'raspberry' window = xbmcgui.Window(10000) window.setProperty("alfa_system_platform", PLATFORM) except: pass else: environment['os_name'] = str(PLATFORM.capitalize()) if not environment['os_release']: environment['os_release'] = str(platform.release()) if environment['proc_num'] and environment['prod_model']: environment['prod_model'] += environment['proc_num'] environment['machine'] = str(platform.machine()) environment['architecture'] = str(sys.maxsize > 2**32 and "64-bit" or "32-bit") environment['language'] = str(xbmc.getInfoLabel('System.Language')) environment['cpu_usage'] = str(xbmc.getInfoLabel('System.CpuUsage')) environment['mem_total'] = str( xbmc.getInfoLabel('System.Memory(total)')).replace('MB', '').replace( 'KB', '') environment['mem_free'] = str( xbmc.getInfoLabel('System.Memory(free)')).replace('MB', '').replace( 'KB', '') if not environment['mem_total'] or not environment['mem_free']: try: if environment['os_name'].lower() in ['windows', 'xbox']: kernel32 = ctypes.windll.kernel32 c_ulong = ctypes.c_ulong c_ulonglong = ctypes.c_ulonglong class MEMORYSTATUS(ctypes.Structure): _fields_ = [('dwLength', c_ulong), ('dwMemoryLoad', c_ulong), ('dwTotalPhys', c_ulonglong), ('dwAvailPhys', c_ulonglong), ('dwTotalPageFile', c_ulonglong), ('dwAvailPageFile', c_ulonglong), ('dwTotalVirtual', c_ulonglong), ('dwAvailVirtual', c_ulonglong), ('availExtendedVirtual', c_ulonglong)] memoryStatus = MEMORYSTATUS() memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS) kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus)) environment['mem_total'] = str( old_div(int(memoryStatus.dwTotalPhys), (1024**2))) environment['mem_free'] = str( old_div(int(memoryStatus.dwAvailPhys), (1024**2))) else: with open('/proc/meminfo') as f: meminfo = f.read() environment['mem_total'] = str( old_div( int( re.search(r'MemTotal:\s+(\d+)', meminfo).groups()[0]), 1024)) environment['mem_free'] = str( old_div( int( re.search(r'MemAvailable:\s+(\d+)', meminfo).groups()[0]), 1024)) except: environment['mem_total'] = '' environment['mem_free'] = '' try: environment['kodi_buffer'] = '20' environment['kodi_bmode'] = '0' environment['kodi_rfactor'] = '4.0' if filetools.exists( filetools.join("special://userdata", "advancedsettings.xml")): advancedsettings = filetools.read( filetools.join("special://userdata", "advancedsettings.xml")).split('\n') for label_a in advancedsettings: if 'memorysize' in label_a: environment['kodi_buffer'] = str( old_div( int( scrapertools.find_single_match( label_a, '>(\d+)<\/')), 1024**2)) if 'buffermode' in label_a: environment['kodi_bmode'] = str( scrapertools.find_single_match( label_a, '>(\d+)<\/')) if 'readfactor' in label_a: environment['kodi_rfactor'] = str( scrapertools.find_single_match( label_a, '>(.*?)<\/')) except: pass environment['userdata_path'] = str(config.get_data_path()) environment['userdata_path_perm'] = filetools.file_info( environment['userdata_path']) if not environment['userdata_path_perm']: del environment['userdata_path_perm'] try: if environment['os_name'].lower() in ['windows', 'xbox']: free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(environment['userdata_path']), None, None, ctypes.pointer(free_bytes)) environment['userdata_free'] = str( round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['userdata_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['userdata_free'] = '?' if environment.get('userdata_path_perm', ''): environment['userdata_path'] = environment['userdata_path_perm'] del environment['userdata_path_perm'] environment['torrent_lang'] = '%s/%s' % (config.get_setting("channel_language", default="").upper(), \ config.get_setting("second_language", default="").upper()) try: environment['videolab_series'] = '?' environment['videolab_episodios'] = '?' environment['videolab_pelis'] = '?' environment['videolab_path'] = str(config.get_videolibrary_path()) environment['videolab_path_perm'] = filetools.file_info( environment['videolab_path']) if not environment['videolab_path_perm']: environment['videolab_path_perm'] = environment[ 'videolab_path'] if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))))) counter = 0 for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): for file in files: if file.endswith('.strm'): counter += 1 environment['videolab_episodios'] = str(counter) if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))): environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))))) except: pass try: video_updates = [ 'No', 'Inicio', 'Una vez', 'Inicio+Una vez', 'Dos veces al día' ] environment['videolab_update'] = str( video_updates[config.get_setting("update", "videolibrary")]) if config.get_setting("videolibrary_backup_scan", "videolibrary", default=False): environment['videolab_update'] += ' (Solo SCAN)' except: environment['videolab_update'] = '?' try: if environment['os_name'].lower() in ['windows', 'xbox']: free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(environment['videolab_path']), None, None, ctypes.pointer(free_bytes)) environment['videolab_free'] = str( round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['videolab_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['videolab_free'] = '?' torrent_paths = torrent_dirs() environment['torrent_list'] = [] environment['torrentcli_option'] = '' environment['torrent_error'] = '' environment['torrentcli_rar'] = config.get_setting("mct_rar_unpack", server="torrent", default=True) environment['torrentcli_backgr'] = config.get_setting( "mct_background_download", server="torrent", default=True) environment['torrentcli_lib_path'] = config.get_setting( "libtorrent_path", server="torrent", default="") if environment['torrentcli_lib_path']: lib_path = 'Activo' else: lib_path = 'Inactivo' if config.get_setting("libtorrent_version", server="torrent", default=""): lib_path += '-%s' % config.get_setting( "libtorrent_version", server="torrent", default="") environment['torrentcli_unrar'] = config.get_setting("unrar_path", server="torrent", default="") if environment['torrentcli_unrar']: unrar = config.get_setting("unrar_device", server="torrent", default="").capitalize() else: unrar = 'Inactivo' torrent_id = config.get_setting("torrent_client", server="torrent", default=0) environment['torrentcli_option'] = str(torrent_id) torrent_options = platformtools.torrent_client_installed() if lib_path != 'Inactivo': torrent_options = [': MCT'] + torrent_options torrent_options = [': BT'] + torrent_options environment['torrent_list'].append({'Torrent_opt': str(torrent_id), 'Libtorrent': lib_path, \ 'RAR_Auto': str(environment['torrentcli_rar']), \ 'RAR_backgr': str(environment['torrentcli_backgr']), \ 'UnRAR': unrar}) environment['torrent_error'] = config.get_setting("libtorrent_error", server="torrent", default="") if environment['torrent_error']: environment['torrent_list'].append( {'Libtorrent_error': environment['torrent_error']}) for torrent_option in torrent_options: cliente = dict() cliente['D_load_Path'] = '' cliente['Libre'] = '?' cliente['Plug_in'] = scrapertools.find_single_match( torrent_option, ':\s*(\w+)') if cliente['Plug_in'] not in ['BT', 'MCT']: cliente['Plug_in'] = cliente['Plug_in'].capitalize() cliente['D_load_Path'] = torrent_paths[cliente['Plug_in'].upper()] cliente['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) cliente['Buffer'] = str(torrent_paths[cliente['Plug_in'].upper() + '_buffer']) cliente['Version'] = str(torrent_paths[cliente['Plug_in'].upper() + '_version']) if cliente['Plug_in'].upper() == 'TORREST': cliente['Buffer'] = str( int( int(torrent_paths[cliente['Plug_in'].upper() + '_buffer']) / (1024 * 1024))) bin_path = filetools.join('special://home', 'addons', 'plugin.video.torrest', 'resources', 'bin') if filetools.exists(bin_path): cliente['Platform'] = str(filetools.listdir(bin_path)[0]) else: cliente['Platform'] = 'None' try: __settings__ = xbmcaddon.Addon(id="plugin.video.torrest") cliente['Platform'] += ': %s: %s:%s' % (str(__settings__.getSetting("service_enabled")), \ str(__settings__.getSetting("service_ip")), str(__settings__.getSetting("port"))) except: pass #cliente['Options'] = str(filetools.read(filetools.join('special://masterprofile', \ # 'addon_data', 'plugin.video.torrest', 'settings.xml'))) if torrent_paths.get(cliente['Plug_in'].upper() + '_memory_size', ''): cliente['Memoria'] = str( torrent_paths[cliente['Plug_in'].upper() + '_memory_size']) if cliente.get('D_load_Path', ''): try: if environment['os_name'].lower() in ['windows', 'xbox']: free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(cliente['D_load_Path']), None, None, ctypes.pointer(free_bytes)) cliente['Libre'] = str(round(float(free_bytes.value) / \ (1024**3), 3)).replace('.', ',') else: disk_space = os.statvfs(cliente['D_load_Path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize cliente['Libre'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)).replace('.', ',') except: pass if cliente.get('D_load_Path_perm', ''): cliente['D_load_Path'] = cliente['D_load_Path_perm'] del cliente['D_load_Path_perm'] environment['torrent_list'].append(cliente) environment['proxy_active'] = '' try: proxy_channel_bloqued_str = base64.b64decode( config.get_setting('proxy_channel_bloqued')).decode('utf-8') proxy_channel_bloqued = dict() proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str) for channel_bloqued, proxy_active in list( proxy_channel_bloqued.items()): if proxy_active != 'OFF': environment['proxy_active'] += channel_bloqued + ', ' except: pass if not environment['proxy_active']: environment['proxy_active'] = 'OFF' environment['proxy_active'] = environment['proxy_active'].rstrip(', ') for root, folders, files in filetools.walk("special://logpath/"): for file in files: if file.lower() in ['kodi.log', 'jarvis.log', 'spmc.log', 'cemc.log', \ 'mygica.log', 'wonderbox.log', 'leiapp,log', \ 'leianmc.log', 'kodiapp.log', 'anmc.log', \ 'latin-anmc.log']: environment['log_path'] = str(filetools.join(root, file)) break else: environment['log_path'] = '' break if environment.get('log_path', ''): environment['log_size_bytes'] = str( filetools.getsize(environment['log_path'])) environment['log_size'] = str(round(float(environment['log_size_bytes']) / \ (1024*1024), 3)) else: environment['log_size_bytes'] = '' environment['log_size'] = '' environment['debug'] = str(config.get_setting('debug')) environment['addon_version'] = '%s (Upd: %s h.)' % (str(config.get_addon_version(from_xml=True)), \ str(config.get_setting("addon_update_timer", default=12)).replace('0', 'No')) environment['assistant_version'] = str(None) if filetools.exists(filetools.join(config.get_data_path(), 'alfa-desktop-assistant.version')) \ and config.get_setting("assistant_mode") == "este": environment['assistant_version'] = filetools.read( filetools.join(config.get_data_path(), 'alfa-desktop-assistant.version')) environment['assistant_path'] = str( filetools.file_info( filetools.join(config.get_data_path(), 'assistant'))) elif filetools.exists( filetools.join(config.get_data_path(), 'alfa-mobile-assistant.version')): environment['assistant_version'] = filetools.read( filetools.join(config.get_data_path(), 'alfa-mobile-assistant.version')) environment['assistant_version'] += '; Req: %s' % str( config.get_setting('assistant_binary', default=False)) environment['assistant_cf_ua'] = str( config.get_setting('cf_assistant_ua', default=None)) assistant_path = filetools.join(os.getenv('ANDROID_STORAGE'), 'emulated', '0', 'Android', 'data', 'com.alfa.alfamobileassistant') if PLATFORM in ['android', 'atv2' ] and filetools.exists(assistant_path): environment['assistant_path'] = str( filetools.file_info(assistant_path)) except: logger.error(traceback.format_exc()) environment = {} environment['log_size'] = '' environment['cpu_usage'] = '' environment['python_version'] = '' environment['log_path'] = '' environment['userdata_free'] = '' environment['mem_total'] = '' environment['machine'] = '' environment['platform'] = '' environment['videolab_path'] = '' environment['num_version'] = '' environment['os_name'] = '' environment['video_db'] = '' environment['userdata_path'] = '' environment['log_size_bytes'] = '' environment['name_version'] = '' environment['language'] = '' environment['mem_free'] = '' environment['prod_model'] = '' environment['proxy_active'] = '' environment['architecture'] = '' environment['os_release'] = '' environment['videolab_free'] = '' environment['kodi_buffer'] = '' environment['kodi_bmode'] = '' environment['kodi_rfactor'] = '' environment['videolab_series'] = '' environment['videolab_episodios'] = '' environment['videolab_pelis'] = '' environment['videolab_update'] = '' environment['videolab_path_perm'] = '' environment['debug'] = '' environment['addon_version'] = '' environment['torrent_list'] = [] environment['torrent_lang'] = '' environment['torrentcli_option'] = '' environment['torrentcli_rar'] = '' environment['torrentcli_lib_path'] = '' environment['torrentcli_unrar'] = '' environment['torrent_error'] = '' environment['assistant_version'] = '' environment['assistant_cf_ua'] = '' return environment
def mainlist(item): logger.info() itemlist = [] #Lista de archivos for file in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): #Saltamos todos los que no sean JSON if not file.endswith(".json"): continue #cargamos el item file = os.path.join(DOWNLOAD_LIST_PATH, file) i = Item(path = file).fromjson(filetools.read(file)) i.thumbnail = i.contentThumbnail #Listado principal if not item.contentType == "tvshow": # Series if i.contentType == "episode": #Comprobamos que la serie no este ya en el itemlist if not filter(lambda x: x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel, itemlist): title = TITLE_TVSHOW % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel) itemlist.append(Item(title = title, channel= "descargas", action= "mainlist", contentType = "tvshow", contentSerieName = i.contentSerieName, contentChannel = i.contentChannel, downloadStatus = i.downloadStatus, downloadProgress = [i.downloadProgress], fanart = i.fanart, thumbnail = i.thumbnail)) else: s = filter(lambda x: x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel, itemlist)[0] s.downloadProgress.append(i.downloadProgress) downloadProgress = sum(s.downloadProgress) / len(s.downloadProgress) if not s.downloadStatus in [STATUS_CODES.error, STATUS_CODES.canceled] and not i.downloadStatus in [STATUS_CODES.completed, STATUS_CODES.stoped]: s.downloadStatus = i.downloadStatus s.title = TITLE_TVSHOW % (STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel) # Peliculas elif i.contentType == "movie" or i.contentType == "video": i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) #Listado dentro de una serie else: if i.contentType == "episode" and i.contentSerieName == item.contentSerieName and i.contentChannel == item.contentChannel: i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber,i.contentTitle)) itemlist.append(i) estados = [i.downloadStatus for i in itemlist] # Si hay alguno completado if 2 in estados: itemlist.insert(0, Item(channel=item.channel, action="clean_ready", title="Eliminar descargas completadas", contentType = item.contentType, contentChannel=item.contentChannel, contentSerieName = item.contentSerieName, text_color = "sandybrown")) # Si hay alguno con error if 3 in estados: itemlist.insert(0, Item(channel=item.channel, action="restart_error", title="Reiniciar descargas con error", contentType = item.contentType, contentChannel=item.contentChannel, contentSerieName = item.contentSerieName, text_color = "orange")) # Si hay alguno pendiente if 1 in estados or 0 in estados: itemlist.insert(0, Item(channel=item.channel, action="download_all", title="Descargar todo", contentType = item.contentType, contentChannel=item.contentChannel, contentSerieName = item.contentSerieName, text_color = "green")) if len(itemlist): itemlist.insert(0, Item(channel=item.channel, action="clean_all", title="Eliminar todo", contentType = item.contentType, contentChannel=item.contentChannel, contentSerieName = item.contentSerieName, text_color = "red")) if not item.contentType == "tvshow" and config.get_setting("browser", "descargas") == True: itemlist.insert(0, Item(channel=item.channel, action="browser", title="Ver archivos descargados", url = DOWNLOAD_PATH, text_color = "yellow")) if not item.contentType == "tvshow": itemlist.insert(0, Item(channel=item.channel, action="settings", title="Configuración descargas...", text_color = "blue")) return itemlist
platform['version'] = default_path sizefile_path = filetools.join(__root__, platform['system'], platform['version']) if not filetools.exists(sizefile_path): log('set_version: no sizefile at %s back to default %s' % (sizefile_path, default_path)) platform['version'] = default_path sizefile_path = filetools.join(__root__, platform['system'], platform['version']) if not filetools.exists(sizefile_path): log('set_version: no default at %s searching for any version' % sizefile_path) try: versions = sorted( filetools.listdir( filetools.join(__root__, platform['system']))) except: versions = [] versions_for = versions[:] for ver in versions_for: if ver not in VERSIONS: versions.remove(ver) continue if not filetools.isdir( filetools.join(__root__, platform['system'], ver)): versions.remove(ver) VERSIONS_for = VERSIONS[:] for ver in VERSIONS_for: if ver not in versions:
def eliminar(item): def eliminar_todo(_item): filetools.rmdirtree(_item.path) if config.is_xbmc(): import xbmc # esperamos 3 segundos para dar tiempo a borrar los ficheros xbmc.sleep(3000) # TODO mirar por qué no funciona al limpiar en la biblioteca de Kodi al añadirle un path # limpiamos la biblioteca de Kodi from platformcode import xbmc_library xbmc_library.clean() logger.info("Eliminados todos los enlaces") platformtools.itemlist_refresh() # logger.info(item.contentTitle) # logger.debug(item.tostring('\n')) if item.contentType == 'movie': heading = "Eliminar película" else: heading = "Eliminar serie" if item.multicanal: # Obtener listado de canales opciones = [ "Eliminar solo los enlaces de %s" % k.capitalize() for k in item.library_urls.keys() if k != "descargas" ] opciones.insert(0, heading) index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index == 0: # Seleccionado Eliminar pelicula/serie eliminar_todo(item) elif index > 0: # Seleccionado Eliminar canal X canal = opciones[index].replace("Eliminar solo los enlaces de ", "").lower() num_enlaces = 0 for fd in filetools.listdir(item.path): if fd.endswith(canal + '].json'): if filetools.remove(filetools.join(item.path, fd)): num_enlaces += 1 if num_enlaces > 0: # Actualizar .nfo head_nfo, item_nfo = library.read_nfo(item.nfo) del item_nfo.library_urls[canal] filetools.write(item.nfo, head_nfo + item_nfo.tojson()) msg_txt = "Eliminados %s enlaces del canal %s" % (num_enlaces, canal) logger.info(msg_txt) platformtools.dialog_notification(heading, msg_txt) platformtools.itemlist_refresh() else: if platformtools.dialog_yesno( heading, "¿Realmente desea eliminar '%s' de su biblioteca?" % item.infoLabels['title']): eliminar_todo(item)
def mainlist(item): logger.info("pelisalacarta.channels.descargas mainlist") itemlist = [] status_color = {0: "orange", 1: "orange", 2: "green", 3: "red"} item.url = config.get_setting("downloadlistpath") series = {} for file in sorted(filetools.listdir(item.url)): file = os.path.join(item.url, file) # Saltamos los archivos que no sean .json if not file.endswith(".json"): continue i = Item().fromjson(filetools.read(file)) i.path = file i.thumbnail = i.contentThumbnail #item.serie_name significa que estamos desntro de una serie if not item.serie_name: # Series if i.contentType == "episode": serie_name = "%s [%s]" % (i.contentSerieName, i.contentChannel) if not serie_name in series: title = serie_name series = {serie_name: {"downloadProgress": [i.downloadProgress], "downloadStatus": [i.downloadStatus]}} i.title=title i.contentSeason = "" i.contntEpisodeNumber = "" i.action = "mainlist" i.serie_name = serie_name itemlist.append(i) else: series[serie_name]["downloadProgress"].append(i.downloadProgress) series[serie_name]["downloadStatus"].append(i.downloadStatus) # Peliculas elif i.contentType == "movie": i.title = "[COLOR %s][%i%%][/COLOR] %s" % (status_color[i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) else: if i.contentType == "episode": serie_name = "%s [%s]" % (i.contentSerieName, i.contentChannel) if serie_name == item.serie_name: i.title = "[COLOR %s][%i%%][/COLOR] %s" % (status_color[i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) for i in itemlist: if i.title in series: if any(series[i.title]["downloadStatus"]) == 3: downloadStatus = 3 elif all(series[i.title]["downloadStatus"]) == 2: downloadStatus = 2 else: downloadStatus = 1 downloadProgress = sum(series[i.title]["downloadProgress"]) / len(series[i.title]["downloadProgress"]) i.title = "[COLOR %s][%i%%][/COLOR] %s [%s]" % (status_color[downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel) i.downloadStatus = downloadStatus estados = [i.downloadStatus for i in itemlist] # Si hay alguno completado if 2 in estados: itemlist.insert(0, Item(channel=item.channel, action="clean_ready", title="Eliminar descargas completadas", url=config.get_setting("downloadlistpath"), serie_name = item.serie_name)) # Si hay alguno con error if 3 in estados: itemlist.insert(0, Item(channel=item.channel, action="restart_error", title="Reiniciar descargas con error", url=config.get_setting("downloadlistpath"), serie_name = item.serie_name)) # Si hay alguno pendiente if 1 in estados or 0 in estados: itemlist.insert(0, Item(channel=item.channel, action="download_all", title="Descargar todo", url=config.get_setting("downloadlistpath"), serie_name = item.serie_name)) if len(itemlist): itemlist.insert(0, Item(channel=item.channel, action="clean_all", title="Eliminar todo", url=config.get_setting("downloadlistpath"), serie_name = item.serie_name)) return itemlist
def get_environment(): """ Devuelve las variables de entorno del OS, de Kodi y de Alfa más habituales, necesarias para el diagnóstico de fallos """ try: import base64 import ast environment = config.get_platform(full_version=True) environment['num_version'] = str(environment['num_version']) environment['python_version'] = str(platform.python_version()) environment['os_release'] = str(platform.release()) if xbmc.getCondVisibility("system.platform.Windows"): try: if platform._syscmd_ver()[2]: environment['os_release'] = str(platform._syscmd_ver()[2]) except: pass environment['prod_model'] = '' if xbmc.getCondVisibility("system.platform.Android"): environment['os_name'] = 'Android' try: for label_a in subprocess.check_output('getprop').split('\n'): if 'build.version.release' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, ':\s*\[(.*?)\]$')) if 'product.model' in label_a: environment['prod_model'] = str( scrapertools.find_single_match( label_a, ':\s*\[(.*?)\]$')) except: try: for label_a in filetools.read(os.environ['ANDROID_ROOT'] + '/build.prop').split(): if 'build.version.release' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, '=(.*?)$')) if 'product.model' in label_a: environment['prod_model'] = str( scrapertools.find_single_match( label_a, '=(.*?)$')) except: pass elif xbmc.getCondVisibility("system.platform.Linux.RaspberryPi"): environment['os_name'] = 'RaspberryPi' else: environment['os_name'] = str(platform.system()) environment['machine'] = str(platform.machine()) environment['architecture'] = str(sys.maxsize > 2**32 and "64-bit" or "32-bit") environment['language'] = str(xbmc.getInfoLabel('System.Language')) environment['cpu_usage'] = str(xbmc.getInfoLabel('System.CpuUsage')) environment['mem_total'] = str( xbmc.getInfoLabel('System.Memory(total)')).replace('MB', '').replace( 'KB', '') environment['mem_free'] = str( xbmc.getInfoLabel('System.Memory(free)')).replace('MB', '').replace( 'KB', '') if not environment['mem_total'] or not environment['mem_free']: try: if environment['os_name'].lower() == 'windows': kernel32 = ctypes.windll.kernel32 c_ulong = ctypes.c_ulong c_ulonglong = ctypes.c_ulonglong class MEMORYSTATUS(ctypes.Structure): _fields_ = [('dwLength', c_ulong), ('dwMemoryLoad', c_ulong), ('dwTotalPhys', c_ulonglong), ('dwAvailPhys', c_ulonglong), ('dwTotalPageFile', c_ulonglong), ('dwAvailPageFile', c_ulonglong), ('dwTotalVirtual', c_ulonglong), ('dwAvailVirtual', c_ulonglong), ('availExtendedVirtual', c_ulonglong)] memoryStatus = MEMORYSTATUS() memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS) kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus)) environment['mem_total'] = str( old_div(int(memoryStatus.dwTotalPhys), (1024**2))) environment['mem_free'] = str( old_div(int(memoryStatus.dwAvailPhys), (1024**2))) else: with open('/proc/meminfo') as f: meminfo = f.read() environment['mem_total'] = str( old_div( int( re.search(r'MemTotal:\s+(\d+)', meminfo).groups()[0]), 1024)) environment['mem_free'] = str( old_div( int( re.search(r'MemAvailable:\s+(\d+)', meminfo).groups()[0]), 1024)) except: environment['mem_total'] = '' environment['mem_free'] = '' try: environment['kodi_buffer'] = '20' environment['kodi_bmode'] = '0' environment['kodi_rfactor'] = '4.0' if filetools.exists( filetools.join(xbmc.translatePath("special://userdata"), "advancedsettings.xml")): advancedsettings = filetools.read( filetools.join(xbmc.translatePath("special://userdata"), "advancedsettings.xml")).split('\n') for label_a in advancedsettings: if 'memorysize' in label_a: environment['kodi_buffer'] = str( old_div( int( scrapertools.find_single_match( label_a, '>(\d+)<\/')), 1024**2)) if 'buffermode' in label_a: environment['kodi_bmode'] = str( scrapertools.find_single_match( label_a, '>(\d+)<\/')) if 'readfactor' in label_a: environment['kodi_rfactor'] = str( scrapertools.find_single_match( label_a, '>(.*?)<\/')) except: pass environment['userdata_path'] = str( xbmc.translatePath(config.get_data_path())) try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(environment['userdata_path']), None, None, ctypes.pointer(free_bytes)) environment['userdata_free'] = str( round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['userdata_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['userdata_free'] = '?' try: environment['videolab_series'] = '?' environment['videolab_episodios'] = '?' environment['videolab_pelis'] = '?' environment['videolab_path'] = str( xbmc.translatePath(config.get_videolibrary_path())) if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))))) counter = 0 for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): for file in files: if file.endswith('.strm'): counter += 1 environment['videolab_episodios'] = str(counter) if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))): environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))))) except: pass try: video_updates = [ 'No', 'Inicio', 'Una vez', 'Inicio+Una vez', 'Dos veces al día' ] environment['videolab_update'] = str( video_updates[config.get_setting("update", "videolibrary")]) except: environment['videolab_update'] = '?' try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(environment['videolab_path']), None, None, ctypes.pointer(free_bytes)) environment['videolab_free'] = str( round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['videolab_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['videolab_free'] = '?' environment['torrent_list'] = [] environment['torrentcli_option'] = '' environment['torrent_error'] = '' environment['torrentcli_rar'] = config.get_setting("mct_rar_unpack", server="torrent", default=True) environment['torrentcli_backgr'] = config.get_setting( "mct_background_download", server="torrent", default=True) environment['torrentcli_lib_path'] = config.get_setting( "libtorrent_path", server="torrent", default="") if environment['torrentcli_lib_path']: lib_path = 'Activo' else: lib_path = 'Inactivo' environment['torrentcli_unrar'] = config.get_setting("unrar_path", server="torrent", default="") if environment['torrentcli_unrar']: if xbmc.getCondVisibility("system.platform.Android"): unrar = 'Android' else: unrar, bin = filetools.split(environment['torrentcli_unrar']) unrar = unrar.replace('\\', '/') if not unrar.endswith('/'): unrar = unrar + '/' unrar = scrapertools.find_single_match( unrar, '\/([^\/]+)\/$').capitalize() else: unrar = 'Inactivo' torrent_id = config.get_setting("torrent_client", server="torrent", default=0) environment['torrentcli_option'] = str(torrent_id) torrent_options = platformtools.torrent_client_installed() if lib_path == 'Activo': torrent_options = ['MCT'] + torrent_options torrent_options = ['BT'] + torrent_options environment['torrent_list'].append({'Torrent_opt': str(torrent_id), 'Libtorrent': lib_path, \ 'RAR_Auto': str(environment['torrentcli_rar']), \ 'RAR_backgr': str(environment['torrentcli_backgr']), \ 'UnRAR': unrar}) environment['torrent_error'] = config.get_setting("libtorrent_error", server="torrent", default="") if environment['torrent_error']: environment['torrent_list'].append( {'Libtorrent_error': environment['torrent_error']}) for torrent_option in torrent_options: cliente = dict() cliente['D_load_Path'] = '' cliente['Libre'] = '?' cliente['Plug_in'] = torrent_option.replace('Plugin externo: ', '') if cliente['Plug_in'] == 'BT': cliente['D_load_Path'] = str( config.get_setting("bt_download_path", server="torrent", default='')) if not cliente['D_load_Path']: continue cliente['D_load_Path'] = filetools.join( cliente['D_load_Path'], 'BT-torrents') cliente['Buffer'] = str( config.get_setting("bt_buffer", server="torrent", default=50)) elif cliente['Plug_in'] == 'MCT': cliente['D_load_Path'] = str( config.get_setting("mct_download_path", server="torrent", default='')) if not cliente['D_load_Path']: continue cliente['D_load_Path'] = filetools.join( cliente['D_load_Path'], 'MCT-torrent-videos') cliente['Buffer'] = str( config.get_setting("mct_buffer", server="torrent", default=50)) elif xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % cliente['Plug_in']): __settings__ = xbmcaddon.Addon(id="plugin.video.%s" % cliente['Plug_in']) cliente['Plug_in'] = cliente['Plug_in'].capitalize() if cliente['Plug_in'] == 'Torrenter': cliente['D_load_Path'] = str( xbmc.translatePath(__settings__.getSetting('storage'))) if not cliente['D_load_Path']: cliente['D_load_Path'] = str(filetools.join(xbmc.translatePath("special://home/"), \ "cache", "xbmcup", "plugin.video.torrenter", "Torrenter")) cliente['Buffer'] = str( __settings__.getSetting('pre_buffer_bytes')) else: cliente['D_load_Path'] = str( xbmc.translatePath( __settings__.getSetting('download_path'))) cliente['Buffer'] = str( __settings__.getSetting('buffer_size')) if __settings__.getSetting( 'download_storage' ) == '1' and __settings__.getSetting('memory_size'): cliente['Memoria'] = str( __settings__.getSetting('memory_size')) if cliente['D_load_Path']: try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(cliente['D_load_Path']), None, None, ctypes.pointer(free_bytes)) cliente['Libre'] = str(round(float(free_bytes.value) / \ (1024**3), 3)).replace('.', ',') else: disk_space = os.statvfs(cliente['D_load_Path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize cliente['Libre'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)).replace('.', ',') except: pass environment['torrent_list'].append(cliente) environment['proxy_active'] = '' try: proxy_channel_bloqued_str = base64.b64decode( config.get_setting('proxy_channel_bloqued')).decode('utf-8') proxy_channel_bloqued = dict() proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str) for channel_bloqued, proxy_active in list( proxy_channel_bloqued.items()): if proxy_active != 'OFF': environment['proxy_active'] += channel_bloqued + ', ' except: pass if not environment['proxy_active']: environment['proxy_active'] = 'OFF' environment['proxy_active'] = environment['proxy_active'].rstrip(', ') for root, folders, files in filetools.walk( xbmc.translatePath("special://logpath/")): for file in files: if file.lower() in ['kodi.log', 'jarvis.log', 'spmc.log', 'cemc.log', \ 'mygica.log', 'wonderbox.log', 'leiapp,log', \ 'leianmc.log', 'kodiapp.log', 'anmc.log', \ 'latin-anmc.log']: environment['log_path'] = str(filetools.join(root, file)) break else: environment['log_path'] = '' break if environment['log_path']: environment['log_size_bytes'] = str( filetools.getsize(environment['log_path'])) environment['log_size'] = str(round(float(environment['log_size_bytes']) / \ (1024*1024), 3)) else: environment['log_size_bytes'] = '' environment['log_size'] = '' environment['debug'] = str(config.get_setting('debug')) environment['addon_version'] = str(config.get_addon_version()) except: logger.error(traceback.format_exc()) environment = {} environment['log_size'] = '' environment['cpu_usage'] = '' environment['python_version'] = '' environment['log_path'] = '' environment['userdata_free'] = '' environment['mem_total'] = '' environment['machine'] = '' environment['platform'] = '' environment['videolab_path'] = '' environment['num_version'] = '' environment['os_name'] = '' environment['video_db'] = '' environment['userdata_path'] = '' environment['log_size_bytes'] = '' environment['name_version'] = '' environment['language'] = '' environment['mem_free'] = '' environment['prod_model'] = '' environment['proxy_active'] = '' environment['architecture'] = '' environment['os_release'] = '' environment['videolab_free'] = '' environment['kodi_buffer'] = '' environment['kodi_bmode'] = '' environment['kodi_rfactor'] = '' environment['videolab_series'] = '' environment['videolab_episodios'] = '' environment['videolab_pelis'] = '' environment['videolab_update'] = '' environment['debug'] = '' environment['addon_version'] = '' environment['torrent_list'] = [] environment['torrentcli_option'] = '' environment['torrentcli_rar'] = '' environment['torrentcli_lib_path'] = '' environment['torrentcli_unrar'] = '' environment['torrent_error'] = '' return environment
def mainlist(item): logger.info("pelisalacarta.channels.descargas mainlist") itemlist = [] status_color = {0: "orange", 1: "orange", 2: "green", 3: "red"} item.url = config.get_setting("downloadlistpath") series = {} for file in sorted(filetools.listdir(item.url)): file = os.path.join(item.url, file) # Saltamos los archivos que no sean .json if not file.endswith(".json"): continue i = Item().fromjson(filetools.read(file)) i.path = file i.thumbnail = i.contentThumbnail #item.serie_name significa que estamos desntro de una serie if not item.serie_name: # Series if i.contentType == "episode": serie_name = "%s [%s]" % (i.contentSerieName, i.contentChannel) if not serie_name in series: title = serie_name series = { serie_name: { "downloadProgress": [i.downloadProgress], "downloadStatus": [i.downloadStatus] } } i.title = title i.contentSeason = "" i.contntEpisodeNumber = "" i.action = "mainlist" i.serie_name = serie_name itemlist.append(i) else: series[serie_name]["downloadProgress"].append( i.downloadProgress) series[serie_name]["downloadStatus"].append( i.downloadStatus) # Peliculas elif i.contentType == "movie": i.title = "[COLOR %s][%i%%][/COLOR] %s" % (status_color[ i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) else: if i.contentType == "episode": serie_name = "%s [%s]" % (i.contentSerieName, i.contentChannel) if serie_name == item.serie_name: i.title = "[COLOR %s][%i%%][/COLOR] %s" % (status_color[ i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) for i in itemlist: if i.title in series: if any(series[i.title]["downloadStatus"]) == 3: downloadStatus = 3 elif all(series[i.title]["downloadStatus"]) == 2: downloadStatus = 2 else: downloadStatus = 1 downloadProgress = sum(series[i.title]["downloadProgress"]) / len( series[i.title]["downloadProgress"]) i.title = "[COLOR %s][%i%%][/COLOR] %s [%s]" % ( status_color[downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel) i.downloadStatus = downloadStatus estados = [i.downloadStatus for i in itemlist] # Si hay alguno completado if 2 in estados: itemlist.insert( 0, Item(channel=item.channel, action="clean_ready", title="Eliminar descargas completadas", url=config.get_setting("downloadlistpath"), serie_name=item.serie_name)) # Si hay alguno con error if 3 in estados: itemlist.insert( 0, Item(channel=item.channel, action="restart_error", title="Reiniciar descargas con error", url=config.get_setting("downloadlistpath"), serie_name=item.serie_name)) # Si hay alguno pendiente if 1 in estados or 0 in estados: itemlist.insert( 0, Item(channel=item.channel, action="download_all", title="Descargar todo", url=config.get_setting("downloadlistpath"), serie_name=item.serie_name)) if len(itemlist): itemlist.insert( 0, Item(channel=item.channel, action="clean_all", title="Eliminar todo", url=config.get_setting("downloadlistpath"), serie_name=item.serie_name)) return itemlist
def execute_sql_kodi(sql): """ Ejecuta la consulta sql contra la base de datos de kodi @param sql: Consulta sql valida @type sql: str @return: Numero de registros modificados o devueltos por la consulta @rtype nun_records: int @return: lista con el resultado de la consulta @rtype records: list of tuples """ logger.info("pelisalacarta.platformcode.library execute_sql_kodi") file_db = "" nun_records = 0 records = None # Buscamos el nombre de la BBDD de videos segun la version de kodi code_db = {'10': 'MyVideos37.db', '11': 'MyVideos60.db', '12': 'MyVideos75.db', '13': 'MyVideos78.db', '14': 'MyVideos90.db', '15': 'MyVideos93.db', '16': 'MyVideos99.db', '17': 'MyVideos107.db'} video_db = code_db.get(xbmc.getInfoLabel("System.BuildVersion").split(".", 1)[0], '') if video_db: file_db = filetools.join(xbmc.translatePath("special://userdata/Database"), video_db) # metodo alternativo para localizar la BBDD if not file_db or not filetools.exists(file_db): file_db = "" for f in filetools.listdir(xbmc.translatePath("special://userdata/Database")): path_f = filetools.join(xbmc.translatePath("special://userdata/Database"), f) if filetools.isfile(path_f) and f.lower().startswith('myvideos') and f.lower().endswith('.db'): file_db = path_f break if file_db: logger.info("Archivo de BD: %s" % file_db) conn = None try: import sqlite3 conn = sqlite3.connect(file_db) cursor = conn.cursor() logger.info("Ejecutando sql: %s" % sql) cursor.execute(sql) conn.commit() records = cursor.fetchall() if sql.lower().startswith("select"): nun_records = len(records) if nun_records == 1 and records[0][0] is None: nun_records = 0 records = [] else: nun_records = conn.total_changes conn.close() logger.info("Consulta ejecutada. Registros: %s" % nun_records) except: logger.error("Error al ejecutar la consulta sql") if conn: conn.close() else: logger.debug("Base de datos no encontrada") return nun_records, records
def list_tvshows(item): logger.debug() itemlist = [] lista = [] root = videolibrarytools.TVSHOWS_PATH with futures.ThreadPoolExecutor() as executor: itlist = [executor.submit(get_results, filetools.join(root, folder, "tvshow.nfo"), root, 'tvshow') for folder in filetools.listdir(root)] for res in futures.as_completed(itlist): item_tvshow, value = res.result() # verify the existence of the channels if item_tvshow.library_urls and len(item_tvshow.library_urls) > 0: itemlist += [item_tvshow] lista += [{'title':item_tvshow.contentTitle,'thumbnail':item_tvshow.thumbnail,'fanart':item_tvshow.fanart, 'active': value, 'nfo':item_tvshow.nfo}] if itemlist: itemlist = sorted(itemlist, key=lambda it: it.title.lower()) itemlist += [Item(channel=item.channel, action="update_videolibrary", thumbnail=item.thumbnail, title=typo(config.get_localized_string(70269), 'bold color kod'), folder=False), Item(channel=item.channel, action="configure_update_videolibrary", thumbnail=item.thumbnail, title=typo(config.get_localized_string(60599), 'bold color kod'), lista=lista, folder=False)] return itemlist
def init(): logger.info() """ Todo el código añadido al add-on se borra con cada actualización. Esta función permite restaurarlo automáticamente con cada actualización. Esto permite al usuario tener su propio código, bajo su responsabilidad, y restaurarlo al add-on cada vez que se actualiza. El mecanismo funciona copiando el contenido de la carpeta-arbol "./userdata/addon_data/plugin.video.alfa/custom_code/..." sobre las carpetas de código del add-on. No verifica el contenido, solo vuelca(reemplaza) el contenido de "custom_code". El usuario almacenará en las subcarpetas de "custom_code" su código actualizado y listo para ser copiado en cualquier momento. Si no se desea que copie algo, simplemente se borra de "custom_code" y ya no se copiará en la próxima actualización. Los pasos que sigue esta función, son los siguientes: 1.- La función se llama desde videolibrary_service.py, desde la función inicial: # Copia Custom code a las carpetas de Alfa desde la zona de Userdata from platformcode import custom_code custom_code.init() 2.- En el inicio de Kodi, comprueba si existe la carpeta "custom_code" en "./userdata/addon_data/plugin.video.alfa/". Si no existe, la crea y sale sin más, dando al ususario la posibilidad de copiar sobre esa estructura su código, y que la función la vuelque sobre el add-on en el próximo inicio de Kodi. 3.- En el siguiente inicio de Kodi, comprueba si existe el custom_code.json en la carpeta root del add-on. Si no existe, lo crea con el número de versión del add-on vacío, para permitir que se copien los archivos en esta pasada. 4.- Verifica que el número de versión del add-on es diferente de el de custom_code.json. Si es la misma versión, se sale porque ya se realizo la copia anteriormente. Si la versión es distinta, se realiza el volcado de todos los archivos de la carpeta-árbol "custom_code" sobre el add-on. Si la carpeta de destino no existe, dará un error y se cancelará la copia. Se considera que no tienen sentido nuevas carpetas. 5.- Si la copia ha terminado con éxito, se actualiza el custom_code.json con el número de versión del add-on, para que en inicios sucesivos de Kodi no se realicen las copias, hasta que el add-on cambie de versión. En el número de versión del add-on no se considera el número de fix. Tiempos: Copiando 7 archivos de prueba, el proceso ha tardado una décima de segundo. """ try: #Se realizan algunas funciones con cada nueva versión de Alfa if not filetools.exists( filetools.join(config.get_runtime_path(), 'custom_code.json')): config.set_setting( 'cf_assistant_ua', '') # Se limpia CF_UA. Mejora de rendimiento en httptools CF #Comprime la BD de cache de TMDB para evitar que crezca demasiado bd_tmdb_maintenance() if config.get_setting('tmdb_cache_expire', default=4) == 4: config.set_setting('tmdb_cache_expire', 2) #Verifica si es necsario instalar script.alfa-update-helper verify_script_alfa_update_helper() #Borra el .zip de instalación de Alfa de la carpeta Packages, por si está corrupto, y que así se pueda descargar de nuevo version = 'plugin.video.alfa-%s.zip' % config.get_addon_version( with_fix=False) filetools.remove( filetools.join('special://home', 'addons', 'packages', version), True) #Borrar contenido de carpeta de Torrents y de Subtitles filetools.rmdirtree(filetools.join(config.get_videolibrary_path(), 'temp_torrents_Alfa'), silent=True) subtitle_path = config.get_kodi_setting("subtitles.custompath") if subtitle_path and filetools.exists(subtitle_path): for file in filetools.listdir(subtitle_path): if not file.endswith('.srt'): continue file_path = filetools.join(subtitle_path, file) ret = filetools.remove(file_path, silent=True) if not ret: logger.error('ERROR on REMOVING subtitle: ' + file_path) #Verifica si Kodi tiene algún achivo de Base de Datos de Vídeo de versiones anteriores, entonces los borra verify_Kodi_video_DB() #Verifica si la Base de Datos de Vídeo tiene la fuente de CINE con useFolderNames=1 set_Kodi_video_DB_useFolderNames() #LIBTORRENT: se descarga el binario de Libtorrent cada vez que se actualiza Alfa try: threading.Thread(target=update_libtorrent).start( ) # Creamos un Thread independiente, hasta el fin de Kodi time.sleep(2) # Dejamos terminar la inicialización... except: # Si hay problemas de threading, nos vamos logger.error(traceback.format_exc()) #TORREST: Hacemos unas modificaciones a Torrest, si está instalado if xbmc.getCondVisibility('System.HasAddon("plugin.video.torrest")'): try: __settings__ = xbmcaddon.Addon(id="plugin.video.torrest") __settings__.setSetting("show_bg_progress", "false") # Usamos nuestro sistema from platformcode import updater updater.check_update_to_others(app=False) except: logger.error(traceback.format_exc()) #QUASAR: Preguntamos si se hacen modificaciones a Quasar if not filetools.exists(filetools.join(config.get_data_path(), "quasar.json")) \ and not config.get_setting('addon_quasar_update', default=False): question_update_external_addon("quasar") #QUASAR: Hacemos las modificaciones a Quasar, si está permitido, y si está instalado if config.get_setting('addon_quasar_update', default=False) or \ (filetools.exists(filetools.join(config.get_data_path(), \ "quasar.json")) and not xbmc.getCondVisibility('System.HasAddon("plugin.video.quasar")')): if not update_external_addon("quasar"): platformtools.dialog_notification( "Actualización Quasar", "Ha fallado. Consulte el log") #Existe carpeta "custom_code" ? Si no existe se crea y se sale custom_code_dir = filetools.join(config.get_data_path(), 'custom_code') if not filetools.exists(custom_code_dir): create_folder_structure(custom_code_dir) return else: #Existe "custom_code.json" ? Si no existe se crea custom_code_json_path = config.get_runtime_path() custom_code_json = filetools.join(custom_code_json_path, 'custom_code.json') if not filetools.exists(custom_code_json): create_json(custom_code_json_path) #Se verifica si la versión del .json y del add-on son iguales. Si es así se sale. Si no se copia "custom_code" al add-on verify_copy_folders(custom_code_dir, custom_code_json_path) #Si se han quedado "colgadas" descargas con archivos .RAR, se intenta identificarlos y reactivar el UnRar reactivate_unrar(init=True, mute=True) #Inicia un rastreo de vídeos decargados desde .torrent: marca los VISTOS y elimina los controles de los BORRADOS from servers import torrent try: threading.Thread(target=torrent.mark_torrent_as_watched).start( ) # Creamos un Thread independiente, hasta el fin de Kodi time.sleep(2) # Dejamos terminar la inicialización... except: # Si hay problemas de threading, nos vamos logger.error(traceback.format_exc()) except: logger.error(traceback.format_exc())
def get_all_settings_addon(caching_var=True): global alfa_caching, alfa_settings # Si los settings ya están cacheados, se usan. Si no, se cargan por el método tradicional if alfa_caching and caching_var and json.loads( window.getProperty("alfa_settings")): return json.loads(window.getProperty("alfa_settings")).copy() # Lee el archivo settings.xml y retorna un diccionario con {id: value} inpath = os.path.join(get_data_path(), "settings.xml") if not os.path.exists(inpath): # Si no existe el archivo settings.xml, llama a Kodi .setSetting para forzar la creación de un archivo con valores por defecto __settings__.setSetting('caching', 'true') verify_directories_created() if not os.path.exists(inpath): # Comprobamos si Kodi ha generado un archivo settings.xml accesible. Si no es así, se cancela el cacheo y el menú de bienvenida (Apple TV) __settings__.setSetting('show_once', 'true') try: infile = open(inpath, "rb") data = infile.read() if not PY3: data = data.encode("utf-8", "ignore") elif PY3 and isinstance(data, (bytes, bytearray)): data = "".join(chr(x) for x in data) infile.close() except: data = '' alfa_caching = False alfa_settings = {} try: window.setProperty("alfa_caching", '') window.setProperty("alfa_settings", json.dumps(alfa_settings)) import traceback from platformcode import logger logger.error(traceback.format_exc()) # Verificar si hay problemas de permisos de acceso a userdata/alfa from core.filetools import file_info, listdir, dirname logger.error("Error al leer settings.xml: %s, ### Folder-info: %s, ### File-info: %s" % \ (inpath, file_info(dirname(inpath)), listdir(dirname(inpath), file_inf=True))) except: pass ret = {} # matches = scrapertools.find_multiple_matches(data, '<setting\s*id="([^"]*)"\s*value="([^"]*)"') matches = re.compile('<setting\s*id="([^"]*)"\s*value="([^"]*)"', re.DOTALL).findall(data) if not matches: # matches = scrapertools.find_multiple_matches(data, '<setting\s*id="([^"]+)"[^>]*>([^<]*)<\/') matches = re.compile('<setting\s*id="([^"]+)"[^>]*>([^<]*)<\/', re.DOTALL).findall(data) for _id, value in matches: # ret[_id] = get_setting(_id, caching_var=False) ret[_id] = get_setting_values(_id, value, decode_var_=False) alfa_settings = ret.copy() alfa_caching = False if alfa_settings: alfa_caching = alfa_settings.get('caching', True) if alfa_caching: window.setProperty("alfa_caching", str(alfa_caching)) else: window.setProperty("alfa_caching", '') if not alfa_caching: alfa_settings = {} alfa_kodi_platform = {} alfa_channels = {} alfa_servers = {} window.setProperty("alfa_channels", json.dumps(alfa_channels)) window.setProperty("alfa_servers", json.dumps(alfa_servers)) window.setProperty("alfa_settings", json.dumps(alfa_settings)) return ret
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(library.MOVIES_PATH, item.strm_path.strip('\/')) 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(library.TVSHOWS_PATH, item.strm_path.strip('\/')) 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 (content_title in contenido.strip() 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) if 'descargas' in list_canales: json_path = list_canales['descargas'] item_json = Item().fromjson(filetools.read(json_path)) del list_canales['descargas'] # 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", "biblioteca") == True: 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 = 'descargas' 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_idiomas" in item_json: # si se viene desde la biblioteca de pelisalacarta if "library_filter_show" in item: item_json.show = item.library_filter_show.get(nom_canal, "") # Ejecutamos find_videos, del canal o común if hasattr(channel, 'findvideos'): list_servers = getattr(channel, 'findvideos')(item_json) 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 {0} occured. Arguments:\n{1!r}" message = template.format(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 = "biblioteca" server.nfo = item.nfo server.strm_path = item.strm_path 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) # return sorted(itemlist, key=lambda it: it.title.lower()) return itemlist
set_version = 0 ### Alfa if getSettingAsBool('custom_version'): log('set_version:' +str(set_version)+' '+VERSIONS[set_version]) platform['version'] = VERSIONS[set_version] else: platform['version'] = default_path sizefile_path = filetools.join(__root__, platform['system'], platform['version']) if not filetools.exists(sizefile_path): log('set_version: no sizefile at %s back to default %s' % (sizefile_path, default_path)) platform['version'] = default_path sizefile_path = filetools.join(__root__, platform['system'], platform['version']) if not filetools.exists(sizefile_path): log('set_version: no default at %s searching for any version' % sizefile_path) try: versions = sorted(filetools.listdir(filetools.join(__root__, platform['system']))) except: versions = [] versions_for = versions[:] for ver in versions_for: if ver not in VERSIONS: versions.remove(ver) continue if not filetools.isdir(filetools.join(__root__, platform['system'], ver)): versions.remove(ver) VERSIONS_for = VERSIONS[:] for ver in VERSIONS_for: if ver not in versions: VERSIONS.remove(ver)
def mainlist(item): logger.info() itemlist = [] item.text_color = color1 logueado, error_message = login("kbagi.com") if not logueado: itemlist.append( item.clone(title=error_message, action="configuracion", folder=False)) else: item.extra = "http://kbagi.com" itemlist.append(item.clone(title="kbagi", action="", text_color=color2)) itemlist.append( item.clone(title=" Búsqueda", action="search", url="http://kbagi.com/action/SearchFiles")) itemlist.append( item.clone( title=" Colecciones", action="colecciones", url= "http://kbagi.com/action/home/MoreNewestCollections?pageNumber=1" )) itemlist.append( item.clone(title=" Búsqueda personalizada", action="filtro", url="http://kbagi.com/action/SearchFiles")) itemlist.append(item.clone(title=" Mi cuenta", action="cuenta")) item.extra = "http://diskokosmiko.mx/" itemlist.append( item.clone(title="DiskoKosmiko", action="", text_color=color2)) itemlist.append( item.clone(title=" Búsqueda", action="search", url="http://diskokosmiko.mx/action/SearchFiles")) itemlist.append( item.clone( title=" Colecciones", action="colecciones", url= "http://diskokosmiko.mx/action/home/MoreNewestCollections?pageNumber=1" )) itemlist.append( item.clone(title=" Búsqueda personalizada", action="filtro", url="http://diskokosmiko.mx/action/SearchFiles")) itemlist.append(item.clone(title=" Mi cuenta", action="cuenta")) itemlist.append(item.clone(action="", title="")) folder_thumb = filetools.join(config.get_data_path(), 'thumbs_kbagi') files = filetools.listdir(folder_thumb) if files: itemlist.append( item.clone(title="Eliminar caché de imágenes (%s)" % len(files), action="delete_cache", text_color="red")) itemlist.append( item.clone(title="Configuración del canal", action="configuracion", text_color="gold")) return itemlist
def extract_files(rar_file, save_path_videos, password, dp, item=None, torr_client=None): logger.info() import sys #reload(sys) #sys.setdefaultencoding('utf-8') sys.path.insert(0, config.get_setting("unrar_path", server="torrent", default="")\ .replace('/unrar', '').replace('\\unrar,exe', '')) import rarfile # Verificamos si hay path para UnRAR rarfile.UNRAR_TOOL = config.get_setting("unrar_path", server="torrent", default="") if not rarfile.UNRAR_TOOL: if xbmc.getCondVisibility("system.platform.Android"): rarfile.UNRAR_TOOL = xbmc.executebuiltin("StartAndroidActivity(com.rarlab.rar)") return rar_file, False, '', '' log("##### unrar_path: %s" % rarfile.UNRAR_TOOL) rarfile.DEFAULT_CHARSET = 'utf-8' # Preparamos un path alternativo más corto para no sobrepasar la longitud máxima video_path = '' if item: if item.contentType == 'movie': video_path = '%s-%s' % (item.contentTitle, item.infoLabels['tmdb_id']) else: video_path = '%s-%sx%s-%s' % (item.contentSerieName, item.contentSeason, \ item.contentEpisodeNumber, item.infoLabels['tmdb_id']) # Renombramos el path dejado en la descarga a uno más corto rename_status = False org_rar_file = rar_file org_save_path_videos = save_path_videos if video_path and '/' in rar_file: log("##### rar_file: %s" % rar_file) rename_status, rar_file = rename_rar_dir(org_rar_file, org_save_path_videos, video_path, torr_client) # Calculamos el path para del RAR if "/" in rar_file: folders = rar_file.split("/") erase_file_path = filetools.join(save_path_videos, folders[0]) file_path = save_path_videos for f in folders: file_path = filetools.join(file_path, f) else: file_path = save_path_videos erase_file_path = save_path_videos # Calculamos el path para la extracción if "/" in rar_file: folders = rar_file.split("/") for f in folders: if not '.rar' in f: save_path_videos = filetools.join(save_path_videos, f) save_path_videos = filetools.join(save_path_videos, 'Extracted') if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos) log("##### save_path_videos: %s" % save_path_videos) # Permite hasta 5 pasadas de extracción de .RARs anidados platformtools.dialog_notification("Empezando extracción...", rar_file, time=5000) for x in range(5): try: archive = rarfile.RarFile(file_path.decode("utf8")) except: log("##### ERROR en Archivo rar: %s" % rar_file) log("##### ERROR en Carpeta del rar: %s" % file_path) log(traceback.format_exc()) platformtools.dialog_notification("Error al abrir el RAR", "Comprueba el log para más detalles") return rar_file, False, '', '' # Analizamos si es necesaria una contraseña, que debería estar en item.password if archive.needs_password(): if not password: pass_path = filetools.split(file_path)[0] password = last_password_search(pass_path) if not password : password = platformtools.dialog_input(heading="Introduce la contraseña (Mira en %s)" % pass_path) if not password: return rar_file, False, '', '' archive.setpassword(password) log("##### Password rar: %s" % password) # Miramos el contenido del RAR a extraer files = archive.infolist() info = [] for idx, i in enumerate(files): if i.file_size == 0: files.pop(idx) continue filename = i.filename if "/" in filename: filename = filename.rsplit("/", 1)[1] info.append("%s - %.2f MB" % (filename, i.file_size / 1048576.0)) if info: info.append("Extraer todo sin reproducir") else: platformtools.dialog_notification("El RAR está vacío", "O no contiene archivos válidos") return rar_file, False, '', erase_file_path # Seleccionamos extraer TODOS los archivos del RAR #selection = xbmcgui.Dialog().select("Selecciona el fichero a extraer y reproducir", info) selection = len(info) - 1 if selection < 0: return rar_file, False, '', erase_file_path else: try: log("##### RAR Extract INI #####") if selection == len(info) - 1: log("##### rar_file 1: %s" % file_path) log("##### save_path_videos 1: %s" % save_path_videos) dp.update(99, "Extrayendo archivos...", "Espera unos minutos....") archive.extractall(save_path_videos) else: log("##### rar_file 2: %s" % file_path) log("##### save_path_videos 2: %s" % save_path_videos) dp.update(99, "Espera unos minutos....", "Extrayendo archivo... %s" % info[selection]) archive.extract(files[selection], save_path_videos) log("##### RAR Extract END #####") except (rarfile.RarWrongPassword, rarfile.RarCRCError): platformtools.dialog_notification("Error al extraer", "Contraseña incorrecta") log(traceback.format_exc(1)) return rar_file, False, '', erase_file_path except rarfile.BadRarFile: platformtools.dialog_notification("Error al extraer", "Archivo rar con errores") log(traceback.format_exc(1)) return rar_file, False, '', erase_file_path except: platformtools.dialog_notification("Error al extraer", "Comprueba el log para más detalles") log(traceback.format_exc(1)) return rar_file, False, '', erase_file_path extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.mpe', '.mp4', '.ogg', '.wmv'] # Localizamos el path donde se ha dejado la extracción folder = True file_result = filetools.listdir(save_path_videos) while folder: for file_r in file_result: if filetools.isdir(filetools.join(save_path_videos, file_r)): file_result_alt = filetools.listdir(filetools.join(save_path_videos, file_r)) if file_result_alt: file_result = file_result_alt save_path_videos = filetools.join(save_path_videos, file_r) else: folder = False break else: folder = False # Si hay RARs anidados, ajustamos los paths para la siguiente pasada if '.rar' in str(file_result): for file_r in file_result: if '.rar' in file_r: rar_file = file_r file_path = str(filetools.join(save_path_videos, rar_file)) save_path_videos = filetools.join(save_path_videos, 'Extracted') if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos) platformtools.dialog_notification("Siguiente extracción...", rar_file, time=5000) # Si ya se ha extraido todo, preparamos el retorno else: video_list = [] for file_r in file_result: if os.path.splitext(file_r)[1] in extensions_list: video_list += [file_r] if len(video_list) == 0: platformtools.dialog_notification("El rar está vacío", "O no contiene archivos válidos") return rar_file, False, '', erase_file_path else: log("##### Archivo extraído: %s" % video_list[0]) platformtools.dialog_notification("Archivo extraído...", video_list[0], time=10000) return str(video_list[0]), True, save_path_videos, erase_file_path
def update_libtorrent(): logger.info() if not config.get_setting("mct_buffer", server="torrent", default=""): default = config.get_setting("torrent_client", server="torrent", default=0) config.set_setting("torrent_client", default, server="torrent") config.set_setting("mct_buffer", "50", server="torrent") if config.get_setting("mct_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("mct_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_background_download", True, server="torrent") config.set_setting("mct_rar_unpack", True, server="torrent") config.set_setting("bt_buffer", "50", server="torrent") if config.get_setting("bt_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("bt_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_download_limit", "", server="torrent") config.set_setting("magnet2torrent", False, server="torrent") if not filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) or not \ config.get_setting("unrar_path", server="torrent", default=""): path = filetools.join(config.get_runtime_path(), 'lib', 'rarfiles') creationflags = '' sufix = '' unrar = '' for device in filetools.listdir(path): if xbmc.getCondVisibility( "system.platform.android") and 'android' not in device: continue if xbmc.getCondVisibility( "system.platform.windows") and 'windows' not in device: continue if not xbmc.getCondVisibility("system.platform.windows") and not xbmc.getCondVisibility("system.platform.android") \ and ('android' in device or 'windows' in device): continue if 'windows' in device: creationflags = 0x08000000 sufix = '.exe' else: creationflags = '' sufix = '' unrar = filetools.join(path, device, 'unrar%s') % sufix if not filetools.exists(unrar): unrar = '' if unrar: if not xbmc.getCondVisibility("system.platform.windows"): try: if xbmc.getCondVisibility("system.platform.android"): # Para Android copiamos el binario a la partición del sistema unrar_org = unrar unrar = filetools.join( xbmc.translatePath('special://xbmc/'), 'files').replace('/cache/apk/assets', '') if not filetools.exists(unrar): filetools.mkdir(unrar) unrar = filetools.join(unrar, 'unrar') filetools.copy(unrar_org, unrar, silent=True) command = ['chmod', '777', '%s' % unrar] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() command = ['ls', '-l', unrar] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() xbmc.log('######## UnRAR file: %s' % str(output_cmd), xbmc.LOGNOTICE) except: xbmc.log( '######## UnRAR ERROR in path: %s' % str(unrar), xbmc.LOGNOTICE) logger.error(traceback.format_exc(1)) try: if xbmc.getCondVisibility("system.platform.windows"): p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags) else: p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() if p.returncode != 0 or error_cmd: xbmc.log('######## UnRAR returncode in module %s: %s, %s in %s' % \ (device, str(p.returncode), str(error_cmd), unrar), xbmc.LOGNOTICE) unrar = '' else: xbmc.log( '######## UnRAR OK in %s: %s' % (device, unrar), xbmc.LOGNOTICE) break except: xbmc.log( '######## UnRAR ERROR in module %s: %s' % (device, unrar), xbmc.LOGNOTICE) logger.error(traceback.format_exc(1)) unrar = '' if unrar: config.set_setting("unrar_path", unrar, server="torrent") if filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) and \ config.get_setting("libtorrent_path", server="torrent", default="") : return try: from lib.python_libtorrent.python_libtorrent import get_libtorrent except Exception as e: logger.error(traceback.format_exc(1)) if not PY3: e = unicode(str(e), "utf8", errors="replace").encode("utf8") config.set_setting("libtorrent_path", "", server="torrent") if not config.get_setting( "libtorrent_error", server="torrent", default=''): config.set_setting("libtorrent_error", str(e), server="torrent") return
def move_videolibrary(current_path, new_path, current_movies_folder, new_movies_folder, current_tvshows_folder, new_tvshows_folder): logger.debug() backup_current_path = current_path backup_new_path = new_path logger.info('current_path: ' + current_path) logger.info('new_path: ' + new_path) logger.info('current_movies_folder: ' + current_movies_folder) logger.info('new_movies_folder: ' + new_movies_folder) logger.info('current_tvshows_folder: ' + current_tvshows_folder) logger.info('new_tvshows_folder: ' + new_tvshows_folder) notify = False progress = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80011)) current_path = u'' + xbmc.translatePath(current_path) new_path = u'' + xbmc.translatePath(new_path) current_movies_path = u'' + filetools.join(current_path, current_movies_folder) new_movies_path = u'' + filetools.join(new_path, new_movies_folder) current_tvshows_path = u'' + filetools.join(current_path, current_tvshows_folder) new_tvshows_path = u'' + filetools.join(new_path, new_tvshows_folder) logger.info('current_movies_path: ' + current_movies_path) logger.info('new_movies_path: ' + new_movies_path) logger.info('current_tvshows_path: ' + current_tvshows_path) logger.info('new_tvshows_path: ' + new_tvshows_path) from platformcode import xbmc_videolibrary movies_path, tvshows_path = xbmc_videolibrary.check_sources(new_movies_path, new_tvshows_path) logger.info('check_sources: ' + str(movies_path) + ', ' + str(tvshows_path)) if movies_path or tvshows_path: if not movies_path: filetools.rmdir(new_movies_path) if not tvshows_path: filetools.rmdir(new_tvshows_path) config.set_setting("videolibrarypath", backup_current_path) config.set_setting("folder_movies", current_movies_folder) config.set_setting("folder_tvshows", current_tvshows_folder) xbmc_videolibrary.update_sources(backup_current_path, backup_new_path) progress.update(100) xbmc.sleep(1000) progress.close() platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(80028)) return config.verify_directories_created() progress.update(10, config.get_localized_string(20000) + '\n' + config.get_localized_string(80012)) if current_movies_path != new_movies_path: if filetools.listdir(current_movies_path): dir_util.copy_tree(current_movies_path, new_movies_path) notify = True filetools.rmdirtree(current_movies_path) progress.update(40) if current_tvshows_path != new_tvshows_path: if filetools.listdir(current_tvshows_path): dir_util.copy_tree(current_tvshows_path, new_tvshows_path) notify = True filetools.rmdirtree(current_tvshows_path) progress.update(70) if current_path != new_path and not filetools.listdir(current_path) and not "plugin.video.kod\\videolibrary" in current_path: filetools.rmdirtree(current_path) xbmc_videolibrary.update_sources(backup_new_path, backup_current_path) if config.is_xbmc() and config.get_setting("videolibrary_kodi"): xbmc_videolibrary.update_db(backup_current_path, backup_new_path, current_movies_folder, new_movies_folder, current_tvshows_folder, new_tvshows_folder, progress) else: progress.update(100) xbmc.sleep(1000) progress.close() if notify: platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80014), time=5000, sound=False)
def mainlist(item): logger.info("pelisalacarta.channels.descargas mainlist") itemlist = [] #Lista de archivos for file in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): #Saltamos todos los que no sean JSON if not file.endswith(".json"): continue #cargamos el item file = os.path.join(DOWNLOAD_LIST_PATH, file) i = Item(path = file).fromjson(filetools.read(file)) i.thumbnail = i.contentThumbnail #Listado principal if not item.contentType == "tvshow": # Series if i.contentType == "episode": #Comprobamos que la serie no este ya en el itemlist if not filter(lambda x: x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel, itemlist): title = TITLE_TVSHOW % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel) itemlist.append(Item(title = title, channel= "descargas", action= "mainlist", contentType = "tvshow", contentSerieName = i.contentSerieName, contentChannel = i.contentChannel, downloadStatus = i.downloadStatus, downloadProgress = [i.downloadProgress], fanart = i.fanart, thumbnail = i.thumbnail)) else: s = filter(lambda x: x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel, itemlist)[0] s.downloadProgress.append(i.downloadProgress) downloadProgress = sum(s.downloadProgress) / len(s.downloadProgress) if not s.downloadStatus in [STATUS_CODES.error, STATUS_CODES.canceled] and not i.downloadStatus in [STATUS_CODES.completed, STATUS_CODES.stoped]: s.downloadStatus = i.downloadStatus s.title = TITLE_TVSHOW % (STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel) # Peliculas elif i.contentType == "movie" or i.contentType == "video": i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) #Listado dentro de una serie else: if i.contentType == "episode" and i.contentSerieName == item.contentSerieName and i.contentChannel == item.contentChannel: i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber,i.contentTitle)) itemlist.append(i) estados = [i.downloadStatus for i in itemlist] # Si hay alguno completado if 2 in estados: itemlist.insert(0, Item(channel=item.channel, action="clean_ready", title="Eliminar descargas completadas", contentType = item.contentType, contentChannel=item.contentChannel, contentSerieName = item.contentSerieName)) # Si hay alguno con error if 3 in estados: itemlist.insert(0, Item(channel=item.channel, action="restart_error", title="Reiniciar descargas con error", contentType = item.contentType, contentChannel=item.contentChannel, contentSerieName = item.contentSerieName)) # Si hay alguno pendiente if 1 in estados or 0 in estados: itemlist.insert(0, Item(channel=item.channel, action="download_all", title="Descargar todo", contentType = item.contentType, contentChannel=item.contentChannel, contentSerieName = item.contentSerieName)) if len(itemlist): itemlist.insert(0, Item(channel=item.channel, action="clean_all", title="Eliminar todo", contentType = item.contentType, contentChannel=item.contentChannel, contentSerieName = item.contentSerieName)) return itemlist
def update_libtorrent(): logger.info() if not config.get_setting("mct_buffer", server="torrent", default=""): default = config.get_setting("torrent_client", server="torrent", default=0) config.set_setting("torrent_client", default, server="torrent") config.set_setting("mct_buffer", "50", server="torrent") config.set_setting("mct_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_background_download", True, server="torrent") config.set_setting("mct_rar_unpack", True, server="torrent") config.set_setting("bt_buffer", "50", server="torrent") config.set_setting("bt_download_path", config.get_setting("downloadpath"), server="torrent") if not filetools.exists(os.path.join(config.get_runtime_path(), "custom_code.json")) or not \ config.get_setting("unrar_path", server="torrent", default=""): path = os.path.join(config.get_runtime_path(), 'lib', 'rarfiles') creationflags = '' sufix = '' unrar = '' for device in filetools.listdir(path): if xbmc.getCondVisibility("system.platform.android") and 'android' not in device: continue if xbmc.getCondVisibility("system.platform.windows") and 'windows' not in device: continue if 'windows' in device: creationflags = 0x08000000 sufix = '.exe' unrar = os.path.join(path, device, 'unrar%s') % sufix if not filetools.exists(unrar): unrar = '' if unrar: if not xbmc.getCondVisibility("system.platform.windows"): try: if xbmc.getCondVisibility("system.platform.android"): # Para Android copiamos el binario a la partición del sistema unrar_org = unrar unrar = os.path.join(xbmc.translatePath('special://xbmc'), 'unrar') import xbmcvfs xbmcvfs.copy(unrar_org, unrar) command = ['chmod', '777', '%s' % unrar] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() except: pass try: p = subprocess.Popen(unrar, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags) output_cmd, error_cmd = p.communicate() if p.returncode != 0: unrar = '' xbmc.log('######## UnRAR returncode for %s: %s' % (device, str(p.returncode)), xbmc.LOGNOTICE) else: xbmc.log('######## UnRAR OK en %s: %s' % (device, unrar), xbmc.LOGNOTICE) break except: unrar = '' xbmc.log('######## UnRAR error en %s' % device, xbmc.LOGNOTICE) if unrar: config.set_setting("unrar_path", unrar, server="torrent") if filetools.exists(os.path.join(config.get_runtime_path(), "custom_code.json")) and \ config.get_setting("libtorrent_path", server="torrent", default="") : return if xbmc.getCondVisibility("system.platform.android"): LIBTORRENT_PATH = config.get_setting("libtorrent_path", server="torrent", default='') LIBTORRENT_MSG = config.get_setting("libtorrent_msg", server="torrent", default='') if '/data/app/' not in LIBTORRENT_PATH and not LIBTORRENT_MSG: platformtools.dialog_notification('ALFA: Instalando Cliente Torrent interno', \ 'Puede solicitarle permisos de Superusuario', time=15000) xbmc.log('### ALFA: Notificación enviada: Instalando Cliente Torrent interno', \ xbmc.LOGNOTICE) config.set_setting("libtorrent_msg", 'OK', server="torrent") try: from lib.python_libtorrent.python_libtorrent import get_libtorrent except Exception, e: logger.error(traceback.format_exc(1)) e = unicode(str(e), "utf8", errors="replace").encode("utf8") config.set_setting("libtorrent_path", "", server="torrent") if not config.get_setting("libtorrent_error", server="torrent", default=''): config.set_setting("libtorrent_error", str(e), server="torrent")