def move_to_libray(item): download_path = filetools.join(config.get_setting("downloadpath"), item.downloadFilename) library_path = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename)) final_path = download_path if config.get_setting("library_add", "descargas") == True and config.get_setting("library_move", "descargas") == 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)) if config.get_setting("library_add", "descargas") == True: if filetools.isfile(final_path): 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=final_path) 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=final_path) tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]}) library.save_library_tvshow(tvshow, [library_item])
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 marshal_check(): try: marshal_modules = ['lib/alfaresolver_py3', 'core/proxytools_py3'] for module in marshal_modules: path = filetools.join(ADDON_PATH, filetools.dirname(module)) path_list = filetools.listdir(path) library = filetools.dirname(module).rstrip('/') module_name = filetools.basename(module) for alt_module in path_list: if module_name not in alt_module: continue if alt_module == module_name + '.py': continue try: alt_module_path = '%s.%s' % (library, alt_module.rstrip('.py')) spec = __import__(alt_module_path, None, None, [alt_module_path]) if not spec: raise except Exception as e: logger.info('marshal_check ERROR in %s: %s' % (alt_module, str(e)), force=True) continue filetools.copy(filetools.join(path, alt_module), filetools.join(path, module_name + '.py'), silent=True) logger.info('marshal_check FOUND: %s' % alt_module, force=True) break else: logger.info('marshal_check NOT FOUND: %s.py' % module_name, force=True) except: logger.error(traceback.format_exc(1))
def get_kodi_setting(name, total=False): """ Retorna el valor de configuracion del parametro solicitado. Devuelve el valor del parametro 'name' en la configuracion global de Kodi @param default: valor devuelto en caso de que no exista el parametro name @type default: any @return: El valor del parametro 'name' @rtype: any """ # Global Kodi setting #from core import scrapertools try: inpath = os.path.join(translatePath('special://masterprofile/'), "guisettings.xml") 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 = '' try: import traceback from platformcode import logger logger.error(traceback.format_exc()) # Verificar si hay problemas de permisos de acceso a userdata from core.filetools import file_info, listdir, dirname logger.error("Error al leer guisettings.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="([^"]+)"[^>]*>([^<]*)<\/setting>') matches = re.compile('<setting\s*id="([^"]+)"[^>]*>([^<]*)<\/setting>', re.DOTALL).findall(data) for _id, value in matches: # hack para devolver el tipo correspondiente ret[_id] = get_setting_values(_id, value, decode_var_=False) if _id == name and not total: return ret[_id] if not total: return None else: return ret
def move_to_libray(item): if not config.get_setting("library_move", "descargas") == True: return try: from core 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="Scaricato: %s" % item.downloadFilename, channel="descargas", action="findvideos", infoLabels=item.infoLabels, url=item.downloadFilename) library.save_library_movie(library_item) elif item.contentType == "episode" and item.infoLabels["tmdb_id"]: library_item = Item(title="Scaricato: %s" % item.downloadFilename, channel="descargas", action="findvideos", infoLabels=item.infoLabels, url=item.downloadFilename) tvshow = Item(channel="descargas", contentType="tvshow", infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]}) library.save_library_tvshow(tvshow, [library_item])
def overwrite_tools(item): import library_service from core import library seleccion = platformtools.dialog_yesno("Sobrescribir toda la biblioteca", "Esto puede llevar algun tiempo.", "¿Desea continuar?") if seleccion == 1: heading = 'Sobrescribiendo biblioteca....' p_dialog = platformtools.dialog_progress_bg('mitvspain', heading) p_dialog.update(0, '') import glob show_list = glob.glob(filetools.join(library.TVSHOWS_PATH, u'/*/tvshow.nfo')) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = library.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) if not serie.active: # si la serie no esta activa descartar continue # Eliminamos la carpeta con la serie ... filetools.rmdirtree(path) # ... y la volvemos a añadir library_service.update(path, p_dialog, i, t, serie, 3) p_dialog.close()
def overwrite_tools(item): import library_service from core import library seleccion = platformtools.dialog_yesno("Sovrascrivere la libreria?", "Richiede un certo tempo.", "Continuare?") if seleccion == 1: heading = 'Sovrascrivo la libreria....' p_dialog = platformtools.dialog_progress_bg('Stefano', heading) p_dialog.update(0, '') import glob show_list = glob.glob( filetools.join(library.TVSHOWS_PATH, u'/*/tvshow.sod')) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = library.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) if not serie.active: # si la serie no esta activa descartar continue # Eliminamos la carpeta con la serie ... filetools.rmdirtree(path) # ... y la volvemos a añadir library_service.update(path, p_dialog, i, t, serie, 3) p_dialog.close()
def list_movies(item): logger.info() itemlist = [] for f in glob.glob( filetools.join(videolibrarytools.MOVIES_PATH, u'/*/*.nfo')): nfo_path = f head_nfo, new_item = videolibrarytools.read_nfo(nfo_path) new_item.nfo = nfo_path new_item.path = filetools.dirname(f) new_item.thumbnail = new_item.contentThumbnail new_item.text_color = "blue" if not filetools.exists( filetools.join(videolibrarytools.MOVIES_PATH, new_item.strm_path)): # Si se ha eliminado el strm desde la bilbioteca de kodi, no mostrarlo continue # Menu contextual: Marcar como visto/no visto visto = new_item.library_playcounts.get(os.path.splitext(f)[0], 0) new_item.infoLabels["playcount"] = visto if visto > 0: texto_visto = "Marcar película como no vista" contador = 0 else: texto_visto = "Marcar película como vista" contador = 1 # Menu contextual: Eliminar serie/canal num_canales = len(new_item.library_urls) if "downloads" in new_item.library_urls: num_canales -= 1 if num_canales > 1: texto_eliminar = "Eliminar película/canal" multicanal = True else: texto_eliminar = "Eliminar esta película" multicanal = False new_item.context = [{ "title": texto_visto, "action": "mark_content_as_watched", "channel": "videolibrary", "playcount": contador }, { "title": texto_eliminar, "action": "delete", "channel": "videolibrary", "multicanal": multicanal }] # ,{"title": "Cambiar contenido (PENDIENTE)", # "action": "", # "channel": "videolibrary"}] # logger.debug("new_item: " + new_item.tostring('\n')) itemlist.append(new_item) return sorted(itemlist, key=lambda it: it.title.lower())
def __init__(self, dest_path, platform): self.dest_path = dest_path self.platform = platform self.root=filetools.dirname(filetools.dirname(__file__)) ver1, ver2, ver3 = platform['version'].split('.') ### Alfa: resto método try: ver1 = int(ver1) ver2 = int(ver2) except: ver1 = 2 ver2 = 0 if ver1 > 1 or (ver1 == 1 and ver2 >= 2): global __libbaseurl__ __libbaseurl__ = ['https://github.com/alfa-addon/alfa-repo/raw/master/downloads/libtorrent', \ 'https://bitbucket.org/alfa_addon/alfa-repo/raw/master/downloads/libtorrent'] else: __libbaseurl__ = ["https://github.com/DiMartinoXBMC/script.module.libtorrent/raw/master/python_libtorrent"]
def download_from_url(url, item): logger.info("Intentando descargar: %s" % (url)) if url.lower().endswith(".m3u8") or url.lower().startswith("rtmp"): save_server_statistics(item.server, 0, False) return {"downloadStatus": STATUS_CODES.error} # Obtenemos la ruta de descarga y el nombre del archivo item.downloadFilename = item.downloadFilename.replace('/','-') download_path = filetools.dirname(filetools.join(DOWNLOAD_PATH, item.downloadFilename)) file_name = filetools.basename(filetools.join(DOWNLOAD_PATH, item.downloadFilename)) # Creamos la carpeta si no existe if not filetools.exists(download_path): filetools.mkdir(download_path) # Lanzamos la descarga d = Downloader(url, download_path, file_name, max_connections=1 + int(config.get_setting("max_connections", "downloads")), block_size=2 ** (17 + int(config.get_setting("block_size", "downloads"))), part_size=2 ** (20 + int(config.get_setting("part_size", "downloads"))), max_buffer=2 * int(config.get_setting("max_buffer", "downloads"))) d.start_dialog(config.get_localized_string(60332)) # Descarga detenida. Obtenemos el estado: # Se ha producido un error en la descarga if d.state == d.states.error: logger.info("Error al intentar descargar %s" % (url)) status = STATUS_CODES.error # La descarga se ha detenifdo elif d.state == d.states.stopped: logger.info("Descarga detenida") status = STATUS_CODES.canceled # La descarga ha finalizado elif d.state == d.states.completed: logger.info("Descargado correctamente") status = STATUS_CODES.completed if item.downloadSize and item.downloadSize != d.size[0]: status = STATUS_CODES.error save_server_statistics(item.server, d.speed[0], d.state != d.states.error) dir = os.path.dirname(item.downloadFilename) file = filetools.join(dir, d.filename) if status == STATUS_CODES.completed: move_to_libray(item.clone(downloadFilename=file)) return {"downloadUrl": d.download_url, "downloadStatus": status, "downloadSize": d.size[0], "downloadProgress": d.progress, "downloadCompleted": d.downloaded[0], "downloadFilename": file}
def show_channels(item): support.log() itemlist = [] # add context menu context = [{ "title": config.get_localized_string(50005), "action": "remove_channel", "channel": "community" }] # read json json = load_and_check(item) itemlist.append( Item(channel=item.channel, title=support.typo(config.get_localized_string(70676), 'bold color kod'), action='add_channel', thumbnail=get_thumb('add.png'))) for key, channel in json['channels'].items(): path = filetools.dirname(channel['path']) # relative path channel_json = load_json(channel['path']) # read channel json # retrieve information from json thumbnail = relative('thumbnail', channel_json, path) if not thumbnail: thumbnail = item.thumbnail fanart = relative('fanart', channel_json, path) plot = channel_json['plot'] if 'plot' in channel_json else '' itemlist.append( Item(channel=item.channel, title=support.typo(channel['channel_name'], 'bold'), url=channel['path'], thumbnail=thumbnail, fanart=fanart, plot=plot, action='show_menu', channel_id=key, context=context, path=path)) autoplay.show_option(item.channel, itemlist) support.channel_config(item, itemlist) return itemlist
def search_library_path(): logger.info() cine = config.get_setting('folder_movies', default='CINE') series = config.get_setting('folder_tvshows', default='SERIES') cine_win = '\\%s\\' % cine cine_res = '/%s/' % cine series_win = '\\%s\\' % series series_res = '/%s/' % series sql = 'SELECT strPath FROM path WHERE (idParentPath IS NULL AND strContent IS NOT NULL AND (' + \ 'strPath LIKE "%library' + cine_win + '" or strPath LIKE "%library' + cine_res + \ '" or strPath LIKE "%library' + series_win + '" or strPath LIKE "%library' + series_res + '"))' nun_records, records = execute_sql_kodi(sql) if nun_records >= 1: logger.debug(records) resp = filetools.join(filetools.dirname(records[0][0][:-1]), ' ').rstrip() if filetools.exists(resp): return resp return None
def overwrite_tools(item): import library_service from core import library seleccion = platformtools.dialog_yesno("Sobrescribir toda la biblioteca", "Esto puede llevar algun tiempo.", "¿Desea continuar?") if seleccion == 1: heading = 'Sobrescribiendo biblioteca....' p_dialog = platformtools.dialog_progress_bg('pelisalacarta', heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk(library.TVSHOWS_PATH): show_list.extend([filetools.join(path, f) for f in files if f == "tvshow.nfo"]) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = library.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) if not serie.active: # si la serie no esta activa descartar continue # Eliminamos la carpeta con la serie ... filetools.rmdirtree(path) # ... y la volvemos a añadir library_service.update(path, p_dialog, i, t, serie, 3) p_dialog.close()
def check_for_update(overwrite=True): logger.debug("Update Series...") p_dialog = None serie_actualizada = False update_when_finished = False hoy = datetime.date.today() estado_verify_playcount_series = False local_ended = True try: if config.get_setting("update", "videolibrary") != 0 or overwrite: config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "videolibrary") heading = config.get_localized_string(60389) p_dialog = platformtools.dialog_progress_bg( config.get_localized_string(20000), heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk( videolibrarytools.TVSHOWS_PATH): show_list.extend([ filetools.join(path, f) for f in files if f == "tvshow.nfo" ]) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = videolibrarytools.read_nfo(tvshow_file) if serie.local_episodes_path: local_ended = True if serie.infoLabels[ 'number_of_episodes'] == len( serie.local_episodes_list) else False if serie.infoLabels['status'].lower( ) == 'ended' and local_ended: serie.active = 0 filetools.write(tvshow_file, head_nfo + serie.tojson()) path = filetools.dirname(tvshow_file) logger.debug("serie=" + serie.contentSerieName) p_dialog.update(int(math.ceil((i + 1) * t)), heading, serie.contentSerieName) # Check the status of the series.library_playcounts of the Series in case it is incomplete try: estado = False # If we have not done the verification or do not have a playcount, we enter estado = config.get_setting("verify_playcount", "videolibrary") if not estado or estado == False or not serie.library_playcounts: # If it hasn't happened before, we do it now serie, estado = videolibrary.verify_playcount_series( serie, path ) # Also happens if a PlayCount is missing completely except: logger.error(traceback.format_exc()) else: if estado: # If the update was successful ... estado_verify_playcount_series = True # ... is checked to change the Video Library option interval = int(serie.active) # Could be the bool type if not serie.active: # if the series is not active discard if not overwrite: # Synchronize the episodes seen from the Kodi video library with that of Alpha, even if the series is deactivated try: if config.is_xbmc(): # If it's Kodi, we do it from platformcode import xbmc_videolibrary xbmc_videolibrary.mark_content_as_watched_on_kod( filetools.join(path, 'tvshow.nfo')) except: logger.error(traceback.format_exc()) continue # Obtain the update date and the next scheduled for this series update_next = serie.update_next if update_next: y, m, d = update_next.split('-') update_next = datetime.date(int(y), int(m), int(d)) else: update_next = hoy update_last = serie.update_last if update_last: y, m, d = update_last.split('-') update_last = datetime.date(int(y), int(m), int(d)) else: update_last = hoy # if the series is active ... if overwrite or config.get_setting("updatetvshows_interval", "videolibrary") == 0: # ... force update regardless of interval serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next = hoy + datetime.timedelta(days=interval) elif interval == 1 and update_next <= hoy: # ...daily update serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada and update_last <= hoy - datetime.timedelta( days=7): # if it hasn't been updated for a week, change the interval to weekly interval = 7 update_next = hoy + datetime.timedelta(days=interval) elif interval == 7 and update_next <= hoy: # ... weekly update serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: if update_last <= hoy - datetime.timedelta(days=14): # if it has not been updated for 2 weeks, change the interval to monthly interval = 30 update_next += datetime.timedelta(days=interval) elif interval == 30 and update_next <= hoy: # ... monthly update serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next += datetime.timedelta(days=interval) if serie_actualizada: update_last = hoy update_next = hoy + datetime.timedelta(days=interval) head_nfo, serie = videolibrarytools.read_nfo( tvshow_file) # Reread the .nfo, which has been modified if interval != int(serie.active) or update_next.strftime( '%Y-%m-%d' ) != serie.update_next or update_last.strftime( '%Y-%m-%d') != serie.update_last: serie.update_last = update_last.strftime('%Y-%m-%d') if update_next > hoy: serie.update_next = update_next.strftime('%Y-%m-%d') serie.active = interval serie.channel = "videolibrary" serie.action = "get_seasons" filetools.write(tvshow_file, head_nfo + serie.tojson()) if serie_actualizada: if config.get_setting("search_new_content", "videolibrary") == 0: # We update the Kodi video library: Find content in the series folder if config.is_xbmc() and config.get_setting( "videolibrary_kodi"): from platformcode import xbmc_videolibrary xbmc_videolibrary.update( folder=filetools.basename(path)) else: update_when_finished = True if estado_verify_playcount_series: # If any playcount has been changed, ... estado = config.set_setting( "verify_playcount", True, "videolibrary") # ... we update the Videolibrary option if config.get_setting( "search_new_content", "videolibrary") == 1 and update_when_finished: # We update the Kodi video library: Find content in all series if config.is_xbmc() and config.get_setting( "videolibrary_kodi"): from platformcode import xbmc_videolibrary xbmc_videolibrary.update() p_dialog.close() else: logger.debug("Not update the video library, it is disabled") except Exception as ex: logger.error("An error occurred while updating the series") template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) if p_dialog: p_dialog.close() from core.item import Item item_dummy = Item() videolibrary.list_movies(item_dummy, silent=True) if config.get_setting('trakt_sync'): from core import trakt_tools trakt_tools.update_all()
def main(): if scrapertools.wait_for_internet(retry=10): # -- Update channels from repository streamondemand ------ try: from core import update_channels except: logger.info( "streamondemand.library_service Error in update_channels") # ---------------------------------------------------------------------- # -- Update servertools and servers from repository streamondemand ------ try: from core import update_servers except: logger.info( "streamondemand.library_service Error in update_servers") # ---------------------------------------------------------------------- logger.info("streamondemand.library_service Actualizando series...") p_dialog = None try: if config.get_setting("updatelibrary") == "true": heading = 'Aggiornamento biblioteca....' p_dialog = platformtools.dialog_progress_bg( 'streamondemand', heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk( library.TVSHOWS_PATH): show_list.extend([ filetools.join(path, f) for f in files if f == "tvshow.json" ]) # fix float porque la division se hace mal en python 2.x t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): serie = Item().fromjson(filetools.read(tvshow_file)) path = filetools.dirname(tvshow_file) logger.info("streamondemand.library_service serie=" + serie.contentSerieName) logger.info( "streamondemand.library_service Actualizando " + path) logger.info("streamondemand.library_service url " + serie.url) show_name = serie.contentTitle if show_name == "": show_name = serie.show p_dialog.update(int(math.ceil((i + 1) * t)), heading, show_name) # si la serie esta activa se actualiza if serie.active: try: pathchannels = filetools.join( config.get_runtime_path(), "channels", serie.channel + '.py') logger.info( "streamondemand.library_service Cargando canal: " + pathchannels + " " + serie.channel) obj = imp.load_source(serie.channel, pathchannels) itemlist = obj.episodios(serie) try: library.save_library_episodes( path, itemlist, serie, True) except Exception as ex: logger.info( "streamondemand.library_service Error al guardar los capitulos de la serie" ) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format( type(ex).__name__, ex.args) logger.info(message) except Exception as ex: logger.error( "Error al obtener los episodios de: {0}". format(serie.show)) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format( type(ex).__name__, ex.args) logger.info(message) p_dialog.close() else: logger.info( "No actualiza la biblioteca, está desactivado en la configuración de streamondemand" ) except Exception as ex: logger.info( "streamondemand.library_service Se ha producido un error al actualizar las series" ) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info(message) if p_dialog: p_dialog.close()
def download_from_url(url, item): logger.info("Intentando descargar: %s" % (url)) if url.lower().endswith(".m3u8") or url.lower().startswith("rtmp"): save_server_statistics(item.server, 0, False) return {"downloadStatus": STATUS_CODES.error} # Obtenemos la ruta de descarga y el nombre del archivo download_path = filetools.dirname( filetools.join(DOWNLOAD_PATH, item.downloadFilename)) file_name = filetools.basename( filetools.join(DOWNLOAD_PATH, item.downloadFilename)) # Creamos la carpeta si no existe if not filetools.exists(download_path): filetools.mkdir(download_path) # Mostramos el progreso progreso = platformtools.dialog_progress("Descargas", "Iniciando descarga...") # Lanzamos la descarga d = Downloader(url, download_path, file_name) d.start() # Monitorizamos la descarga hasta que se termine o se cancele while d.state == d.states.downloading and not progreso.iscanceled(): time.sleep(0.1) line1 = "%s" % (filetools.decode(d.filename)) line2 = "%.2f%% - %.2f %s de %.2f %s a %.2f %s/s (%d/%d)" % ( d.progress, d.downloaded[1], d.downloaded[2], d.size[1], d.size[2], d.speed[1], d.speed[2], d.connections[0], d.connections[1]) line3 = "Tiempo restante: %s" % (d.remaining_time) progreso.update(int(d.progress), line1, line2, line3) # Descarga detenida. Obtenemos el estado: # Se ha producido un error en la descarga if d.state == d.states.error: logger.info("Error al intentar descargar %s" % (url)) d.stop() progreso.close() status = STATUS_CODES.error # Aun está descargando (se ha hecho click en cancelar) elif d.state == d.states.downloading: logger.info("Descarga detenida") d.stop() progreso.close() status = STATUS_CODES.canceled # La descarga ha finalizado elif d.state == d.states.completed: logger.info("Descargado correctamente") progreso.close() status = STATUS_CODES.completed if item.downloadSize and item.downloadSize != d.size[0]: status = STATUS_CODES.error save_server_statistics(item.server, d.speed[0], d.state != d.states.error) if progreso.iscanceled(): status = STATUS_CODES.canceled dir = os.path.dirname(item.downloadFilename) file = filetools.join(dir, d.filename) if status == STATUS_CODES.completed: move_to_libray(item.clone(downloadFilename=file)) return { "downloadUrl": d.download_url, "downloadStatus": status, "downloadSize": d.size[0], "downloadProgress": d.progress, "downloadCompleted": d.downloaded[0], "downloadFilename": file }
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'] = '%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 xbmc.getCondVisibility("system.platform.Windows"): 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 if xbmc.getCondVisibility("system.platform.Android"): environment['os_name'] = 'Android' 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 '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 xbmc.getCondVisibility("system.platform.Linux"): environment['os_name'] = 'Linux' 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 elif xbmc.getCondVisibility("system.platform.Linux.RaspberryPi"): environment['os_name'] = 'RaspberryPi' else: environment['os_name'] = str(platform.system()) 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() == '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("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() == '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'] = '?' if environment['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")]) 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' 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']: if xbmc.getCondVisibility("system.platform.Android"): unrar = 'Android' else: unrar = filetools.dirname(environment['torrentcli_unrar']) unrar = filetools.basename(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 != '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'] = 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['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) if not cliente['D_load_Path_perm']: del cliente['D_load_Path_perm'] 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['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) if not cliente['D_load_Path_perm']: del cliente['D_load_Path_perm'] cliente['Buffer'] = str( config.get_setting("mct_buffer", server="torrent", default=50)) elif xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % cliente['Plug_in']): try: __settings__ = xbmcaddon.Addon(id="plugin.video.%s" % cliente['Plug_in']) except: continue cliente['Plug_in'] = cliente['Plug_in'].capitalize() if cliente['Plug_in'] == 'Torrenter': cliente['D_load_Path'] = str( filetools.translatePath( __settings__.getSetting('storage'))) if not cliente['D_load_Path']: cliente['D_load_Path'] = str(filetools.join("special://home/", \ "cache", "xbmcup", "plugin.video.torrenter", "Torrenter")) cliente['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) if not cliente['D_load_Path_perm']: del cliente['D_load_Path_perm'] cliente['Buffer'] = str( __settings__.getSetting('pre_buffer_bytes')) else: cliente['D_load_Path'] = str( filetools.translatePath( __settings__.getSetting('download_path'))) cliente['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) if not cliente['D_load_Path_perm']: del cliente['D_load_Path_perm'] 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 if cliente['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['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()), \ 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-mobile-assistant.version')): environment['assistant_version'] = filetools.read( filetools.join(config.get_data_path(), 'alfa-mobile-assistant.version')) environment['assistant_cf_ua'] = str( config.get_setting('cf_assistant_ua', None)) 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 establecer_contenido(content_type, silent=False): if config.is_xbmc(): continuar = False msg_text = "Ruta Biblioteca personalizada" librarypath = config.get_setting("librarypath") if librarypath == "": continuar = True if content_type == FOLDER_MOVIES: if not xbmc.getCondVisibility( 'System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno( "The Movie Database", "No se ha encontrado el Scraper de películas de TheMovieDB.", "¿Desea instalarlo ahora?") else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin( 'xbmc.installaddon(metadata.themoviedb.org)', True) logger.info( "Instalado el Scraper de películas de TheMovieDB" ) except: pass continuar = (install and xbmc.getCondVisibility( 'System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = "The Movie Database no instalado." else: # SERIES # Instalar The TVDB if not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno( "The TVDB", "No se ha encontrado el Scraper de series de The TVDB.", "¿Desea instalarlo ahora?") else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin( 'xbmc.installaddon(metadata.tvdb.com)', True) logger.info( "Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility( 'System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = "The TVDB no instalado." # Instalar TheMovieDB if continuar and not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno( "The Movie Database", "No se ha encontrado el Scraper de series de TheMovieDB.", "¿Desea instalarlo ahora?") else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org # 1º Probar desde el repositorio ... xbmc.executebuiltin( 'xbmc.installaddon(metadata.tvshows.themoviedb.org)', True) if not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)' ): # ...si no funciona descargar e instalar desde la web url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip" path_down = xbmc.translatePath( "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip" ) path_unzip = xbmc.translatePath( "special://home/addons/") header = ( "User-Agent", "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013" ) from core import downloadtools from core import ziptools downloadtools.downloadfile(url, path_down, continuar=True, headers=[header]) unzipper = ziptools.ziptools() unzipper.extract(path_down, path_unzip) xbmc.executebuiltin('xbmc.UpdateLocalAddons') strSettings = '<settings>\n' \ ' <setting id="fanart" value="true" />\n' \ ' <setting id="keeporiginaltitle" value="false" />\n' \ ' <setting id="language" value="es" />\n' \ '</settings>' path_settings = xbmc.translatePath( "special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml" ) tv_themoviedb_addon_path = filetools.dirname( path_settings) if not filetools.exists(tv_themoviedb_addon_path): filetools.mkdir(tv_themoviedb_addon_path) if filetools.write(path_settings, strSettings): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = "The Movie Database no instalado." idPath = 0 idParentPath = 0 strPath = "" if continuar: continuar = False librarypath = "special://home/userdata/addon_data/plugin.video." + config.PLUGIN_NAME + "/library/" # Buscamos el idPath sql = 'SELECT MAX(idPath) FROM path' nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idPath = records[0][0] + 1 # Buscamos el idParentPath sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % \ librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/') nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idParentPath = records[0][0] librarypath = records[0][1] continuar = True else: # No existe librarypath en la BD: la insertamos sql = 'INSERT INTO path (idPath, strPath, scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \ '(%s, "%s", 0, 0, 0, 0)' % (idPath, librarypath) nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True idParentPath = idPath idPath += 1 else: msg_text = "Error al fijar librarypath en BD" if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == FOLDER_MOVIES: strContent = 'movies' strScraper = 'metadata.themoviedb.org' scanRecursive = 2147483647 strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \ "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \ "<setting id='language' value='es' /><setting id='tmdbcertcountry' value='us' />" \ "<setting id='trailer' value='true' /></settings>" strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para películas?" else: strContent = 'tvshows' strScraper = 'metadata.tvdb.com' scanRecursive = 0 strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \ "<setting id='absolutenumber' value='false' />" \ "<setting id='dvdorder' value='false' />" \ "<setting id='fallback' value='true' />" \ "<setting id='fanart' value='true' />" \ "<setting id='language' value='es' /></settings>" strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para series?" # Fijamos strPath strPath = librarypath + content_type + "/" logger.info("%s: %s" % (content_type, strPath)) # Comprobamos si ya existe strPath en la BD para evitar duplicados sql = 'SELECT idPath FROM path where strPath="%s"' % strPath nun_records, records = execute_sql_kodi(sql) sql = "" if nun_records == 0: # Insertamos el scraper sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \ 'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno( "The TVDB", strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = "Error al configurar el scraper en la BD." if not continuar: heading = "Biblioteca no %s configurada" % content_type #msg_text = "Asegurese de tener instalado el scraper de The Movie Database" elif content_type == FOLDER_TVSHOWS and not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = "Biblioteca %s configurada" % content_type msg_text = "Es necesario reiniciar Kodi para que los cambios surtan efecto." else: heading = "Biblioteca %s configurada" % content_type msg_text = "Felicidades la biblioteca de Kodi ha sido configurada correctamente." platformtools.dialog_notification(heading, msg_text, icon=1, time=10000) logger.info("%s: %s" % (heading, msg_text))
def check_for_update(overwrite=True): logger.info("Actualizando series...") p_dialog = None serie_actualizada = False update_when_finished = False hoy = datetime.date.today() try: if config.get_setting("updatelibrary", "biblioteca") != 0 or overwrite: config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "biblioteca") heading = 'Actualizando biblioteca....' p_dialog = platformtools.dialog_progress_bg('mitvspain', heading) p_dialog.update(0, '') import glob show_list = glob.glob( filetools.join(library.TVSHOWS_PATH, u'/*/tvshow.nfo')) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = library.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) logger.info("serie=" + serie.contentSerieName) p_dialog.update(int(math.ceil((i + 1) * t)), heading, serie.contentSerieName) interval = int(serie.active) # Podria ser del tipo bool if not serie.active: # si la serie no esta activa descartar continue # obtenemos las fecha de actualizacion y de la proxima programada para esta serie update_next = serie.update_next if update_next: y, m, d = update_next.split('-') update_next = datetime.date(int(y), int(m), int(d)) else: update_next = hoy update_last = serie.update_last if update_last: y, m, d = update_last.split('-') update_last = datetime.date(int(y), int(m), int(d)) else: update_last = hoy # si la serie esta activa ... if overwrite or config.get_setting("updatetvshows_interval", "biblioteca") == 0: # ... forzar actualizacion independientemente del intervalo serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) elif interval == 1 and update_next <= hoy: # ...actualizacion diaria serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada and update_last <= hoy - datetime.timedelta( days=7): # si hace una semana q no se actualiza, pasar el intervalo a semanal interval = 7 update_next = hoy + datetime.timedelta(days=interval) elif interval == 7 and update_next <= hoy: # ...actualizacion semanal serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: if update_last <= hoy - datetime.timedelta(days=14): # si hace 2 semanas q no se actualiza, pasar el intervalo a mensual interval = 30 update_next += datetime.timedelta(days=interval) elif interval == 30 and update_next <= hoy: # ...actualizacion mensual serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next += datetime.timedelta(days=interval) if interval != int(serie.active) or update_next.strftime( '%Y-%m-%d') != serie.update_next: serie.active = interval serie.update_next = update_next.strftime('%Y-%m-%d') serie.channel = "biblioteca" serie.action = "get_temporadas" filetools.write(tvshow_file, head_nfo + serie.tojson()) if serie_actualizada: if config.get_setting("search_new_content", "biblioteca") == 0: # Actualizamos la biblioteca de Kodi: Buscar contenido en la carpeta de la serie if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.update( folder=filetools.basename(path)) else: update_when_finished = True if config.get_setting("search_new_content", "biblioteca") == 1 and update_when_finished: # Actualizamos la biblioteca de Kodi: Buscar contenido en todas las series if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.update() p_dialog.close() else: logger.info( "No actualiza la biblioteca, está desactivado en la configuración de mitvspain" ) except Exception, ex: logger.error("Se ha producido un error al actualizar las series") template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) if p_dialog: p_dialog.close()
def findvideos(item): from core import autoplay logger.info() # 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 [] content_title = str(item.contentSeason) + 'x' + (str(item.contentEpisodeNumber) if item.contentEpisodeNumber > 9 else '0' + str(item.contentEpisodeNumber)) 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) from platformcode import platformtools index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index < 0: return [] elif item_local and index == len(opciones) - 1: filtro_canal = 'downloads' platformtools.play_video(item_local) elif index > 0: filtro_canal = opciones[index].replace(config.get_localized_string(70078), "").strip() itemlist = [] for nom_canal, json_path in list(list_canales.items()): if filtro_canal and filtro_canal != nom_canal.capitalize(): continue item_canal = Item() # 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") item_json = Item().fromjson(filetools.read(json_path)) list_servers = [] # from core.support import dbg;dbg() 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
description) finally: if fp: fp.close() elif xbmc.getCondVisibility("system.platform.android"): try: import imp from ctypes import CDLL dest_path = '' envirom = os.environ.get('KODI_ANDROID_APK', '') if not envirom: envirom = os.environ.get('XBMC_ANDROID_APK', '') if envirom: log(envirom) dest_path = filetools.join(filetools.dirname(envirom), 'lib') dest_path_dir = filetools.listdir(dest_path) log(filetools.listdir(dest_path, file_inf=True)) if dest_path_dir: for folder in dest_path_dir: if 'arm' in folder or 'aarch' in folder: dest_path = filetools.join(dest_path, folder) break else: dest_path = '' if dest_path and filetools.exists(dest_path): dest_path = lm.android_workaround(dest_path) if not filetools.exists( filetools.join(dest_path, 'liblibtorrent.so')): dest_path = ''
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 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: with open(inpath, "rb") as infile: 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) 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 main(): logger.info("pelisalacarta.library_service Actualizando series...") p_dialog = None try: if config.get_setting("updatelibrary") == "true": heading = 'Actualizando biblioteca....' p_dialog = platformtools.dialog_progress_bg('pelisalacarta', heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk(library.TVSHOWS_PATH): show_list.extend([filetools.join(path, f) for f in files if f == "tvshow.json"]) # fix float porque la division se hace mal en python 2.x t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): serie = Item().fromjson(filetools.read(tvshow_file)) path = filetools.dirname(tvshow_file) logger.info("pelisalacarta.library_service serie="+serie.contentSerieName) logger.info("pelisalacarta.library_service Actualizando " + path) logger.info("pelisalacarta.library_service url " + serie.url) show_name = serie.contentTitle if show_name == "": show_name = serie.show p_dialog.update(int(math.ceil((i+1) * t)), heading, show_name) # si la serie esta activa se actualiza if serie.active: try: pathchannels = filetools.join(config.get_runtime_path(), "channels", serie.channel + '.py') logger.info("pelisalacarta.library_service Cargando canal: " + pathchannels + " " + serie.channel) obj = imp.load_source(serie.channel, pathchannels) itemlist = obj.episodios(serie) try: library.save_library_episodes(path, itemlist, serie, True) except Exception as ex: logger.info("pelisalacarta.library_service Error al guardar los capitulos de la serie") template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info(message) except Exception as ex: logger.error("Error al obtener los episodios de: {0}". format(serie.show)) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info(message) p_dialog.close() else: logger.info("No actualiza la biblioteca, está desactivado en la configuración de pelisalacarta") except Exception as ex: logger.info("pelisalacarta.library_service Se ha producido un error al actualizar las series") template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info(message) if p_dialog: p_dialog.close()
def check_for_update(overwrite=True): logger.info("Actualizando series...") from core import filetools from core import channeltools, videolibrarytools from platformcode import platformtools from channels import videolibrary from lib import generictools if config.is_xbmc(): from platformcode import xbmc_videolibrary p_dialog = None serie_actualizada = False update_when_finished = False hoy = datetime.date.today() estado_verify_playcount_series = False try: if config.get_setting("update", "videolibrary") != 0 or overwrite: config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "videolibrary") heading = config.get_localized_string(60389) p_dialog = platformtools.dialog_progress_bg( config.get_localized_string(20000), heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk( videolibrarytools.TVSHOWS_PATH): show_list.extend([ filetools.join(path, f) for f in files if f == "tvshow.nfo" ]) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): try: head_nfo, serie = videolibrarytools.read_nfo(tvshow_file) if not serie: logger.error('.nfo erroneo en ' + str(tvshow_file)) continue path = filetools.dirname(tvshow_file) ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial overwrite_forced = False try: serie, serie, overwrite_forced = generictools.redirect_clone_newpct1( serie, head_nfo, serie, path, overwrite, lookup=True) except: logger.error(traceback.format_exc()) if overwrite_forced == True: overwrite = True serie.update_next = '' info_status = '' if serie.infoLabels['status']: info_status = serie.infoLabels['status'] logger.info("Serie=%s, Activa=%s, Fecha=%s, Status=%s" % (serie.contentSerieName, \ str(serie.active), str(serie.update_last), str(info_status))) p_dialog.update(int(math.ceil((i + 1) * t)), heading, serie.contentSerieName) #Verificamos el estado del serie.library_playcounts de la Serie por si está incompleto try: estado = False #Si no hemos hecho la verificación o no tiene playcount, entramos estado = config.get_setting("verify_playcount", "videolibrary") if not estado or estado == False or not serie.library_playcounts: #Si no se ha pasado antes, lo hacemos ahora serie, estado = videolibrary.verify_playcount_series( serie, path ) #También se pasa si falta un PlayCount por completo except: logger.error(traceback.format_exc()) else: if estado: #Si ha tenido éxito la actualización... estado_verify_playcount_series = True #... se marca para cambiar la opción de la Videoteca if serie.active: try: interval = int( serie.active) # Podria ser del tipo bool except: interval = 1 else: interval = 0 if not serie.active: # si la serie no esta activa descartar if overwrite_forced == False: #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa, aunque la serie esté desactivada try: if config.is_xbmc(): #Si es Kodi, lo hacemos xbmc_videolibrary.mark_content_as_watched_on_alfa( path + '/tvshow.nfo') except: logger.error(traceback.format_exc()) continue # obtenemos las fecha de actualizacion y de la proxima programada para esta serie update_next = serie.update_next if update_next: y, m, d = update_next.split('-') update_next = datetime.date(int(y), int(m), int(d)) else: update_next = hoy update_last = serie.update_last if update_last: y, m, d = update_last.split('-') update_last = datetime.date(int(y), int(m), int(d)) else: update_last = hoy # si la serie esta activa ... if overwrite or config.get_setting( "updatetvshows_interval", "videolibrary") == 0: # ... forzar actualizacion independientemente del intervalo serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next = hoy + datetime.timedelta( days=interval) elif interval == 1 and update_next <= hoy: # ...actualizacion diaria serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada and update_last <= hoy - datetime.timedelta( days=7): # si hace una semana q no se actualiza, pasar el intervalo a semanal interval = 7 update_next = hoy + datetime.timedelta( days=interval) elif interval == 7 and update_next <= hoy: # ...actualizacion semanal serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: if update_last <= hoy - datetime.timedelta( days=14): # si hace 2 semanas q no se actualiza, pasar el intervalo a mensual interval = 30 update_next += datetime.timedelta(days=interval) elif interval == 30 and update_next <= hoy: # ...actualizacion mensual serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next += datetime.timedelta(days=interval) if serie_actualizada: update_last = hoy update_next = hoy + datetime.timedelta(days=interval) head_nfo, serie = videolibrarytools.read_nfo( tvshow_file ) #Vuelve a leer el.nfo, que ha sido modificado if interval != int(serie.active) or update_next.strftime( '%Y-%m-%d' ) != serie.update_next or update_last.strftime( '%Y-%m-%d') != serie.update_last: serie.update_last = update_last.strftime('%Y-%m-%d') if update_next > hoy: serie.update_next = update_next.strftime( '%Y-%m-%d') if serie.infoLabels[ "status"] != "Ended" and serie.infoLabels[ "status"] != "Canceled": serie.active = interval serie.channel = "videolibrary" serie.action = "get_seasons" filetools.write(tvshow_file, head_nfo + serie.tojson()) if serie_actualizada and not config.get_setting( 'cleanlibrary', 'videolibrary', default=False): if config.get_setting("search_new_content", "videolibrary") == 0: # Actualizamos la videoteca de Kodi: Buscar contenido en la carpeta de la serie if config.is_xbmc(): xbmc_videolibrary.update( folder=filetools.basename(path)) update_when_finished = True else: update_when_finished = True except Exception as ex: logger.error( "Se ha producido un error al actualizar la serie %s" % tvshow_file) 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(1)) if estado_verify_playcount_series: #Si se ha cambiado algún playcount, ... estado = config.set_setting( "verify_playcount", True, "videolibrary" ) #... actualizamos la opción de Videolibrary #if config.get_setting("search_new_content", "videolibrary") == 1 and update_when_finished: if config.is_xbmc() and config.get_setting( 'cleanlibrary', 'videolibrary', default=False): while xbmc.getCondVisibility( 'Library.IsScanningVideo()'): # Se espera a que acabe time.sleep(1) xbmc.executebuiltin('CleanLibrary(video)') while xbmc.getCondVisibility( 'Library.IsScanningVideo()'): # Se espera a que acabe time.sleep(1) update_when_finished = True config.set_setting('cleanlibrary', False, 'videolibrary') if update_when_finished: # Actualizamos la videoteca de Kodi: Buscar contenido en todas las series if config.is_xbmc(): xbmc_videolibrary.update() p_dialog.close() else: logger.info( "No actualiza la videoteca, está desactivado en la configuración de alfa" ) except Exception as ex: logger.error("Se ha producido un error al actualizar las series") template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) if p_dialog: p_dialog.close() # Sincroniza los "vistos" de la Videoteca de Películas from core.item import Item item_dummy = Item() videolibrary.list_movies(item_dummy, silent=True) # Descarga los últimos episodios disponibles, si el canal lo permite if config.get_setting("update", "videolibrary") != 0 or overwrite: from channels import downloads downloads.download_auto(item_dummy)
def main(overwrite=True): logger.info("pelisalacarta.library_service Actualizando series...") p_dialog = None try: if config.get_setting("updatelibrary") == "true": if not overwrite: # No venimos del canal configuracion updatelibrary_wait = [0, 10000, 20000, 30000, 60000] wait = updatelibrary_wait[int(config.get_setting("updatelibrary_wait"))] if wait > 0: import xbmc xbmc.sleep(wait) heading = 'Actualizando biblioteca....' p_dialog = platformtools.dialog_progress_bg('pelisalacarta', heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk(library.TVSHOWS_PATH): show_list.extend([filetools.join(path, f) for f in files if f == "tvshow.nfo"]) # fix float porque la division se hace mal en python 2.x t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): serie = Item().fromjson(filetools.read(tvshow_file, 1)) path = filetools.dirname(tvshow_file) logger.info("pelisalacarta.library_service serie=" + serie.contentSerieName) p_dialog.update(int(math.ceil((i+1) * t)), heading, serie.contentSerieName) if not serie.active: continue # si la serie esta activa se actualiza logger.info("pelisalacarta.library_service Actualizando " + path) # logger.debug("%s: %s" %(serie.contentSerieName,str(list_canales) )) for channel, url in serie.library_urls.items(): serie.channel = channel serie.url = url p_dialog.update(int(math.ceil((i + 1) * t)), heading, "%s: %s" % (serie.contentSerieName, serie.channel.capitalize())) try: pathchannels = filetools.join(config.get_runtime_path(), "channels", serie.channel + '.py') logger.info("pelisalacarta.library_service Cargando canal: " + pathchannels + " " + serie.channel) if serie.library_filter_show: serie.show = serie.library_filter_show.get(channel, serie.contentSerieName) obj = imp.load_source(serie.channel, pathchannels) itemlist = obj.episodios(serie) try: library.save_library_episodes(path, itemlist, serie, silent=True, overwrite=overwrite) except Exception as ex: logger.info("pelisalacarta.library_service Error al guardar los capitulos de la serie") template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info(message) except Exception as ex: logger.error("Error al obtener los episodios de: {0}". format(serie.show)) template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info(message) p_dialog.close() else: logger.info("No actualiza la biblioteca, está desactivado en la configuración de pelisalacarta") except Exception as ex: logger.info("pelisalacarta.library_service Se ha producido un error al actualizar las series") template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.info(message) if p_dialog: p_dialog.close()
def check_for_update(overwrite=True): logger.info("Aggiornamento series...") p_dialog = None serie_actualizada = False update_when_finished = False hoy = datetime.date.today() try: if config.get_setting("updatelibrary", "biblioteca") != 0 or overwrite: config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "biblioteca") heading = 'Aggiornamento della libreria...' p_dialog = platformtools.dialog_progress_bg( 'streamondemand', heading) p_dialog.update(0, '') import glob show_list = glob.glob( filetools.join(library.TVSHOWS_PATH, u'/*/tvshow.nfo')) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = library.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) logger.info("serie=" + serie.contentSerieName) p_dialog.update(int(math.ceil((i + 1) * t)), heading, serie.contentSerieName) interval = int(serie.active) # Can be bool type if not serie.active: # Unload if the Serie is not active continue # Update next update_next = serie.update_next if update_next: y, m, d = update_next.split('-') update_next = datetime.date(int(y), int(m), int(d)) else: update_next = hoy update_last = serie.update_last if update_last: y, m, d = update_last.split('-') update_last = datetime.date(int(y), int(m), int(d)) else: update_last = hoy # if the Serie is active ... if overwrite or config.get_setting("updatetvshows_interval", "biblioteca") == 0: # ... force autonomus update serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) elif interval == 1 and update_next <= hoy: # ...weekly update serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada and update_last <= hoy - datetime.timedelta( days=7): # raise the interval interval = 7 update_next = hoy + datetime.timedelta(days=interval) elif interval == 7 and update_next <= hoy: # ...14days update serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: if update_last <= hoy - datetime.timedelta(days=14): # raise the interval interval = 30 update_next += datetime.timedelta(days=interval) elif interval == 30 and update_next <= hoy: # ...monthly update serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next += datetime.timedelta(days=interval) if interval != int(serie.active) or update_next.strftime( '%Y-%m-%d') != serie.update_next: serie.active = interval serie.update_next = update_next.strftime('%Y-%m-%d') serie.channel = "biblioteca" serie.action = "get_temporadas" filetools.write(tvshow_file, head_nfo + serie.tojson()) if serie_actualizada: if config.get_setting("search_new_content", "biblioteca") == 0: # Update Kodi library: Search contents in the Serie directory if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.update( folder=filetools.basename(path)) else: update_when_finished = True if config.get_setting("search_new_content", "biblioteca") == 1 and update_when_finished: # Update Kodi library: Search contents for every Serie if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.update() p_dialog.close() else: logger.info( "Libreria non aggiornata, opzione disattiva nella configurazione di streamondemand" ) except Exception as ex: logger.error("Si è verificato un errore nell'aggiornamento") template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) if p_dialog: p_dialog.close()
def check_for_update(overwrite=True): logger.info("Actualizando series...") p_dialog = None serie_actualizada = False hoy = datetime.date.today() try: if config.get_setting("updatelibrary", "biblioteca") != 0 or overwrite: config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "biblioteca") if config.get_setting("updatelibrary", "biblioteca") == 1 and not overwrite: # "Actualizar al inicio" y No venimos del canal configuracion updatelibrary_wait = [0, 10000, 20000, 30000, 60000] wait = updatelibrary_wait[int( config.get_setting("updatelibrary_wait", "biblioteca"))] if wait > 0: import xbmc xbmc.sleep(wait) heading = 'Actualizando biblioteca....' p_dialog = platformtools.dialog_progress_bg( 'pelisalacarta', heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk(library.TVSHOWS_PATH): show_list.extend([ filetools.join(path, f) for f in files if f == "tvshow.nfo" ]) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = library.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) logger.info("serie=" + serie.contentSerieName) p_dialog.update(int(math.ceil((i + 1) * t)), heading, serie.contentSerieName) interval = int(serie.active) # Podria ser del tipo bool if not serie.active: # si la serie no esta activa descartar continue # obtenemos las fecha de auctualizacion y de la proxima programada para esta serie update_next = serie.update_next if update_next: y, m, d = update_next.split('-') update_next = datetime.date(int(y), int(m), int(d)) else: update_next = hoy update_last = serie.update_last if update_last: y, m, d = update_last.split('-') update_last = datetime.date(int(y), int(m), int(d)) else: update_last = hoy # si la serie esta activa ... if overwrite or config.get_setting("updatetvshows_interval", "biblioteca") == 0: # ... forzar actualizacion independientemente del intervalo serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) elif interval == 1 and update_next <= hoy: # ...actualizacion diaria serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada and update_last <= hoy - datetime.timedelta( days=7): # si hace una semana q no se actualiza, pasar el intervalo a semanal interval = 7 update_next = hoy + datetime.timedelta(days=interval) elif interval == 7 and update_next <= hoy: # ...actualizacion semanal serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: if update_last <= hoy - datetime.timedelta(days=14): # si hace 2 semanas q no se actualiza, pasar el intervalo a mensual interval = 30 update_next += datetime.timedelta(days=interval) elif interval == 30 and update_next <= hoy: # ...actualizacion mensual serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next += datetime.timedelta(days=interval) if interval != int(serie.active) or update_next.strftime( '%Y-%m-%d') != serie.update_next: serie.active = interval serie.update_next = update_next.strftime('%Y-%m-%d') serie.channel = "biblioteca" serie.action = "get_temporadas" filetools.write(tvshow_file, head_nfo + serie.tojson()) if serie_actualizada: # Actualizamos la biblioteca de Kodi xbmc_library.update(folder=filetools.basename(path)) p_dialog.close() else: logger.info( "No actualiza la biblioteca, está desactivado en la configuración de pelisalacarta" ) except Exception as ex: logger.error("Se ha producido un error al actualizar las series") template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.error(message) if p_dialog: p_dialog.close()
def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None): allocate = True try: log("XXX KODI XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") log("OS platform: %s %s" % (platform.system(),platform.release())) log("xbmc/kodi version: %s" % xbmc.getInfoLabel( "System.BuildVersion" )) xbmc_version = int(xbmc.getInfoLabel( "System.BuildVersion" )[:2]) log("Architecture: %s %s" % (str(platform.machine()), \ str(sys.maxsize > 2 ** 32 and "64-bit" or "32-bit"))) log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX KODI & platform XXXX") except: log(traceback.format_exc()) # -- adfly: ------------------------------------ if url.startswith("http://adf.ly/"): try: data = httptools.downloadpage(url).data url = decode_adfly(data) except: ddd = xbmcgui.Dialog() ddd.ok( msg_header + ": Sin soporte adf.ly", "El script no tiene soporte para el acortador de urls adf.ly." + '\n' + " " + '\n' + "url: " + url ) return """ # -- Necesario para algunas webs ---------------------------- if not url.endswith(".torrent") and not url.startswith("magnet"): #t_file = httptools.downloadpage(url, follow_redirects=False).headers["location"] t_file = scrapertools.get_header_from_response(url, header_to_get="location") if t_file: if len(t_file) > 0: url = t_file t_file = httptools.downloadpage(url, follow_redirects=False).headers["location"] if len(t_file) > 0: url = t_file """ # -- Crear dos carpetas en descargas para los archivos ------ save_path_videos = os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ) save_path_torrents = os.path.join( DOWNLOAD_PATH , "MCT-torrents" ) if not os.path.exists( save_path_torrents ): os.mkdir(save_path_torrents) video_path = '' global bkg_user bkg_user = False dp_BG = False DOWNGROUND = False torrent_stop = False BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True) if item.downloadFilename and item.downloadStatus in [2, 4]: # Descargas AUTO BACKGROUND = True DOWNGROUND = True bkg_user = True global ses_lt ses_lt = False 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']) item.rar_path = video_path # -- Usar - archivo torrent desde web, magnet o HD --------- if not os.path.isfile(url) and not url.startswith("magnet"): # -- http - crear archivo torrent ----------------------- data = url_get(url) # -- El nombre del torrent será el que contiene en los -- # -- datos. - re_name = urllib.unquote( scrapertools.find_single_match(data,':name\d+:(.*?)\d+:') ) import bencode, hashlib decodedDict = bencode.bdecode(data) if not PY3: re_name = hashlib.sha1(bencode.bencode(decodedDict[b"info"])).hexdigest() else: re_name = hashlib.sha1(bencode.bencode(decodedDict["info"])).hexdigest() torrent_file = os.path.join(save_path_torrents, encode(re_name.upper() + '.torrent')) f = open(torrent_file,'wb') f.write(data) f.close() elif os.path.isfile(url): # -- file - para usar torrens desde el HD --------------- torrent_file = filetools.join(save_path_torrents, filetools.basename(url).upper()).replace('.TORRENT', '.torrent') filetools.copy(url, torrent_file, silent=True) else: # -- magnet --------------------------------------------- torrent_file = url torrent_file = torrent_file.replace('.TORRENT', '.torrent') # ----------------------------------------------------------- # -- MCT - MiniClienteTorrent ------------------------------- try: log("XXX libtorrent pathname: %s" % str(LIBTORRENT_PATH)) ses = lt.session() except Exception as e: do = xbmcgui.Dialog() e = e1 or e2 do.ok('ERROR en el cliente MCT Libtorrent', 'Módulo no encontrado o imcompatible con el dispositivo.' + '\n' + 'Reporte el fallo adjuntando un "log".' + '\n' + str(e)) return log("XXX libtorrent version: %s" % lt.version) log("##### Torrent file: %s ##" % torrent_file) ses.add_dht_router("router.bittorrent.com",6881) ses.add_dht_router("router.utorrent.com",6881) ses.add_dht_router("dht.transmissionbt.com",6881) trackers = [ "udp://tracker.openbittorrent.com:80/announce", "http://tracker.torrentbay.to:6969/announce", "http://tracker.pow7.com/announce", "udp://tracker.ccc.de:80/announce", "udp://open.demonii.com:1337", "http://9.rarbg.com:2710/announce", "http://bt.careland.com.cn:6969/announce", "http://explodie.org:6969/announce", "http://mgtracker.org:2710/announce", "http://tracker.best-torrents.net:6969/announce", "http://tracker.tfile.me/announce", "http://tracker1.wasabii.com.tw:6969/announce", "udp://9.rarbg.com:2710/announce", "udp://9.rarbg.me:2710/announce", "udp://coppersurfer.tk:6969/announce", "http://www.spanishtracker.com:2710/announce", "http://www.todotorrents.com:2710/announce", ] video_file = "" # -- magnet2torrent ----------------------------------------- if torrent_file.startswith("magnet"): try: import zlib btih = hex(zlib.crc32(scrapertools.find_single_match(torrent_file, 'magnet:\?xt=urn:(?:[A-z0-9:]+|)([A-z0-9]{32})')) & 0xffffffff) t_hash = scrapertools.find_single_match(torrent_file, 'xt=urn:btih:([^\&]+)\&') files = [f for f in os.listdir(save_path_torrents) if os.path.isfile(os.path.join(save_path_torrents, f))] for file in files: if btih in os.path.basename(file): torrent_file = os.path.join(save_path_torrents, file) except: pass if torrent_file.startswith("magnet"): try: tempdir = tempfile.mkdtemp() except IOError: tempdir = os.path.join(save_path_torrents , "temp") if not os.path.exists(tempdir): os.mkdir(tempdir) params = { 'save_path': tempdir, 'trackers': trackers, 'storage_mode': lt.storage_mode_t.storage_mode_allocate } """ , 'paused': False, 'auto_managed': True, 'duplicate_is_error': True """ h = lt.add_magnet_uri(ses, torrent_file, params) dp = xbmcgui.DialogProgress() dp.create(msg_header) while not h.has_metadata(): message, porcent, msg_file, s, download = getProgress(h, "Creando torrent desde magnet") dp.update(porcent, message + '\n' + msg_file + '\n' + ' ') if s.state == 1: download = 1 if dp.iscanceled(): dp.close() remove_files( download, torrent_file, video_file, ses, h, '', item ) return h.force_dht_announce() xbmc.sleep(1000) dp.close() info = h.get_torrent_info() data = lt.bencode( lt.create_torrent(info).generate() ) #torrent_file = os.path.join(save_path_torrents, unicode(info.name()+"-"+btih, "'utf-8'", errors="replace") + ".torrent") torrent_file = os.path.join(save_path_torrents, t_hash.upper()+".torrent") f = open(torrent_file,'wb') f.write(data) f.close() ses.remove_torrent(h) filetools.rmdirtree(tempdir) # ----------------------------------------------------------- # -- Archivos torrent --------------------------------------- e = lt.bdecode(open(torrent_file, 'rb').read()) info = lt.torrent_info(e) # -- El más gordo o uno de los más gordo se entiende que es - # -- el vídeo o es el vídeo que se usará como referencia - # -- para el tipo de archivo - log("##### Archivos ## %s ##" % len(info.files())) _index_file, _video_file, _size_file = get_video_file(info) # -- Prioritarizar/Seleccionar archivo----------------------- _index, video_file, video_size, len_files = get_video_files_sizes( info ) if len_files == 0: dp = xbmcgui.Dialog().ok("No se puede reproducir", "El torrent no contiene ningún archivo de vídeo") if _index < 0: log("##### parts = %s #########" % str(video_file)) log("##### video_size = %s #########" % str(video_size)) log("##### _index = %s #########" % str(_index)) #if _index == -1: # _index = _index_file # video_size = _size_file video_file = _video_file else: log("##### video_size = %s #########" % str(video_size)) log("##### _index = %s #########" % str(_index)) _video_file_ext = os.path.splitext( _video_file )[1] log("##### _video_file ## %s ##" % str(_video_file)) log("##### _video_file_ext ## %s ##" % _video_file_ext) if url.startswith('magnet:') or _index > 0: item.downloadFilename = ':%s: %s' % ('MCT', video_file) item.downloadQueued = 0 time.sleep(1) torr.update_control(item, function='mct_start') dp_cerrado = True rar = False global extracted_rar extracted_rar = False global erase_file_path erase_file_path = '' if _video_file_ext == ".rar": rar = True filename = video_file if "/" in filename: filename = filename.split("/")[1] if (RAR and BACKGROUND): xbmcgui.Dialog().notification("Encontrado archivo .RAR de %.2f MB" % (video_size / 1048576.0), "Puedes realizar otras tareas en Kodi mientrastanto. " + \ "Te informaremos...", time=10000) dialog = True else: dialog = xbmcgui.Dialog().yesno("Encontrado archivo .RAR...", "Nombre: %s" % filename + '\n' + "Tamaño: %.2f MB" % (video_size / 1048576.0) + '\n' + "¿Descargar en segundo plano? Cancelar en menú Descargas") if dialog: dp_cerrado = False dp = xbmcgui.DialogProgressBG() dp.create(msg_header) dp_BG = True if (_video_file_ext == ".avi" or _video_file_ext == ".mp4" or _video_file_ext == ".mkv") and allocate: log("##### storage_mode_t.storage_mode_allocate ("+_video_file_ext+") #####") h = ses.add_torrent( { 'ti':info, 'save_path': save_path_videos, 'trackers':trackers, 'storage_mode':lt.storage_mode_t.storage_mode_allocate } ) else: log("##### storage_mode_t.storage_mode_sparse ("+_video_file_ext+") #####") h = ses.add_torrent( { 'ti':info, 'save_path': save_path_videos, 'trackers':trackers, 'storage_mode':lt.storage_mode_t.storage_mode_sparse } ) allocate = True ses_lt = True # ----------------------------------------------------------- # -- Descarga secuencial - trozo 1, trozo 2, ... ------------ h.set_sequential_download(True) h.force_reannounce() h.force_dht_announce() # -- Inicio de variables para 'pause' automático cuando el - # -- el vídeo se acerca a una pieza sin completar - is_greater_num_pieces = False is_greater_num_pieces_plus = False is_greater_num_pieces_pause = False porcent4first_pieces = int( video_size * 0.000000005 ) porcent4first_pieces = BUFFER if porcent4first_pieces < BUFFER: porcent4first_pieces = BUFFER if porcent4first_pieces > 100: porcent4first_pieces = 100 porcent4last_pieces = int(old_div(porcent4first_pieces,2)) num_pieces_to_resume = int( video_size * 0.0000000025 ) if num_pieces_to_resume < 10: num_pieces_to_resume = 10 if num_pieces_to_resume > 25: num_pieces_to_resume = 25 log("##### porcent4first_pieces ## %s ##" % porcent4first_pieces) log("##### porcent4last_pieces ## %s ##" % porcent4last_pieces) log("##### num_pieces_to_resume ## %s ##" % num_pieces_to_resume) # -- Prioritarizar o seleccionar las piezas del archivo que - # -- se desea reproducir con 'file_priorities' - piece_set = set_priority_pieces(h, _index, video_file, video_size, porcent4first_pieces, porcent4last_pieces, allocate) global tot_piece_set tot_piece_set = len(piece_set) log("##### total piece_set ## %s ##" % len(piece_set)) if dp_cerrado: if bkg_user: dp = xbmcgui.DialogProgressBG() dp.create(msg_header) dp_BG = True else: # -- Crear diálogo de progreso para el primer bucle --------- dp = xbmcgui.DialogProgress() dp.create(msg_header) _pieces_info = {} ren_video_file = os.path.join( save_path_videos, video_file ) # -- Doble bucle anidado ------------------------------------ # -- Descarga - Primer bucle x = 1 while not h.is_seed(): x += 1 s = h.status() xbmc.sleep(1000) if not dp_cerrado and not BACKGROUND: dp.close() dp_cerrado = True dp = xbmcgui.DialogProgress() dp.create(msg_header) # -- Recuperar los datos del progreso ------------------- message, porcent, msg_file, s, download = getProgress(h, video_file, _pf=_pieces_info) # Si se ha borrado el .torrent es porque se quiere cancelar la sesión #log("##### x: %s" % str(x)) #log("##### exists: %s" % str(filetools.exists(torrent_file))) if ((download > 1 and (str(x).endswith('0') or str(x).endswith('5'))) \ or (download == 0 and x > 30)) and not filetools.exists(torrent_file): log('LISTADO de .torrent %s' % (filetools.listdir(filetools.dirname(torrent_file)))) if filetools.exists(torrent_file.replace('.torrent', '.pause')) or filetools.exists(torrent_file.replace('.TORRENT', '.pause')): torrent_paused = True torrent_stop = True action = 'pause' item.downloadProgress = -1 res = filetools.remove(torrent_file.replace('.torrent', '.pause').replace('.TORRENT', '.pause'), silent=True) #res = filetools.rename(torrent_file.replace('.torrent', '.pause').replace('.TORRENT', '.pause'), \ # filetools.basename(torrent_file), strict=True, silent=True) log("##### Progreso: %s, .torrent pausado: %s" % (str(porcent), video_file)) elif filetools.exists(torrent_file.replace('.torrent', '.reset')) or filetools.exists(torrent_file.replace('.TORRENT', '.reset')): torrent_reseted = True torrent_stop = True action = 'reset' item.downloadProgress = 0 res = filetools.remove(torrent_file.replace('.torrent', '.reset').replace('.TORRENT', '.reset'), silent=True) #res = filetools.rename(torrent_file.replace('.torrent', '.reset').replace('.TORRENT', '.reset'), \ # filetools.basename(torrent_file), strict=True, silent=True) log("##### Progreso: %s, .torrent reseteado: %s" % (str(porcent), video_file)) else: torrent_deleted = True torrent_stop = True action = 'delete' item.downloadProgress = 0 res = True log("##### Progreso: %s, .torrent borrado: %s" % (str(porcent), video_file)) if not res: log('ERROR borrando por -%s- el .torrent %s' % (action, filetools.listdir(filetools.dirname(torrent_file)))) if item.downloadProgress == 0 or torrent_stop: remove_files( 1, torrent_file, video_file, ses, h, ren_video_file, item ) bkg_user = False dp.close() return # -- Si hace 'checking' existe descarga ----------------- # -- 'download' Se usará para saber si hay datos - # -- descargados para el diálogo de 'remove_files' - if s.state == 1: download = 1 if (s.state == 5 or s.state == 4) and rar: # -- Borrar sesión para que libere los archivos y se pueda renombrar la carpeta ------- ses.pause() #video_file, rar, play_file = extract_files(video_file, save_path_videos, password, dp, item=item) video_file, rar, play_file, erase_path = torr.extract_files(video_file, \ save_path_videos, password, dp, item=item, torr_client='MCT') # ... extraemos el vídeo del RAR item.downloadFilename = play_file.replace(save_path_videos, '') item.downloadFilename = filetools.join(item.downloadFilename, video_file) item.downloadFilename = ':%s: %s' % ('MCT', item.downloadFilename) dp.close() erase_file_path = erase_path ren_video_file = erase_file_path extracted_rar = rar if not play_file: remove_files( download, torrent_file, erase_file_path, ses, h, ren_video_file, item ) return is_view = "Ok" save_path_videos = play_file xbmc.sleep(3000) # -- Player - play -------------------------------------- # -- Comprobar si se han completado las piezas para el - # -- inicio del vídeo - first_pieces = True #if not extracted_rar: _c = 0 for i in range( piece_set[0], piece_set[porcent4first_pieces] ): first_pieces &= h.have_piece(i) if h.have_piece(i): _c+= 1 _pieces_info = {'current': 0, 'continuous': "%s/%s" % (_c, porcent4first_pieces), \ 'continuous2': "", 'have': h.status().num_pieces, 'len': len(piece_set)} last_pieces = True if not allocate: _c = len(piece_set)-1; _cc = 0 for i in range(len(piece_set)-porcent4last_pieces, len(piece_set)): last_pieces &= h.have_piece(i) if h.have_piece(i): _c-= 1; _cc+=1 _pieces_info['continuous2'] = "[%s/%s] " % (_cc, porcent4last_pieces) if is_view != "Ok" and h.status().num_pieces >= BUFFER and not rar and not bkg_user \ or ((s.state == 5 or s.state == 4) and bkg_user): _pieces_info['continuous2'] = "" log("##### porcent [%.2f%%]" % (s.progress * 100)) dp.close() dp_cerrado = True if not bkg_user: is_view = "Ok" else: remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item ) return if is_view == "Ok": # -- Esperando a que termine otra reproducción -------------------------- while xbmc.Player().isPlaying(): xbmc.sleep(3000) # -- Player - Ver el vídeo -------------------------- playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO ) playlist.clear() ren_video_file = os.path.join( save_path_videos, video_file ) try: playlist.add( ren_video_file, xlistitem ) except: playlist.add( ren_video_file ) if xbmc_version < 17: player = play_video( xbmc.PLAYER_CORE_AUTO ) else: player = play_video() if subtitle: time.sleep(0.5) player.setSubtitles(item.subtitle) # Activamos los subtítulos player.play(playlist) # -- Contador de cancelaciones para la ventana de - # -- 'pause' automático - is_greater_num_pieces_canceled = 0 continuous_pieces = 0 porcent_time = 0.00 current_piece = 0 set_next_continuous_pieces = porcent4first_pieces # -- Impedir que kodi haga 'resume' a un archivo ---- # -- que se reprodujo con anterioridad y que se - # -- eliminó para impedir que intente la reprucción - # -- en una pieza que aún no se ha completado y se - # -- active 'pause' automático - not_resume = True # -- Bandera subTítulos _sub = False # -- Segundo bucle - Player - Control de eventos ---- bkg_auto = True log("##### PLAY %s" % (h.status().num_pieces)) if item: torr.mark_auto_as_watched(item) if ses_lt: h.set_download_limit(DOWNLOAD_LIMIT) h.set_upload_limit(UPLOAD_LIMIT) while player.isPlaying(): # -- Impedir que kodi haga 'resume' al inicio --- # -- de la descarga de un archivo conocido - if not_resume: player.seekTime(0) not_resume = False # -- Control 'pause' automático - continuous_pieces = count_completed_continuous_pieces(h, piece_set) if xbmc.Player().isPlaying() and not rar: # -- Porcentage del progreso del vídeo ------ # -- En kodi 18.x se debe controlar - # -- ZeroDivisionError: float division by - # -- zero - player_getTime = player.getTime() player_getTotalTime = player.getTotalTime() try: porcent_time = old_div(player_getTime, player_getTotalTime) * 100 except: porcent_time = 0 # -- Pieza que se está reproduciendo -------- # -- En kodi 18.x se debe controlar - # -- ZeroDivisionError: float division by - # -- zero - try: current_piece = int( old_div(porcent_time, 100) * len(piece_set) ) except: current_piece = 0 # -- Banderas de control -------------------- is_greater_num_pieces = (current_piece > continuous_pieces - num_pieces_to_resume) #is_greater_num_pieces_plus = (current_piece + porcent4first_pieces > continuous_pieces) is_greater_num_pieces_plus = (current_piece + BUFFER > continuous_pieces) #is_greater_num_pieces_finished = (current_piece + porcent4first_pieces >= len(piece_set)) is_greater_num_pieces_finished = (current_piece + BUFFER >= len(piece_set)) # -- Activa 'pause' automático -------------- if is_greater_num_pieces and not player.paused and not is_greater_num_pieces_finished: is_greater_num_pieces_pause = True player.pause() if continuous_pieces >= set_next_continuous_pieces: set_next_continuous_pieces = continuous_pieces + num_pieces_to_resume next_continuous_pieces = str(continuous_pieces - current_piece) + "/" + str(set_next_continuous_pieces - current_piece) _pieces_info = {'current': current_piece, 'continuous': next_continuous_pieces , 'continuous2': _pieces_info['continuous2'], 'have': h.status().num_pieces, 'len': len(piece_set)} # -- Cerrar el diálogo de progreso -------------- if player.resumed: dp.close() # -- Mostrar el diálogo de progreso ------------- if player.paused and dp_cerrado and not rar: # -- Crear diálogo si no existe ------------- log("##### PAUSED %s" % (h.status().num_pieces)) if not player.statusDialogoProgress: dp = xbmcgui.DialogProgressBG() dp.create(msg_header) dp_BG = True player.setDialogoProgress() # -- Diálogos de estado en el visionado ----- if not h.is_seed(): # -- Recuperar los datos del progreso --- message, porcent, msg_file, s, download = getProgress(h, video_file, _pf=_pieces_info) if dp_BG: dp.update(porcent, message, msg_file) else: dp.update(porcent, message + '\n' + msg_file + '\n' + ' ') else: if dp_BG: dp.update(100, "Descarga completa: ", video_file) else: dp.update(100, "Descarga completa: " + '\n' + video_file + '\n' + ' ') # -- Se canceló el progreso en el visionado - # -- Continuar - if not bkg_auto and dp.iscanceled(): dp.close() player.pause() # -- Se canceló el progreso en el visionado - # -- en la ventana de 'pause' automático. - # -- Parar si el contador llega a 3 - if not bkg_auto and dp.iscanceled() and is_greater_num_pieces_pause: is_greater_num_pieces_canceled+= 1 if is_greater_num_pieces_canceled == 3: player.stop() # -- Desactiva 'pause' automático y --------- # -- reinicia el contador de cancelaciones - if not is_greater_num_pieces_plus and is_greater_num_pieces_pause: dp.close() player.pause() is_greater_num_pieces_pause = False is_greater_num_pieces_canceled = 0 # -- El usuario cancelo el visionado -------- # -- Terminar - if player.ended: # -- Diálogo eliminar archivos ---------- remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item ) return xbmc.sleep(1000) # -- Kodi - Se cerró el visionado ----------------------- # -- Continuar | Terminar - if is_view == "Ok" and not xbmc.Player().isPlaying(): dp.close() if h.status().num_pieces < tot_piece_set: # -- Diálogo continuar o terminar --------------- # Preguntamos si el usuario quiere pasar a backgroung ok = xbmcgui.Dialog().yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)" + '\n' + "Selecciona NO para seguir descargando en segundo plano") else: ok = True # -- NO --------------------------------------------- if not ok: is_view=None bkg_user = True dp_cerrado = False dp = xbmcgui.DialogProgressBG() dp.create(msg_header) dp_BG = True else: # -- Terminar: ---------------------------------- # -- Comprobar si el vídeo pertenece a una ------ # -- lista de archivos - remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item ) if item.path.endswith('.json'): log("##### BORRANDO Archivo de CONTROL %s" % item.path) filetools.remove(filetools.join(config.get_setting("downloadlistpath"), item.path)) dp.close() return """ #_index, video_file, video_size, len_files = get_video_files_sizes( info ) if _index < 0 or len_files == 1: # -- Diálogo eliminar archivos -------------- #video_file = _video_file remove_files( download, torrent_file, video_file, ses, h, ren_video_file ) dp.close() return else: # -- Lista de archivos. Diálogo de opciones - piece_set = set_priority_pieces(h, _index, video_file, video_size, porcent4first_pieces, porcent4last_pieces, allocate) is_view=None dp = xbmcgui.DialogProgress() dp.create(msg_header) """ # -- Mostar progeso antes del visionado ----------------- if is_view != "Ok" : if dp_BG: dp.update(porcent, message, msg_file) else: dp.update(porcent, message + '\n' + msg_file + '\n' + ' ') # -- Se canceló el progreso antes del visionado --------- # -- Dar otra oportunidad en background o Terminar - if not bkg_user and dp_cerrado and dp.iscanceled(): dp.close() # Preguntamos si el usuario quiere pasar a backgroung dialog = xbmcgui.Dialog().yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)", "Seleccione NO para seguir descargando en segundo plano") if not dialog: bkg_user = True dp_cerrado = False dp = xbmcgui.DialogProgressBG() dp.create(msg_header) dp_BG = True if ses_lt: h.set_download_limit(DOWNLOAD_LIMIT) else: remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item ) if item.path.endswith('.json'): log("##### BORRANDO Archivo de CONTROL %s" % item.path) filetools.remove(filetools.join(config.get_setting("downloadlistpath"), item.path)) return # -- Comprobar si el vídeo pertenece a una lista de - # -- archivos - #_index, video_file, video_size, len_files = get_video_files_sizes( info ) if _index < 0 or len_files == 1: # -- Diálogo eliminar archivos ------------------ #video_file = _video_file remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item ) return else: # -- Lista de archivos. Diálogo de opciones ----- piece_set = set_priority_pieces(h, _index, video_file, video_size, porcent4first_pieces, porcent4last_pieces, allocate) is_view=None dp = xbmcgui.DialogProgress() dp.create(msg_header) # -- Kodi - Error? - No debería llegar aquí ----------------- if is_view == "Ok" and not xbmc.Player().isPlaying(): dp.close() # -- Diálogo eliminar archivos -------------------------- remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item ) return
def download_from_url(url, item): logger.info("pelisalacarta.channels.descargas download_from_url - Intentando descargar: %s" % (url)) if url.lower().endswith(".m3u8") or url.lower().startswith("rtmp"): save_server_statistics(item.server, 0, False) return {"downloadStatus": STATUS_CODES.error} # Obtenemos la ruta de descarga y el nombre del archivo download_path = filetools.dirname(filetools.join(config.get_setting("downloadpath"), item.downloadFilename)) file_name = filetools.basename(filetools.join(config.get_setting("downloadpath"), item.downloadFilename)) # Creamos la carpeta si no existe if not filetools.exists(download_path): filetools.mkdir(download_path) # Mostramos el progreso progreso = platformtools.dialog_progress("Descargas", "Iniciando descarga...") # Lanzamos la descarga d = Downloader(url, filetools.encode(download_path), filetools.encode(file_name)) d.start() # Monitorizamos la descarga hasta que se termine o se cancele while d.state == d.states.downloading and not progreso.iscanceled(): time.sleep(0.1) line1 = "%s" % (filetools.decode(d.filename)) line2 = "%.2f%% - %.2f %s de %.2f %s a %.2f %s/s (%d/%d)" % ( d.progress, d.downloaded[1], d.downloaded[2], d.size[1], d.size[2], d.speed[1], d.speed[2], d.connections[0], d.connections[1]) line3 = "Tiempo restante: %s" % (d.remaining_time) progreso.update(int(d.progress), line1, line2, line3) # Descarga detenida. Obtenemos el estado: # Se ha producido un error en la descarga if d.state == d.states.error: logger.info("pelisalacarta.channels.descargas download_video - Error al intentar descargar %s" % (url)) d.stop() progreso.close() status = STATUS_CODES.error # Aun está descargando (se ha hecho click en cancelar) elif d.state == d.states.downloading: logger.info("pelisalacarta.channels.descargas download_video - Descarga detenida") d.stop() progreso.close() status = STATUS_CODES.canceled # La descarga ha finalizado elif d.state == d.states.completed: logger.info("pelisalacarta.channels.descargas download_video - Descargado correctamente") progreso.close() status = STATUS_CODES.completed if item.downloadSize and item.downloadSize != d.size[0]: status = STATUS_CODES.error save_server_statistics(item.server, d.speed[0], d.state != d.states.error) if progreso.iscanceled(): status = STATUS_CODES.canceled dir = os.path.dirname(item.downloadFilename) file = filetools.join(dir, filetools.decode(d.filename)) if status == STATUS_CODES.completed: move_to_libray(item.clone(downloadFilename = file)) return {"downloadUrl": d.download_url, "downloadStatus": status, "downloadSize": d.size[0], "downloadProgress": d.progress, "downloadCompleted": d.downloaded[0], "downloadFilename": file}
def overwrite_tools(item): import videolibrary_service from core import videolibrarytools seleccion = platformtools.dialog_yesno(config.get_localized_string(60581), config.get_localized_string(60582), config.get_localized_string(60583)) if seleccion == 1: # tvshows heading = config.get_localized_string(60584) p_dialog = platformtools.dialog_progress_bg( config.get_localized_string(60585), heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk( videolibrarytools.TVSHOWS_PATH): show_list.extend( [filetools.join(path, f) for f in files if f == "tvshow.nfo"]) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = videolibrarytools.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) if not serie.active: # si la serie no esta activa descartar continue # Eliminamos la carpeta con la serie ... filetools.rmdirtree(path) # ... y la volvemos a añadir videolibrary_service.update(path, p_dialog, i, t, serie, 3) p_dialog.close() # movies heading = config.get_localized_string(60586) p_dialog2 = platformtools.dialog_progress_bg( config.get_localized_string(60585), heading) p_dialog2.update(0, '') movies_list = [] for path, folders, files in filetools.walk( videolibrarytools.MOVIES_PATH): movies_list.extend([ filetools.join(path, f) for f in files if f.endswith(".json") ]) logger.debug("movies_list %s" % movies_list) if movies_list: t = float(100) / len(movies_list) for i, movie_json in enumerate(movies_list): try: from core import jsontools path = filetools.dirname(movie_json) movie = Item().fromjson(filetools.read(movie_json)) # Eliminamos la carpeta con la pelicula ... filetools.rmdirtree(path) import math heading = config.get_localized_string(60587) p_dialog2.update( int(math.ceil((i + 1) * t)), heading, "%s: %s" % (movie.contentTitle, movie.channel.capitalize())) # ... y la volvemos a añadir videolibrarytools.save_movie(movie) except Exception, ex: logger.error("Error al crear de nuevo la película") template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) p_dialog2.close()
def set_content(content_type, silent=False): """ Procedimiento para auto-configurar la biblioteca de kodi con los valores por defecto @type content_type: str ('CINE' o 'SERIES') @param content_type: tipo de contenido para configurar, series o peliculas """ if config.is_xbmc(): continuar = True msg_text = "" librarypath = config.get_setting("librarypath") if content_type == 'CINE': if not xbmc.getCondVisibility( 'System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno( "The Movie Database", "TheMovieDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin( 'xbmc.installaddon(metadata.themoviedb.org)', True) logger.info( "Instalado el Scraper de películas de TheMovieDB") except: pass continuar = (install and xbmc.getCondVisibility( 'System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = "The Movie Database no instalado." else: # SERIES # Instalar The TVDB if not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno( "The TVDB", "The TVDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin( 'xbmc.installaddon(metadata.tvdb.com)', True) logger.info( "Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility( 'System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = "The TVDB no instalado." # Instalar TheMovieDB if continuar and not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno( "The Movie Database", "TheMovieDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org # 1º Probar desde el repositorio ... xbmc.executebuiltin( 'xbmc.installaddon(metadata.tvshows.themoviedb.org)', True) if not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)' ): # ...si no funciona descargar e instalar desde la web url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip" path_down = xbmc.translatePath( "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip" ) path_unzip = xbmc.translatePath( "special://home/addons/") header = ( "User-Agent", "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013" ) from core import downloadtools from core import ziptools downloadtools.downloadfile(url, path_down, continuar=True, headers=[header]) unzipper = ziptools.ziptools() unzipper.extract(path_down, path_unzip) xbmc.executebuiltin('UpdateLocalAddons') strSettings = '<settings>\n' \ ' <setting id="fanart" value="true" />\n' \ ' <setting id="keeporiginaltitle" value="false" />\n' \ ' <setting id="language" value="it" />\n' \ '</settings>' path_settings = xbmc.translatePath( "special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml" ) tv_themoviedb_addon_path = filetools.dirname( path_settings) if not filetools.exists(tv_themoviedb_addon_path): filetools.mkdir(tv_themoviedb_addon_path) if filetools.write(path_settings, strSettings): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = "The Movie Database non installato." idPath = 0 idParentPath = 0 strPath = "" if continuar: continuar = False # Buscamos el idPath sql = 'SELECT MAX(idPath) FROM path' nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idPath = records[0][0] + 1 sql_librarypath = librarypath if sql_librarypath.startswith("special://"): sql_librarypath = sql_librarypath.replace( '/profile/', '/%/').replace('/home/userdata/', '/%/') sep = '/' elif sql_librarypath.startswith("smb://"): sep = '/' else: sep = os.sep if not sql_librarypath.endswith(sep): sql_librarypath += sep # Buscamos el idParentPath sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_librarypath nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idParentPath = records[0][0] librarypath = records[0][1][:-1] continuar = True else: # No existe librarypath en la BD: la insertamos sql_librarypath = librarypath if not sql_librarypath.endswith(sep): sql_librarypath += sep sql = 'INSERT INTO path (idPath, strPath, scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \ '(%s, "%s", 0, 0, 0, 0)' % (idPath, sql_librarypath) nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True idParentPath = idPath idPath += 1 else: msg_text = "Omesso di impostare LibraryPath in BD" if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == 'CINE': strContent = 'movies' strScraper = 'metadata.themoviedb.org' scanRecursive = 2147483647 strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \ "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \ "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \ "<setting id='trailer' value='true' /></settings>" strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per i film ?" if not librarypath.endswith(sep): librarypath += sep strPath = librarypath + config.get_setting( "folder_movies") + sep else: strContent = 'tvshows' strScraper = 'metadata.tvdb.com' scanRecursive = 0 strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \ "<setting id='absolutenumber' value='false' />" \ "<setting id='dvdorder' value='false' />" \ "<setting id='fallback' value='true' />" \ "<setting id='fanart' value='true' />" \ "<setting id='language' value='it' /></settings>" strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per le serie ?" if not librarypath.endswith(sep): librarypath += sep strPath = librarypath + config.get_setting( "folder_tvshows") + sep logger.info("%s: %s" % (content_type, strPath)) # Comprobamos si ya existe strPath en la BD para evitar duplicados sql = 'SELECT idPath FROM path where strPath="%s"' % strPath nun_records, records = execute_sql_kodi(sql) sql = "" if nun_records == 0: # Insertamos el scraper sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \ 'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno( "The TVDB", strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = "Omesso impostare LibraryPath in BD" if not continuar: heading = "Biblioteca %s no configurada" % content_type elif content_type == 'SERIES' and not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = "Biblioteca %s configurata" % content_type msg_text = "Riavviare Kodi per attuare le modifiche." else: heading = "Biblioteca %s configurata" % content_type msg_text = "Libreria di Kodi configurata correttamente." platformtools.dialog_notification(heading, msg_text, icon=1, time=10000) logger.info("%s: %s" % (heading, msg_text))
def set_content(content_type, silent=False): """ Procedimiento para auto-configurar la biblioteca de kodi con los valores por defecto @type content_type: str ('CINE' o 'SERIES') @param content_type: tipo de contenido para configurar, series o peliculas """ if config.is_xbmc(): continuar = True msg_text = "" librarypath = config.get_setting("librarypath") if content_type == 'CINE': if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "TheMovieDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True) logger.info("Instalado el Scraper de películas de TheMovieDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = "The Movie Database no instalado." else: # SERIES # Instalar The TVDB if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno("The TVDB", "The TVDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True) logger.info("Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = "The TVDB no instalado." # Instalar TheMovieDB if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "TheMovieDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org # 1º Probar desde el repositorio ... xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True) if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): # ...si no funciona descargar e instalar desde la web url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip" path_down = xbmc.translatePath( "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip") path_unzip = xbmc.translatePath("special://home/addons/") header = ("User-Agent", "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013") from core import downloadtools from core import ziptools downloadtools.downloadfile(url, path_down, continuar=True, headers=[header]) unzipper = ziptools.ziptools() unzipper.extract(path_down, path_unzip) xbmc.executebuiltin('UpdateLocalAddons') strSettings = '<settings>\n' \ ' <setting id="fanart" value="true" />\n' \ ' <setting id="keeporiginaltitle" value="false" />\n' \ ' <setting id="language" value="it" />\n' \ '</settings>' path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml") tv_themoviedb_addon_path = filetools.dirname(path_settings) if not filetools.exists(tv_themoviedb_addon_path): filetools.mkdir(tv_themoviedb_addon_path) if filetools.write(path_settings,strSettings): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = "The Movie Database non installato." idPath = 0 idParentPath = 0 strPath = "" if continuar: continuar = False # Buscamos el idPath sql = 'SELECT MAX(idPath) FROM path' nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idPath = records[0][0] + 1 sql_librarypath = librarypath if sql_librarypath.startswith("special://"): sql_librarypath = sql_librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/') sep = '/' elif sql_librarypath.startswith("smb://"): sep = '/' else: sep = os.sep if not sql_librarypath.endswith(sep): sql_librarypath += sep # Buscamos el idParentPath sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_librarypath nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idParentPath = records[0][0] librarypath = records[0][1][:-1] continuar = True else: # No existe librarypath en la BD: la insertamos sql_librarypath = librarypath if not sql_librarypath.endswith(sep): sql_librarypath += sep sql = 'INSERT INTO path (idPath, strPath, scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \ '(%s, "%s", 0, 0, 0, 0)' % (idPath, sql_librarypath) nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True idParentPath = idPath idPath += 1 else: msg_text = "Omesso di impostare LibraryPath in BD" if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == 'CINE': strContent = 'movies' strScraper = 'metadata.themoviedb.org' scanRecursive = 2147483647 strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \ "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \ "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \ "<setting id='trailer' value='true' /></settings>" strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per i film ?" if not librarypath.endswith(sep): librarypath += sep strPath = librarypath + config.get_setting("folder_movies") + sep else: strContent = 'tvshows' strScraper = 'metadata.tvdb.com' scanRecursive = 0 strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \ "<setting id='absolutenumber' value='false' />" \ "<setting id='dvdorder' value='false' />" \ "<setting id='fallback' value='true' />" \ "<setting id='fanart' value='true' />" \ "<setting id='language' value='it' /></settings>" strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per le serie ?" if not librarypath.endswith(sep): librarypath += sep strPath = librarypath + config.get_setting("folder_tvshows") + sep logger.info("%s: %s" % (content_type, strPath)) # Comprobamos si ya existe strPath en la BD para evitar duplicados sql = 'SELECT idPath FROM path where strPath="%s"' % strPath nun_records, records = execute_sql_kodi(sql) sql = "" if nun_records == 0: # Insertamos el scraper sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \ 'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno("The TVDB", strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = "Omesso impostare LibraryPath in BD" if not continuar: heading = "Biblioteca %s no configurada" % content_type elif content_type == 'SERIES' and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = "Biblioteca %s configurata" % content_type msg_text = "Riavviare Kodi per attuare le modifiche." else: heading = "Biblioteca %s configurata" % content_type msg_text = "Libreria di Kodi configurata correttamente." platformtools.dialog_notification(heading, msg_text, icon=1, time=10000) logger.info("%s: %s" % (heading,msg_text))
def install_alfa_assistant(update=False, remote='', verbose=False): if update: logger.info('update=%s' % str(update)) # Si ya está instalada, devolvemos el control app_name = 'com.alfa.alfamobileassistant' if not verbose: verbose = config.get_setting('addon_update_message') # Verbose en la actualización/instalación assistant_flag_install = config.get_setting('assistant_flag_install', default=True) addonid = 'alfa-mobile-assistant' download = addonid + '.apk' package = addonid + '.apk' version = addonid + '.version' forced_menu = False respuesta = False alfa_s = True addons_path = config.get_runtime_path() if filetools.exists(filetools.join(addons_path, 'channels', 'custom.py')): alfa_s = False if not remote: ANDROID_STORAGE = os.getenv('ANDROID_STORAGE') if not ANDROID_STORAGE: ANDROID_STORAGE = '/storage' else: # Remote es la url de un servidor FTP o SMB activo que apunta a la ruta "/storage" del dispositivo Android ANDROID_STORAGE = remote if ANDROID_STORAGE.endswith('/'): ANDROID_STORAGE = ANDROID_STORAGE[:-1] apk_files = '%s/%s/%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Android', 'data', app_name) if ASSISTANT_MODE == 'este' and not filetools.exists(filetools.dirname(apk_files)): apk_files_alt = scrapertools.find_single_match(os.getenv('HOME'), '(.*?)\/\w*.\w*.\w*\/files') logger.info('HOME: ' + apk_files_alt) if apk_files_alt and filetools.exists(apk_files_alt): apk_files = '%s/%s' % (apk_files_alt, app_name) version_path = filetools.join(config.get_data_path(), version) version_act = filetools.read(version_path, silent=True) if not version_act: version_act = '0.0.0' # Averiguamos si es instalacción, update, o forzado desde el Menú de Ajustes if not update and ASSISTANT_MODE == 'este' and filetools.exists(apk_files): return version_act, app_name if ASSISTANT_MODE == 'este' and not update: check_permissions_alfa_assistant() # activamos la app por si no se ha inicializado time.sleep(1) if filetools.exists(apk_files): return version_act, app_name # Mirarmos si la app está activa y obtenemos el nº de versión version_dict = get_generic_call('getWebViewInfo', timeout=2-EXTRA_TIMEOUT, alfa_s=True) if isinstance(version_dict, dict): version_app = version_dict.get('assistantVersion', '') try: android_version = int(scrapertools.find_single_match(version_dict.get('userAgent', ''), r"Android\s*(\d+)")) except: android_version = 8 else: version_app = version_dict android_version = 8 if version_app and not update: return version_app, app_name if version_app: app_active = True else: app_active = False if ASSISTANT_MODE == "este": execute_in_alfa_assistant_with_cmd('open') # activamos la app por si no se ha inicializado time.sleep(5) version_dict = get_generic_call('getWebViewInfo', timeout=2-EXTRA_TIMEOUT, alfa_s=True) if isinstance(version_dict, dict): version_app = version_dict.get('assistantVersion', '') try: android_version = int(scrapertools.find_single_match(version_dict.get('userAgent', ''), r"Android\s*(\d+)")) except: android_version = 8 else: version_app = version_dict android_version = 8 version_actual = filetools.read(version_path, silent=True) if not version_actual and version_app: version_actual = version_app filetools.write(version_path, version_actual, mode='wb', silent=True) elif not version_actual: version_actual = '0.0.0' if ASSISTANT_MODE != 'este': if not version_app: if verbose or (update and not isinstance(update, bool)): platformtools.dialog_notification("Active Alfa Assistant", "o Instale manualmente desde [COLOR yellow]https://bit.ly/2Zwpfzq[/COLOR]") logger.info("Active Alfa Assistant, o Instale manualmente desde [COLOR yellow]https://bit.ly/2Zwpfzq[/COLOR]", force=True) config.set_setting('assistant_flag_install', False) return version_app, app_name else: config.set_setting('assistant_flag_install', True) if not update: return version_app, app_name elif not update and not assistant_flag_install and not filetools.exists(apk_files): logger.info('NO está instalada. El usuario no quiere instalaciñon automática: %s' % app_name) return False, app_name elif update and isinstance(update, bool) and not filetools.exists(apk_files): logger.info('NO está instalada. No se va a actualizar: %s' % app_name) return False, app_name elif update and not isinstance(update, bool) and not filetools.exists(apk_files): logger.info('NO está instalada. Viene del Menú y se va a instalar: %s' % app_name) update = False forced_menu = True elif not remote and not xbmc.getCondVisibility("system.platform.android"): logger.info('El sistema local no es Android: %s' % app_name) return False, app_name logger.info('assistant_mode=%s, update=%s, forced_menu=%s, assistant_flag_install=%s, version_actual=%s, version_app=%s, android=%s, app_active=%s' \ % (ASSISTANT_MODE, str(update), str(forced_menu), str(assistant_flag_install), version_actual, \ version_app, str(android_version), str(app_active))) # Si no está instalada, o se quiere actualizar, empezamos el proceso alfa_assistant_pwd = '' assistant_urls = ['https://github.com/alfa-addon/alfa-repo/raw/master/downloads/assistant/%s' % version, \ 'https://bitbucket.org/alfa_addon/alfa-repo/raw/master/downloads/assistant/%s' % version] apk_updated = filetools.join(addons_path, 'tools') apk_path = filetools.join(apk_updated, download) apk_apk = filetools.join(apk_updated, package) upk_install_path = filetools.join('special://xbmc/', 'files').replace('/cache/apk/assets', '') if not remote: apk_install = filetools.join(ANDROID_STORAGE, 'emulated', '0', 'Download') apk_install_SD = filetools.join(apk_install, package) else: apk_install = '%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Download') apk_install_SD = '%s/%s' % (apk_install, package) if not update and not remote and not forced_menu: # Probamos a iniciar por si se ha instalado manualmente y no se ha iniciado la estrucutra de archivos check_permissions_alfa_assistant() try: command = ['pm', 'list', 'packages'] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) PM_LIST, error_cmd = p.communicate() if PY3 and isinstance(label_a, bytes): PM_LIST = PM_LIST.decode() if app_name in PM_LIST: logger.info('Ya instalada. Volvemos: %s' % app_name) return version_actual, app_name except: logger.error(traceback.format_exc(1)) if not update and not forced_menu and not platformtools.dialog_yesno("Instalación Alfa Assistant", \ "¿Desea instalar la App [COLOR yellow][B]%s[/B][/COLOR]\n" % app_name + " como ayuda para acceder a ciertos canales y servidores?"): config.set_setting('assistant_flag_install', False) return respuesta, app_name elif update and not isinstance(update, bool): platformtools.dialog_notification("Instalación Alfa Assistant", "Comienza la actualización") elif forced_menu: platformtools.dialog_notification("Instalación Alfa Assistant", "Comienza la instalación") # Comprobamos si el dispositivo está rooteado is_rooted = config.is_rooted(silent=True) # ¡OJO! puede pedir permisos root en algunos dispositivos if is_rooted == 'rooted' and ASSISTANT_MODE == 'este': # El dispositivo esta rooteado? update_install = 'py' # Se actualiza desde esta función else: update_install = 'app' # Se actualiza desde la app cmd = 'update' # Comando de la app para auto actualizarse dataURI = 'Version:%s' # Versión a actualizar # Comprobamos si hay acceso a Github o BitBucket for assistant_rar in assistant_urls: response = httptools.downloadpage(assistant_rar, timeout=5, ignore_response_code=True, alfa_s=alfa_s, json_to_utf8=False) if response.sucess: break # Descargamos el archivo de version. Si hay error avisamos, pero continuamos if not response.sucess: if update and isinstance(update, bool): logger.error("Error en la descarga de control de versión. No se puede actualizar: %s" % str(response.code)) return respuesta, app_name platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la descarga de control de versión. Seguimos") logger.error("Error en la descarga de control de versión. Seguimos...: %s" % str(response.code)) #Si es una actualización programada, comprobamos las versiones de Github y de lo instalado if update and isinstance(update, bool): if version_actual != response.data: if version_app: version_actual = version_app filetools.write(version_path, version_actual, mode='wb', silent=True) if version_actual == response.data: if verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Ya está actualizado a version %s" % response.data) logger.info("Alfa Assistant ya actualizado a versión: %s" % response.data) if not app_active and ASSISTANT_MODE == "este": execute_in_alfa_assistant_with_cmd('quit') # desactivamos la app si no estaba iniciada return version_actual, app_name # Guardamos archivo de versión if remote: version_path = '%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Android', 'data', 'org.xbmc.kodi', 'files', '.kodi', 'addons', 'plugin.video.alfa', 'tools', version) if not filetools.exists(filetools.dirname(version_path)): logger.error("Ruta a carpeta remota de versión no es estándar: %s" % version_path) version_path = '' version_old = version_actual version_actual = response.data if version_path: res = filetools.write(version_path, response.data, mode='wb', silent=True) if not res: if not update: platformtools.dialog_notification("Instalación Alfa Assistant", \ "Error en la escritura de control de versión. Seguimos...") logger.error("Error en la escritura de control de versión. Seguimos...: %s" % assistant_rar) # Descargamos y guardamos el .APK assistant_rar = assistant_rar.replace(version, download) # Sustituir en la url la versión por el apk res = False if not update: platformtools.dialog_notification("Instalación Alfa Assistant", "Descargando APK") logger.info('Descargando de_ %s' % assistant_rar) response = httptools.downloadpage(assistant_rar, timeout=5, ignore_response_code=True, alfa_s=alfa_s, json_to_utf8=False) if not response.sucess: if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la descarga del .apk") response.data = '' logger.error("Error en la descarga del .apk: %s" % str(response.code)) else: # Guardamos archivo descargado de APK res = filetools.write(apk_path, response.data, mode='wb', silent=True) if not res: if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la escritura del APK") logger.error("Error en la escritura del APK: %s" % apk_path) else: if '.rar' in download: # Empezando la extracción del .rar del APK try: import rarfile archive = rarfile.RarFile(apk_path) if alfa_assistant_pwd: archive.setpassword(alfa_assistant_pwd) archive.extractall(apk_updated) except: logger.error(traceback.format_exc(1)) elif '.zip' in download: # Empezando la extracción del .rar del APK try: import ziptools archive = ziptools.ziptools() #if alfa_assistant_pwd: archive.setpassword(alfa_assistant_pwd) # No hay password en .zip archive.extract(filetools.basename(apk_updated), filetools.dirname(apk_updated)) except: xbmc.executebuiltin('Extract("%s","%s")' % (filetools.basename(apk_updated), filetools.dirname(apk_updated))) time.sleep(1) # Verificado si está el APK, y si está y es LOCAL lo instalamos if ASSISTANT_MODE == "este": res = filetools.copy(apk_apk, apk_install_SD, silent=True) if not res or not filetools.exists(apk_install_SD): if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error de Extracción o Copia %s" % package) logger.error("Error de Extracción o copia %s" % package) # Si está rooteado se instala/actualiza directamente elif update_install == 'py' and res and filetools.exists(apk_install_SD): # Instalamos: nueva o actualización. if not update: platformtools.dialog_notification("Instalación Alfa Assistant", "Installando %s" % package) logger.info("Installing %s" % package) # Instalación Remota if remote: filetools.remove(apk_apk, silent=True) platformtools.dialog_notification("Alfa Assistant: Descarga Remota terminada", "Instale manualmente desde: %s" % apk_install_SD) logger.info("Alfa Assistant: Descarga Remota terminada. Instale manualmente desde: %s" % apk_install_SD) return version_actual, app_name # Instalación Local if not filetools.exists(upk_install_path): filetools.mkdir(upk_install_path) upk_install_path = filetools.join(upk_install_path, package) res = filetools.copy(apk_install_SD, upk_install_path, ch_mod='777') # Copiamos APK a la partición del Sistema, y cambiamos permisos if not res: if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error de Copia %s" % package) logger.error(str(filetools.listdir(apk_install))) logger.error(filetools.file_info(filetools.dirname(upk_install_path))) logger.error(str(filetools.listdir(filetools.dirname(upk_install_path), file_inf=True))) else: # Intenta la instalación vía ROOT y si no funciona como NO ROOT # Marcamos la opción de instalación, -r si es actualización, -g (todos los permisos granted) si es instalación if filetools.exists(apk_files): pm_opt = '-r' else: pm_opt = '-g' # Listamos todas las opciones de comandos, según las variantes de Android command_list = [ ['adb', 'install', '%s' % upk_install_path], ['su', '-c', 'pm install %s %s' % (pm_opt, upk_install_path)], ['su', '-c', 'pm', 'install', pm_opt, '%s' % upk_install_path], ['su', '-0', 'pm install %s %s' % (pm_opt, upk_install_path)], ['su', '-0', 'pm', 'install', pm_opt, '%s' % upk_install_path] ] for command in command_list: try: logger.info(command, force=True) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() if error_cmd: if error_cmd.startswith('su:'): continue if update: ver_upd = get_generic_call('ping', timeout=2-EXTRA_TIMEOUT, alfa_s=True) if not ver_upd: execute_in_alfa_assistant_with_cmd('open') # activamos la app por si no se ha inicializado time.sleep(5) ver_upd = get_generic_call('ping', timeout=2-EXTRA_TIMEOUT, alfa_s=True) execute_in_alfa_assistant_with_cmd('quit') if ver_upd == version_actual: logger.debug(str(error_cmd), force=True) error_cmd = '' else: check_permissions_alfa_assistant() time.sleep(1) if filetools.exists(apk_files): logger.debug(str(error_cmd), force=True) error_cmd = '' if error_cmd: logger.error(str(error_cmd)) else: respuesta = version_actual break else: respuesta = version_actual break except Exception as e: if not PY3: e = unicode(str(e), "utf8", errors="replace").encode("utf8") logger.error('Command ERROR: %s, %s' % (str(command), str(e))) continue # Ùltimo resorte: instalación manual desde GitHub o actualización desde la app if not respuesta and update: # Si hay que actualizar se verifica el vehículo de instalación logger.info("Instalación Alfa Assistant. Actualización desde la app de %s a %s" % (version_old, version_actual)) version_mod = version_actual if not isinstance(update, bool): version_mod = '9.9.999' # Intenta forzar la actualización si viene desde el Menú if ASSISTANT_MODE == "este": if android_version >= 10: app_active = False respuesta = execute_in_alfa_assistant_with_cmd(cmd, dataURI=dataURI % version_mod) else: if not app_active: execute_in_alfa_assistant_with_cmd('openAndQuit') # activamos la app por si no se ha inicializado time.sleep(5) app_active = False respuesta = get_generic_call(cmd, version=version_mod, alfa_s=alfa_s) else: if app_active: respuesta = get_generic_call(cmd, version=version_mod, alfa_s=alfa_s) if not respuesta and ASSISTANT_MODE != "este": if verbose or not isinstance(update, bool): platformtools.dialog_notification("Instalación Alfa Assistant", "Intente la actualización manualmente %s" % version_actual) logger.info("Instalación Alfa Assistant. Intente la actualización manualmente %s" % version_actual) return False, app_name elif not respuesta: # Update local #respuesta = execute_in_alfa_assistant_with_cmd(cmd, dataURI=dataURI % version_mod) if not respuesta: if verbose or not isinstance(update, bool): platformtools.dialog_notification("Instalación Alfa Assistant", "Actualización en error %s. REINTENTANDO" % version_actual) logger.info("Instalación Alfa Assistant. Actualización en error %s. REINTENTANDO" % version_actual) else: respuesta = version_actual if not respuesta: config.set_setting('assistant_flag_install', False) # No vuelve a intentar la instalación try: #xbmc.executebuiltin('StartAndroidActivity("","android.intent.action.VIEW","application/vnd.android.package-archive","file:%s")' % apk_install_SD) if ASSISTANT_MODE == "este": from lib import generictools assistant_rar = assistant_rar.replace('/raw/', '/tree/') # Apuntar a la web de descargas browser, res = generictools.call_browser(assistant_rar, lookup=True) if browser: filetools.remove(apk_install_SD, silent=True) platformtools.dialog_ok("Alfa Assistant: Instale desde [COLOR yellow]%s[/COLOR]" % browser.capitalize(), "O Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD) logger.info('Browser: %s, Ruta: %s' % (browser.capitalize(), apk_install_SD)) time.sleep(5) browser, res = generictools.call_browser(assistant_rar, dataType='application/vnd.android.package-archive') filetools.remove(apk_path, silent=True) filetools.remove(upk_install_path, silent=True) else: logger.error('Error de Instalación: NO Browser, Ruta: %s' % apk_install_SD) raise else: logger.error('Error de Instalación: no se puede instalar en remoto: %s' % ASSISTANT_SERVER) raise except: if ASSISTANT_MODE == "este": platformtools.dialog_ok("Alfa Assistant: Error", "Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD) logger.error("Alfa Assistant: Error. Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD) filetools.remove(apk_path, silent=True) filetools.remove(upk_install_path, silent=True) else: platformtools.dialog_ok("Alfa Assistant: Error", "Copie a Android manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_apk) logger.error("Alfa Assistant: Error. Copie a Android manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_apk) logger.error(traceback.format_exc(1)) if respuesta: if update: if verbose or not isinstance(update, bool): platformtools.dialog_notification("Alfa Assistant", \ "Actualización con exito: %s" % respuesta) logger.info("Actualización terminada con éxito: %s" % respuesta) else: platformtools.dialog_notification("Alfa Assistant", "Instalación con exito: %s" % respuesta) logger.info("Instalación terminada con éxito: %s" % respuesta) filetools.remove(apk_path, silent=True) filetools.remove(apk_install_SD, silent=True) filetools.remove(upk_install_path, silent=True) if not update and not forced_menu: time.sleep(1) check_permissions_alfa_assistant() time.sleep(1) if app_active and ASSISTANT_MODE == "este": execute_in_alfa_assistant_with_cmd('open') # re-activamos la app para dejarla como estaba return respuesta, app_name
def check_for_update(overwrite=True): logger.info("Actualizando series...") p_dialog = None serie_actualizada = False update_when_finished = False hoy = datetime.date.today() try: if config.get_setting("updatelibrary", "biblioteca") != 0 or overwrite: config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "biblioteca") heading = 'Actualizando biblioteca....' p_dialog = platformtools.dialog_progress_bg('pelisalacarta', heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk(library.TVSHOWS_PATH): show_list.extend([filetools.join(path, f) for f in files if f == "tvshow.nfo"]) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = library.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) logger.info("serie=" + serie.contentSerieName) p_dialog.update(int(math.ceil((i+1) * t)), heading, serie.contentSerieName) interval = int(serie.active) # Podria ser del tipo bool if not serie.active: # si la serie no esta activa descartar continue # obtenemos las fecha de actualizacion y de la proxima programada para esta serie update_next = serie.update_next if update_next: y, m, d = update_next.split('-') update_next = datetime.date(int(y), int(m), int(d)) else: update_next = hoy update_last = serie.update_last if update_last: y, m, d = update_last.split('-') update_last = datetime.date(int(y), int(m), int(d)) else: update_last = hoy # si la serie esta activa ... if overwrite or config.get_setting("updatetvshows_interval", "biblioteca") == 0: # ... forzar actualizacion independientemente del intervalo serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) elif interval == 1 and update_next <= hoy: # ...actualizacion diaria serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada and update_last <= hoy - datetime.timedelta(days=7): # si hace una semana q no se actualiza, pasar el intervalo a semanal interval = 7 update_next = hoy + datetime.timedelta(days=interval) elif interval == 7 and update_next <= hoy: # ...actualizacion semanal serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: if update_last <= hoy - datetime.timedelta(days=14): # si hace 2 semanas q no se actualiza, pasar el intervalo a mensual interval = 30 update_next += datetime.timedelta(days=interval) elif interval == 30 and update_next <= hoy: # ...actualizacion mensual serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next += datetime.timedelta(days=interval) if interval != int(serie.active) or update_next.strftime('%Y-%m-%d') != serie.update_next: serie.active = interval serie.update_next = update_next.strftime('%Y-%m-%d') serie.channel = "biblioteca" serie.action = "get_temporadas" filetools.write(tvshow_file, head_nfo + serie.tojson()) if serie_actualizada: if config.get_setting("search_new_content", "biblioteca") == 0: # Actualizamos la biblioteca de Kodi: Buscar contenido en la carpeta de la serie if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.update(folder=filetools.basename(path)) else: update_when_finished = True if config.get_setting("search_new_content", "biblioteca") == 1 and update_when_finished: # Actualizamos la biblioteca de Kodi: Buscar contenido en todas las series if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.update() p_dialog.close() else: logger.info("No actualiza la biblioteca, está desactivado en la configuración de pelisalacarta") except Exception as ex: logger.error("Se ha producido un error al actualizar las series") template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) if p_dialog: p_dialog.close()
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 = 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_canales.keys(): list_canales[nom_canal] = filetools.join(path_dir, fd) num_canales = len(list_canales) if 'downloads' in list_canales: json_path = list_canales['downloads'] item_json = Item().fromjson(filetools.read(json_path)) ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial try: if item_json: item_json, it, overwrite = generictools.redirect_clone_newpct1( item_json) except: logger.error(traceback.format_exc()) item_json.contentChannel = "local" # Soporte para rutas relativas en descargas if filetools.is_relative(item_json.url): item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH, item_json.url) del list_canales['downloads'] # Comprobar q el video no haya sido borrado if filetools.exists(item_json.url): item_local = item_json.clone(action='play') itemlist.append(item_local) else: num_canales -= 1 filtro_canal = '' if num_canales > 1 and config.get_setting("ask_channel", "videolibrary"): opciones = [ config.get_localized_string(70089) % k.capitalize() for k in list_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: if item_json: item_json, it, overwrite = generictools.redirect_clone_newpct1( item_json) except: logger.error(traceback.format_exc()) list_servers = [] try: # FILTERTOOLS # si el canal tiene filtro se le pasa el nombre que tiene guardado para que filtre correctamente. if "list_language" in item_json: # si se viene desde la videoteca del addon if "library_filter_show" in item: item_json.show = item.library_filter_show.get( nom_canal, "") # Ejecutamos find_videos, del canal o común item_json.contentChannel = 'videolibrary' if hasattr(channel, 'findvideos'): from core import servertools if item_json.videolibray_emergency_urls: del item_json.videolibray_emergency_urls list_servers = getattr(channel, 'findvideos')(item_json) list_servers = servertools.filter_servers(list_servers) elif item_json.action == 'play': from platformcode import platformtools autoplay.set_status(True) item_json.contentChannel = item_json.channel item_json.channel = "videolibrary" platformtools.play_video(item_json) return '' else: from core import servertools list_servers = servertools.find_video_items(item_json) except Exception, 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 check_for_update(overwrite=True): logger.info("Actualizando series...") p_dialog = None serie_actualizada = False update_when_finished = False hoy = datetime.date.today() estado_verify_playcount_series = False try: if config.get_setting("update", "videolibrary") != 0 or overwrite: config.set_setting("updatelibrary_last_check", hoy.strftime('%Y-%m-%d'), "videolibrary") heading = config.get_localized_string(60389) p_dialog = platformtools.dialog_progress_bg( config.get_localized_string(20000), heading) p_dialog.update(0, '') show_list = [] for path, folders, files in filetools.walk( videolibrarytools.TVSHOWS_PATH): show_list.extend([ filetools.join(path, f) for f in files if f == "tvshow.nfo" ]) if show_list: t = float(100) / len(show_list) for i, tvshow_file in enumerate(show_list): head_nfo, serie = videolibrarytools.read_nfo(tvshow_file) path = filetools.dirname(tvshow_file) logger.info("serie=" + serie.contentSerieName) p_dialog.update(int(math.ceil((i + 1) * t)), heading, serie.contentSerieName) #Verificamos el estado del serie.library_playcounts de la Serie por si está incompleto try: estado = False #Si no hemos hecho la verificación o no tiene playcount, entramos estado = config.get_setting("verify_playcount", "videolibrary") if not estado or estado == False or not serie.library_playcounts: #Si no se ha pasado antes, lo hacemos ahora serie, estado = videolibrary.verify_playcount_series( serie, path ) #También se pasa si falta un PlayCount por completo except: logger.error(traceback.format_exc()) else: if estado: #Si ha tenido éxito la actualización... estado_verify_playcount_series = True #... se marca para cambiar la opción de la Videoteca interval = int(serie.active) # Podria ser del tipo bool if not serie.active: # si la serie no esta activa descartar if not overwrite: #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa, aunque la serie esté desactivada try: if config.is_xbmc(): #Si es Kodi, lo hacemos from platformcode import xbmc_videolibrary xbmc_videolibrary.mark_content_as_watched_on_alfa( path + '/tvshow.nfo') except: logger.error(traceback.format_exc()) continue # obtenemos las fecha de actualizacion y de la proxima programada para esta serie update_next = serie.update_next if update_next: y, m, d = update_next.split('-') update_next = datetime.date(int(y), int(m), int(d)) else: update_next = hoy update_last = serie.update_last if update_last: y, m, d = update_last.split('-') update_last = datetime.date(int(y), int(m), int(d)) else: update_last = hoy # si la serie esta activa ... if overwrite or config.get_setting("updatetvshows_interval", "videolibrary") == 0: # ... forzar actualizacion independientemente del intervalo serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next = hoy + datetime.timedelta(days=interval) elif interval == 1 and update_next <= hoy: # ...actualizacion diaria serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada and update_last <= hoy - datetime.timedelta( days=7): # si hace una semana q no se actualiza, pasar el intervalo a semanal interval = 7 update_next = hoy + datetime.timedelta(days=interval) elif interval == 7 and update_next <= hoy: # ...actualizacion semanal serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: if update_last <= hoy - datetime.timedelta(days=14): # si hace 2 semanas q no se actualiza, pasar el intervalo a mensual interval = 30 update_next += datetime.timedelta(days=interval) elif interval == 30 and update_next <= hoy: # ...actualizacion mensual serie_actualizada = update(path, p_dialog, i, t, serie, overwrite) if not serie_actualizada: update_next += datetime.timedelta(days=interval) if serie_actualizada: update_last = hoy update_next = hoy + datetime.timedelta(days=interval) head_nfo, serie = videolibrarytools.read_nfo( tvshow_file) #Vuelve a leer el.nfo, que ha sido modificado if interval != int(serie.active) or update_next.strftime( '%Y-%m-%d' ) != serie.update_next or update_last.strftime( '%Y-%m-%d') != serie.update_last: serie.update_last = update_last.strftime('%Y-%m-%d') if update_next > hoy: serie.update_next = update_next.strftime('%Y-%m-%d') serie.active = interval serie.channel = "videolibrary" serie.action = "get_seasons" filetools.write(tvshow_file, head_nfo + serie.tojson()) if serie_actualizada: if config.get_setting("search_new_content", "videolibrary") == 0: # Actualizamos la videoteca de Kodi: Buscar contenido en la carpeta de la serie if config.is_xbmc(): from platformcode import xbmc_videolibrary xbmc_videolibrary.update( folder=filetools.basename(path)) else: update_when_finished = True if estado_verify_playcount_series: #Si se ha cambiado algún playcount, ... estado = config.set_setting( "verify_playcount", True, "videolibrary" ) #... actualizamos la opción de Videolibrary if config.get_setting( "search_new_content", "videolibrary") == 1 and update_when_finished: # Actualizamos la videoteca de Kodi: Buscar contenido en todas las series if config.is_xbmc(): from platformcode import xbmc_videolibrary xbmc_videolibrary.update() p_dialog.close() else: logger.info( "No actualiza la videoteca, está desactivado en la configuración de alfa" ) except Exception, ex: logger.error("Se ha producido un error al actualizar las series") template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) if p_dialog: p_dialog.close()
def establecer_contenido(content_type, silent=False): if config.is_xbmc(): continuar = False msg_text = "Cartella Libreria personalizzata" librarypath = config.get_setting("librarypath") if librarypath == "": continuar = True if content_type == FOLDER_MOVIES: if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "TheMovieDB. non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True) logger.info("Instalado el Scraper de películas de TheMovieDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = "The Movie Database non installato." else: # SERIES # Instalar The TVDB if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno("The TVDB", "The TVDB non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True) logger.info("Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = "The TVDB non installato." # Instalar TheMovieDB if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "TheMovieDB non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org # 1º Probar desde el repositorio ... xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True) if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): # ...si no funciona descargar e instalar desde la web url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip" path_down = xbmc.translatePath( "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip") path_unzip = xbmc.translatePath("special://home/addons/") header = ("User-Agent", "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013") from core import downloadtools from core import ziptools downloadtools.downloadfile(url, path_down, continuar=True, headers=[header]) unzipper = ziptools.ziptools() unzipper.extract(path_down, path_unzip) xbmc.executebuiltin('xbmc.UpdateLocalAddons') strSettings = '<settings>\n' \ ' <setting id="fanart" value="true" />\n' \ ' <setting id="keeporiginaltitle" value="false" />\n' \ ' <setting id="language" value="it" />\n' \ '</settings>' path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml") tv_themoviedb_addon_path = filetools.dirname(path_settings) if not filetools.exists(tv_themoviedb_addon_path): filetools.mkdir(tv_themoviedb_addon_path) if filetools.write(path_settings,strSettings): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = "The Movie Database non installato." idPath = 0 idParentPath = 0 strPath = "" if continuar: continuar = False librarypath = "special://home/userdata/addon_data/plugin.video." + config.PLUGIN_NAME + "/library/" # Buscamos el idPath sql = 'SELECT MAX(idPath) FROM path' nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idPath = records[0][0] + 1 # Buscamos el idParentPath sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % \ librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/') nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idParentPath = records[0][0] librarypath = records[0][1] continuar = True else: # No existe librarypath en la BD: la insertamos sql = 'INSERT INTO path (idPath, strPath, scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \ '(%s, "%s", 0, 0, 0, 0)' % (idPath, librarypath) nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True idParentPath = idPath idPath += 1 else: msg_text = "Impossibile impostare librarypath in BD" if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == FOLDER_MOVIES: strContent = 'movies' strScraper = 'metadata.themoviedb.org' scanRecursive = 2147483647 strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \ "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \ "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \ "<setting id='trailer' value='true' /></settings>" strActualizar = "Configurare lo scraper per i film in italiano?" else: strContent = 'tvshows' strScraper = 'metadata.tvdb.com' scanRecursive = 0 strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \ "<setting id='absolutenumber' value='false' />" \ "<setting id='dvdorder' value='false' />" \ "<setting id='fallback' value='true' />" \ "<setting id='fanart' value='true' />" \ "<setting id='language' value='it' /></settings>" strActualizar = "Configurare lo scraper per le serie in italiano?" # Fijamos strPath strPath = librarypath + content_type + "/" logger.info("%s: %s" % (content_type, strPath)) # Comprobamos si ya existe strPath en la BD para evitar duplicados sql = 'SELECT idPath FROM path where strPath="%s"' % strPath nun_records, records = execute_sql_kodi(sql) sql = "" if nun_records == 0: # Insertamos el scraper sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \ 'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno("The TVDB", strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = "Error al configurar el scraper en la BD." if not continuar: heading = "Libreria non %s configurata" % content_type #msg_text = "Assicurarsi di aver installato l'add-on The Movie Database" elif content_type == FOLDER_TVSHOWS and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = "Libreria %s configurata" % content_type msg_text = "Kodi deve essere riavviato affinché le modifiche abbiano effetto." else: heading = "Libreria %s configurata" % content_type msg_text = "Complimenti la libreria di Kodi è stata configurata correttamente." platformtools.dialog_notification(heading, msg_text, icon=1, time=10000) logger.info("%s: %s" % (heading,msg_text))