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 update_external_addon(addon_name): logger.info(addon_name) try: #Verificamos que el addon está instalado if xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % addon_name): #Path de actualizaciones de Alfa alfa_addon_updates_mig = filetools.join(config.get_runtime_path(), "lib") alfa_addon_updates = filetools.join(alfa_addon_updates_mig, addon_name) #Path de destino en addon externo __settings__ = xbmcaddon.Addon(id="plugin.video." + addon_name) if addon_name.lower() in ['quasar', 'elementum']: addon_path_root = xbmc.translatePath(__settings__.getAddonInfo('Path')) addon_path_mig = filetools.join(addon_path_root, filetools.join("resources", "site-packages")) addon_path = filetools.join(addon_path_mig, addon_name) else: addon_path_root = '' addon_path_mig = '' addon_path = '' #Hay modificaciones en Alfa? Las copiamos al addon, incuidas las carpetas de migración a PY3 if filetools.exists(alfa_addon_updates) and filetools.exists(addon_path): for root, folders, files in filetools.walk(alfa_addon_updates_mig): if ('future' in root or 'past' in root) and not 'concurrent' in root: for file in files: alfa_addon_updates_mig_folder = root.replace(alfa_addon_updates_mig, addon_path_mig) if not filetools.exists(alfa_addon_updates_mig_folder): filetools.mkdir(alfa_addon_updates_mig_folder) if file.endswith('.pyo') or file.endswith('.pyd'): continue input_file = filetools.join(root, file) output_file = input_file.replace(alfa_addon_updates_mig, addon_path_mig) if not filetools.copy(input_file, output_file, silent=True): logger.error('Error en la copia de MIGRACIÓN: Input: %s o Output: %s' % (input_file, output_file)) return False for root, folders, files in filetools.walk(alfa_addon_updates): for file in files: input_file = filetools.join(root, file) output_file = input_file.replace(alfa_addon_updates, addon_path_mig) if file in ['addon.xml']: filetools.copy(input_file, filetools.join(addon_path_root, file), silent=True) continue if not filetools.copy(input_file, output_file, silent=True): logger.error('Error en la copia: Input: %s o Output: %s' % (input_file, output_file)) return False return True else: logger.error('Alguna carpeta no existe: Alfa: %s o %s: %s' % (alfa_addon_updates, addon_name, addon_path_mig)) # Se ha desinstalado Quasar, reseteamos la opción else: config.set_setting('addon_quasar_update', False) if filetools.exists(filetools.join(config.get_data_path(), "%s.json" % addon_name)): filetools.remove(filetools.join(config.get_data_path(), "%s.json" % addon_name)) return True except: logger.error(traceback.format_exc()) return False
def setting(): # support.dbg() xbmc.executebuiltin('UpdateLocalAddons') xbmc.sleep(1000) if filetools.isfile(elementum_setting_file): xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.elementum", "enabled": true }}' ) Continue = True while Continue: try: __settings__ = xbmcaddon.Addon(id="plugin.video.elementum") __settings__.setSetting('skip_burst_search', 'true') __settings__.setSetting('greeting_enabled', 'false') __settings__.setSetting('do_not_disturb', 'true') Continue = False except: support.info('RIPROVO') xbmc.sleep(100) else: if not filetools.exists(elementum_path): filetools.mkdir(elementum_path) filetools.copy(kod_setting_file, elementum_setting_file) xbmc.sleep(1000) xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.elementum", "enabled": true }}' ) updater.refreshLang() if filetools.exists(filename): filetools.remove(filename)
def extract(self, file, dir, folder_to_extract="", overwrite_question=False, backup=False): logger.info("file= %s" % file) logger.info("dir= %s" % dir) if not dir.endswith(':') and not filetools.exists(dir): filetools.mkdir(dir) zf = zipfile.ZipFile(filetools.file_open(file, vfs=False)) if not folder_to_extract: self._createstructure(file, dir) num_files = len(zf.namelist()) for nameo in zf.namelist(): name = nameo.replace(':', '_').replace('<', '_').replace('>', '_').replace('|', '_').replace('"', '_').replace('?', '_').replace('*', '_') logger.info("name=%s" % nameo) if not name.endswith('/'): logger.info("it's not a directory") try: (path, filename) = filetools.split(filetools.join(dir, name)) logger.info("path=%s" % path) logger.info("name=%s" % name) if folder_to_extract: if path != filetools.join(dir, folder_to_extract): break else: filetools.mkdir(path) except: pass if folder_to_extract: outfilename = filetools.join(dir, filename) else: outfilename = filetools.join(dir, name) logger.info("outfilename=%s" % outfilename) try: if filetools.exists(outfilename) and overwrite_question: from platformcode import platformtools dyesno = platformtools.dialog_yesno("File already exists "," File %s to unzip already exists, do you want to overwrite it?" % filetools.basename(outfilename)) if not dyesno: break if backup: import time hora_folder = "Backup [%s]" % time.strftime("%d-%m_%H-%M", time.localtime()) backup = filetools.join(config.get_data_path(), 'backups', hora_folder, folder_to_extract) if not filetools.exists(backup): filetools.mkdir(backup) filetools.copy(outfilename, filetools.join(backup, filetools.basename(outfilename))) if not filetools.write(outfilename, zf.read(nameo), silent=True, vfs=VFS): #TRUNCA en FINAL en Kodi 19 con VFS logger.error("File error " + nameo) except: import traceback logger.error(traceback.format_exc()) logger.error("File error " + nameo) try: zf.close() except: logger.info("Error closing .zip " + file)
def unzip(dir, file): if file.lower().startswith('smb://'): temp = filetools.join(temp_path, os.path.split(file)[-1]) filetools.copy(file, temp) file = temp with ZipFile(filetools.file_open(file, 'rb', vfs=False), 'r') as zf: zf.extractall(dir)
def android_workaround(self, new_dest_path): ### Alfa (entera) import subprocess for libname in get_libname(self.platform): libpath=os.path.join(self.dest_path, libname) size=str(os.path.getsize(libpath)) new_libpath=os.path.join(new_dest_path, libname) if filetools.exists(new_libpath): new_size=str(os.path.getsize(new_libpath)) if size != new_size: filetools.remove(new_libpath) if filetools.exists(new_libpath): try: command = ['su', '-c', 'rm', '%s' % new_libpath] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() log('Comando ROOT: %s' % str(command)) except: log('Sin PERMISOS ROOT: %s' % str(command)) if not filetools.exists(new_libpath): log('Deleted: (%s) %s -> (%s) %s' %(size, libpath, new_size, new_libpath)) if not filetools.exists(new_libpath): filetools.copy(libpath, new_libpath, silent=True) ### ALFA log('Copying... %s -> %s' %(libpath, new_libpath)) if not filetools.exists(new_libpath): try: command = ['su', '-c', 'cp', '%s' % libpath, '%s' % new_libpath] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() log('Comando ROOT: %s' % str(command)) command = ['su', '-c', 'chmod', '777', '%s' % new_libpath] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() log('Comando ROOT: %s' % str(command)) except: log('Sin PERMISOS ROOT: %s' % str(command)) if not filetools.exists(new_libpath): log('ROOT Copy Failed!') else: command = ['chmod', '777', '%s' % new_libpath] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() log('Comando: %s' % str(command)) else: log('Module exists. Not copied... %s' % new_libpath) ### ALFA return new_dest_path
def upgrade_version(channel, list_quality): if channel in ['seriesblanco', 'seriesdanko', 'seriespapaya']: if not config.get_setting("var_temp_filtertools_v2_%s" % channel): dict_series = filetools.get_node_from_data_json(channel, TAG_TVSHOW_FILTER) if dict_series: # Informamos al usuario platformtools.dialog_notification("Espere por favor", "Actualizando filtros al nuevo formato") # Hacemos backup del fichero original = filetools.join(config.get_data_path(), "settings_channels", channel + "_data.json") backup = filetools.join(config.get_data_path(), "settings_channels", channel + "_data.bk_ft") filetools.copy(original, backup) try: for serie in dict_series.keys(): logger.debug("serie %s" % serie) quality_not_allowed = dict_series[serie]["quality_not_allowed"] # Eliminamos el nodo antiguo dict_series[serie].pop("quality_not_allowed", None) # ponemos en minúsculas quality_allowed = [x.lower() for x in list_quality] for quality in quality_not_allowed: if quality in quality_allowed: quality_allowed.remove(quality) # añadimos el nuevo nodo con los datos correctos dict_series[serie][TAG_QUALITY_ALLOWED] = quality_allowed fname, json_data = filetools.update_json_data(dict_series, channel, TAG_TVSHOW_FILTER) result = filetools.write(fname, json_data) except: logger.error("Se ha producido un error al convertir los filtros") logger.error("Debe suministrar el fichero '%s'" % backup) result = False if result: message = "Conversión correcta" config.set_setting("var_temp_filtertools_v2_%s" % channel, "s") else: message = "Error, reporte en el foro" heading = "Proceso terminado" platformtools.dialog_notification(heading, message) else: config.set_setting("var_temp_filtertools_v2_%s" % channel, "s")
def showOnce(): if not config.get_all_settings_addon(): logger.error('corrupted settings.xml!!') settings_xml = filetools.join(config.get_data_path(), 'settings.xml') settings_bak = filetools.join(config.get_data_path(), 'settings.bak') if filetools.exists(settings_bak): filetools.copy(settings_bak, settings_xml, True) logger.info('restored settings.xml from backup') else: filetools.write(settings_xml, '<settings version="2">\n</settings>') # resetted settings else: from platformcode import xbmc_videolibrary xbmc_videolibrary.ask_set_content(silent=False) config.set_setting('show_once', True)
def update_external_addon(addon_name): logger.info(addon_name) #Verificamos que el addon está instalado if xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % addon_name): #Path de actuali<aciones de Alfa alfa_addon_updates = filetools.join(config.get_runtime_path(), filetools.join("lib", addon_name)) #Path de destino en addon externo __settings__ = xbmcaddon.Addon(id="plugin.video." + addon_name) if addon_name.lower() in ['quasar', 'elementum']: addon_path = filetools.join(xbmc.translatePath(__settings__.getAddonInfo('Path')), filetools.join("resources", filetools.join("site-packages", addon_name))) else: addon_path = '' #Hay modificaciones en Alfa? Las copiamos al addon if filetools.exists(alfa_addon_updates) and filetools.exists(addon_path): for root, folders, files in os.walk(alfa_addon_updates): for file in files: input_file = filetools.join(root, file) output_file = input_file.replace(alfa_addon_updates, addon_path) if filetools.copy(input_file, output_file, silent=True) == False: logger.error('Error en la copia: Input: %s o Output: %s' % (input_file, output_file)) return False return True else: logger.error('Alguna carpeta no existe: Alfa: %s o %s: %s' % (alfa_addon_updates, addon_name, addon_path)) return False
def verify_copy_folders(custom_code_dir, custom_code_json_path): logger.info() #verificamos si es una nueva versión de Alfa instalada o era la existente. Si es la existente, nos vamos sin hacer nada json_data_file = filetools.join(custom_code_json_path, json_data_file_name) json_data = jsontools.load(filetools.read(json_data_file)) current_version = config.get_addon_version(with_fix=False) if not json_data or not 'addon_version' in json_data: create_json(custom_code_json_path) json_data = jsontools.load(filetools.read(json_data_file)) try: if current_version == json_data['addon_version']: return except: logger.error(traceback.format_exc(1)) #Ahora copiamos los archivos desde el área de Userdata, Custom_code, sobre las carpetas del add-on for root, folders, files in filetools.walk(custom_code_dir): for file in files: input_file = filetools.join(root, file) output_file = input_file.replace(custom_code_dir, custom_code_json_path) if not filetools.copy(input_file, output_file, silent=True): return #Guardamaos el json con la versión actual de Alfa, para no volver a hacer la copia hasta la nueva versión json_data['addon_version'] = current_version filetools.write(json_data_file, jsontools.dump(json_data)) return
def android_workaround(self, new_dest_path): ### Alfa (entera) for libname in get_libname(self.platform): libpath = filetools.join(self.dest_path, libname) size = str(filetools.getsize(libpath)) new_libpath = filetools.join(new_dest_path, libname) if filetools.exists(new_libpath): new_size = str(filetools.getsize(new_libpath)) if size != new_size: res = filetools.remove(new_libpath, su=True) if res: log('Deleted: (%s) %s -> (%s) %s' % (size, libpath, new_size, new_libpath)) if not filetools.exists(new_libpath): res = filetools.copy(libpath, new_libpath, ch_mod='777', su=True) ### ALFA else: log('Module exists. Not copied... %s' % new_libpath) ### ALFA return new_dest_path
def verify_copy_folders(custom_code_dir, custom_code_json_path): logger.info() #verificamos si es una nueva versión de Alfa instalada o era la existente. Si es la existente, nos vamos sin hacer nada update = None json_data_file = ADDON_CUSTOMCODE_JSON json_data = jsontools.load(filetools.read(json_data_file)) try: if not json_data or not 'addon_version' in json_data: create_json(custom_code_json_path) json_data = jsontools.load(filetools.read(json_data_file)) if not json_data: return if ADDON_VERSION != json_data.get('addon_version', ''): update = 'version' except: logger.error(traceback.format_exc()) json_data['addon_version'] = ADDON_VERSION if not filetools.write(json_data_file, jsontools.dump(json_data)): return #Ahora copiamos los archivos desde el área de Userdata, Custom_code, sobre las carpetas del add-on if update == 'version': for root, folders, files in filetools.walk(custom_code_dir): for file in files: input_file = filetools.join(root, file) output_file = input_file.replace(custom_code_dir, custom_code_json_path) filetools.copy(input_file, output_file, silent=True) if init_version(json_data): json_data['init_version'] = 'true' update = 'init' #Guardamaos el json con la versión actual de Alfa, para no volver a hacer la copia hasta la nueva versión if update: json_data['addon_version'] = ADDON_VERSION filetools.write(json_data_file, jsontools.dump(json_data)) return
def submenu_tools(item): logger.info() itemlist = list() # Herramientas personalizadas import os channel_custom = os.path.join(config.get_runtime_path(), 'channels', 'custom.py') if not filetools.exists(channel_custom): user_custom = os.path.join(config.get_data_path(), 'custom.py') if filetools.exists(user_custom): filetools.copy(user_custom, channel_custom, silent=True) if filetools.exists(channel_custom): itemlist.append(Item(channel='custom', action='mainlist', title='Custom Channel')) #Disabilitato il menu degli aggiornamenti #itemlist.append(Item(channel=CHANNELNAME, action="check_quickfixes", folder=False, # title=config.get_localized_string(30001), plot="Versión actual: %s" % config.get_addon_version() )) itemlist.append(Item(channel=CHANNELNAME, action="update_quasar", folder=False, title=config.get_localized_string(70569))) itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumb("setting_0.png"))) itemlist.append(Item(channel=CHANNELNAME, title=config.get_localized_string(60564) + ":", action="", folder=False, text_bold=True, thumbnail=get_thumb("channels.png"))) itemlist.append(Item(channel=CHANNELNAME, title=config.get_localized_string(60565), action="conf_tools", folder=True, extra="lib_check_datajson", thumbnail=get_thumb("channels.png"))) if config.get_videolibrary_support(): itemlist.append(Item(channel=CHANNELNAME, action="", title="", folder=False, thumbnail=get_thumb("setting_0.png"))) itemlist.append(Item(channel=CHANNELNAME, title=config.get_localized_string(60566) + ":", action="", folder=False, text_bold=True, thumbnail=get_thumb("videolibrary.png"))) itemlist.append(Item(channel=CHANNELNAME, action="overwrite_tools", folder=False, thumbnail=get_thumb("videolibrary.png"), title="- " + config.get_localized_string(60567))) itemlist.append(Item(channel="videolibrary", action="update_videolibrary", folder=False, thumbnail=get_thumb("videolibrary.png"), title="- " + config.get_localized_string(60568))) return itemlist
def download(self): __settings__ = xbmcaddon.Addon(id='plugin.video.alfa') ### Alfa xbmcvfs.mkdirs(self.dest_path) for libname in get_libname(self.platform): dest = os.path.join(self.dest_path, libname) log("try to fetch %s" % libname) url = "%s/%s/%s/%s.zip" % (__libbaseurl__, self.platform['system'], self.platform['version'], libname) if libname != 'liblibtorrent.so': try: self.http = HTTP() self.http.fetch(url, download=dest + ".zip", progress=False) ### Alfa log("%s -> %s" % (url, dest)) xbmc.executebuiltin( 'XBMC.Extract("%s.zip","%s")' % (dest, self.dest_path), True) xbmcvfs.delete(dest + ".zip") except: text = 'Failed download %s!' % libname xbmc.executebuiltin("XBMC.Notification(%s,%s,%s,%s)" % (__plugin__, text, 750, __icon__)) else: xbmcvfs.copy(os.path.join(self.dest_path, 'libtorrent.so'), dest, silent=True) ### Alfa dest_alfa = os.path.join(xbmc.translatePath(__settings__.getAddonInfo('Path')), \ 'lib', libname) ### Alfa xbmcvfs.copy(dest, dest_alfa, silent=True) ### Alfa dest_alfa = os.path.join(xbmc.translatePath(__settings__.getAddonInfo('Profile')), \ 'custom_code', 'lib', libname) ### Alfa xbmcvfs.copy(dest, dest_alfa, silent=True) ### Alfa return True
def download(self): __settings__ = xbmcaddon.Addon(id='plugin.video.alfa') ### Alfa filetools.mkdir(self.dest_path) for libname in get_libname(self.platform): p_version = self.platform['version'] if PY3: p_version += '_PY3' dest = os.path.join(self.dest_path, libname) log("try to fetch %s/%s/%s" % (self.platform['system'], p_version, libname)) for url_lib in __libbaseurl__: ### Alfa url = "%s/%s/%s/%s.zip" % (url_lib, self.platform['system'], p_version, libname) url_size = "%s/%s/%s/%s.size.txt" % ( url_lib, self.platform['system'], p_version, libname) if libname != 'liblibtorrent.so': try: self.http = HTTP() response = self.http.fetch(url, download=dest + ".zip", progress=False) ### Alfa log("%s -> %s" % (url, dest)) if response.code != 200: continue ### Alfa response = self.http.fetch(url_size, download=dest + '.size.txt', progress=False) ### Alfa log("%s -> %s" % (url_size, dest + '.size.txt')) if response.code != 200: continue ### Alfa xbmc.executebuiltin( 'XBMC.Extract("%s.zip","%s")' % (dest, self.dest_path), True) filetools.remove(dest + ".zip") except: text = 'Failed download %s!' % libname #xbmc.executebuiltin("XBMC.Notification(%s,%s,%s,%s)" % (__plugin__,text,750,__icon__)) continue else: filetools.copy(os.path.join(self.dest_path, 'libtorrent.so'), dest, silent=True) ### Alfa dest_alfa = os.path.join(xbmc.translatePath(__settings__.getAddonInfo('Path')), \ 'lib', libname) ### Alfa filetools.copy(dest, dest_alfa, silent=True) ### Alfa dest_alfa = os.path.join(xbmc.translatePath(__settings__.getAddonInfo('Profile')), \ 'custom_code', 'lib', libname) ### Alfa filetools.copy(dest, dest_alfa, silent=True) ### Alfa break else: return False return True
def copiar_lista(item): logger.info() import xbmcgui origen = xbmcgui.Dialog().browseSingle(1, 'Selecciona el fichero .sqlite a copiar', 'files', '.sqlite', False, False, '') # 1:ShowAndGetFile if origen is None or origen == '': return False lista_origen = filetools.basename(origen) destino = filetools.join(trackingtools.get_tracking_path(), lista_origen) if filetools.exists(destino): lista_origen = lista_origen.replace('.sqlite', '') + '-' + datetime.now().strftime('%Y%m%d-%H%M%S') + '.sqlite' destino = filetools.join(trackingtools.get_tracking_path(), lista_origen) platformtools.dialog_ok(config.__addon_name, 'Ya existe una lista con este nombre, se le añade un sufijo para diferenciarla.', lista_origen) if not filetools.copy(origen, destino, silent=False): platformtools.dialog_ok(config.__addon_name, 'Error, no se ha podido copiar la lista!', origen, destino) return False platformtools.itemlist_refresh() return True
def download(self, dest_path='', platform=''): if dest_path: self.dest_path = dest_path if platform: self.platform = platform 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://gitlab.com/addon-alfa/alfa-repo/-/raw/master/downloads/libtorrent'] else: __libbaseurl__ = [ "https://github.com/DiMartinoXBMC/script.module.libtorrent/raw/master/python_libtorrent" ] __settings__ = xbmcaddon.Addon(id='plugin.video.alfa') ### Alfa filetools.mkdir(self.dest_path) for libname in get_libname(self.platform): p_version = self.platform['version'] if PY3: p_version += '_PY3' dest = filetools.join(self.dest_path, libname) log("try to fetch %s/%s/%s" % (self.platform['system'], p_version, libname)) for url_lib in __libbaseurl__: ### Alfa url = "%s/%s/%s/%s.zip" % (url_lib, self.platform['system'], p_version, libname) url_size = "%s/%s/%s/%s.size.txt" % ( url_lib, self.platform['system'], p_version, libname) if libname != 'liblibtorrent.so': try: self.http = HTTP() response = self.http.fetch(url, download=dest + ".zip", progress=False) ### Alfa log("%s -> %s" % (url, dest)) if response.code != 200: continue ### Alfa response = self.http.fetch(url_size, download=dest + '.size.txt', progress=False) ### Alfa log("%s -> %s" % (url_size, dest + '.size.txt')) if response.code != 200: continue ### Alfa try: unzipper = ziptools.ziptools() unzipper.extract("%s.zip" % dest, self.dest_path) except: xbmc.executebuiltin('Extract("%s.zip","%s")' % (dest, self.dest_path)) time.sleep(1) if filetools.exists(dest): filetools.remove(dest + ".zip") except: import traceback text = 'Failed download %s!' % libname log(text) log(traceback.format_exc(1)) #xbmc.executebuiltin("Notification(%s,%s,%s,%s)" % (__plugin__,text,750,__icon__)) continue else: filetools.copy(filetools.join(self.dest_path, 'libtorrent.so'), dest, silent=True) ### Alfa #dest_alfa = filetools.join(filetools.translatePath(__settings__.getAddonInfo('Path')), \ # 'lib', libname) ### Alfa #filetools.copy(dest, dest_alfa, silent=True) ### Alfa dest_alfa = filetools.join(filetools.translatePath(__settings__.getAddonInfo('Profile')), \ 'bin', libname) ### Alfa filetools.remove(dest_alfa, silent=True) filetools.copy(dest, dest_alfa, silent=True) ### Alfa break else: return False return True
def onSettingsChanged(self): logger.debug('settings changed') settings_post = config.get_all_settings_addon() if settings_post: # backup settings filetools.copy( os.path.join(config.get_data_path(), "settings.xml"), os.path.join(config.get_data_path(), "settings.bak"), True) logger.debug({ k: self.settings_pre[k] for k in self.settings_pre if k in settings_post and self.settings_pre[k] != settings_post[k] }) from platformcode import xbmc_videolibrary if self.settings_pre.get('downloadpath', None) != settings_post.get( 'downloadpath', None): xbmc_videolibrary.update_sources( settings_post.get('downloadpath', None), self.settings_pre.get('downloadpath', None)) # If the path of the video library has been changed, we call to check directories so that it creates it and automatically asks if to configure the video library if self.settings_pre.get("videolibrarypath", None) and self.settings_pre.get("videolibrarypath", None) != settings_post.get("videolibrarypath", None) or \ self.settings_pre.get("folder_movies", None) and self.settings_pre.get("folder_movies", None) != settings_post.get("folder_movies", None) or \ self.settings_pre.get("folder_tvshows", None) and self.settings_pre.get("folder_tvshows", None) != settings_post.get("folder_tvshows", None): videolibrary.move_videolibrary( self.settings_pre.get("videolibrarypath", ''), settings_post.get("videolibrarypath", ''), self.settings_pre.get("folder_movies", ''), settings_post.get("folder_movies", ''), self.settings_pre.get("folder_tvshows", ''), settings_post.get("folder_tvshows", '')) # if you want to autoconfigure and the video library directory had been created if not self.settings_pre.get("videolibrary_kodi", None) and settings_post.get( "videolibrary_kodi", None): xbmc_videolibrary.ask_set_content(silent=True) elif self.settings_pre.get( "videolibrary_kodi", None) and not settings_post.get("videolibrary_kodi", None): xbmc_videolibrary.clean() if self.settings_pre.get('addon_update_timer') != settings_post.get( 'addon_update_timer'): schedule.clear('updater') self.scheduleUpdater() if self.update_setting != config.get_setting( "update", "videolibrary") or self.update_hour != config.get_setting( "everyday_delay", "videolibrary") * 4: schedule.clear('videolibrary') self.scheduleVideolibrary() if self.settings_pre.get('elementum_on_seed') != settings_post.get( 'elementum_on_seed') and settings_post.get( 'elementum_on_seed'): if not platformtools.dialog_yesno( config.get_localized_string(70805), config.get_localized_string(70806)): config.set_setting('elementum_on_seed', False) self.settings_pre = settings_post
def searchSubtitle(item): if config.get_setting("subtitle_type") == 0: subtitlepath = config.get_setting("subtitlepath_folder") if subtitlepath == "": subtitlepath = filetools.join(config.get_data_path(), "subtitles") config.set_setting("subtitlepath_folder", subtitlepath) elif config.get_setting("subtitle_type") == 1: subtitlepath = config.get_setting("subtitlepath_keyboard") if subtitlepath == "": subtitlepath = filetools.join(config.get_data_path(), "subtitles") config.set_setting("subtitlepathkeyboard", subtitlepath) elif subtitlepath.startswith("http"): subtitlepath = config.get_setting("subtitlepath_folder") else: subtitlepath = config.get_setting("subtitlepath_folder") if subtitlepath == "": subtitlepath = filetools.join(config.get_data_path(), "subtitles") config.set_setting("subtitlepath_folder", subtitlepath) if not filetools.exists(subtitlepath): try: filetools.mkdir(subtitlepath) except: logger.error("error no se pudo crear path subtitulos") return path_movie_subt = xbmc.translatePath(filetools.join( subtitlepath, "Movies")) if not filetools.exists(path_movie_subt): try: filetools.mkdir(path_movie_subt) except: logger.error("error no se pudo crear el path Movies") return full_path_tvshow = "" path_tvshow_subt = xbmc.translatePath( filetools.join(subtitlepath, "Tvshows")) if not filetools.exists(path_tvshow_subt): try: filetools.mkdir(path_tvshow_subt) except: logger.error("error no pudo crear el path Tvshows") return if item.show in item.title: title_new = title = urllib.unquote_plus(item.title) else: title_new = title = urllib.unquote_plus(item.show + " - " + item.title) path_video_temp = xbmc.translatePath( filetools.join(config.get_runtime_path(), "resources", "subtitle.mp4")) if not filetools.exists(path_video_temp): logger.error("error : no existe el video temporal de subtitulos") return # path_video_temp = xbmc.translatePath(filetools.join( ,video_temp + ".mp4" )) title_new = _normalize(title_new) tvshow_title, season, episode = regex_tvshow(False, title_new) if episode != "": full_path_tvshow = xbmc.translatePath( filetools.join(path_tvshow_subt, tvshow_title)) if not filetools.exists(full_path_tvshow): filetools.mkdir(full_path_tvshow) # title_new + ".mp4" full_path_video_new = xbmc.translatePath( filetools.join(full_path_tvshow, "%s %sx%s.mp4" % (tvshow_title, season, episode))) logger.info(full_path_video_new) listitem = xbmcgui.ListItem(title_new, iconImage="DefaultVideo.png", thumbnailImage="") listitem.setInfo( "video", { "Title": title_new, "Genre": "Tv shows", "episode": int(episode), "season": int(season), "tvshowtitle": tvshow_title }) else: full_path_video_new = xbmc.translatePath( filetools.join(path_movie_subt, title_new + ".mp4")) listitem = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage="") listitem.setInfo("video", {"Title": title_new, "Genre": "Movies"}) import time try: filetools.copy(path_video_temp, full_path_video_new) copy = True logger.info("nuevo path =" + full_path_video_new) time.sleep(2) playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(full_path_video_new, listitem) # xbmcPlayer = xbmc.Player( xbmc.PLAYER_CORE_AUTO ) xbmcPlayer = xbmc.Player() xbmcPlayer.play(playlist) # xbmctools.launchplayer(full_path_video_new,listitem) except: copy = False logger.error("Error : no se pudo copiar") time.sleep(1) if copy: if xbmc.Player().isPlayingVideo(): xbmc.executebuiltin("RunScript(script.xbmc.subtitles)") while xbmc.Player().isPlayingVideo(): continue time.sleep(1) filetools.remove(full_path_video_new) try: if full_path_tvshow != "": filetools.rmdir(full_path_tvshow) except OSError: pass
def verify_directories_created(): from platformcode import logger from core import filetools from platformcode import xbmc_videolibrary config_paths = [["videolibrarypath", "videolibrary"], ["downloadpath", "downloads"], ["downloadlistpath", "downloads/list"], ["settings_path", "settings_channels"]] for path, default in config_paths: saved_path = get_setting(path) # video store if path == "videolibrarypath": if not saved_path: saved_path = xbmc_videolibrary.search_library_path() if saved_path: set_setting(path, saved_path) if not saved_path: saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default set_setting(path, saved_path) saved_path = xbmc.translatePath(saved_path) if not filetools.exists(saved_path): logger.debug("Creating %s: %s" % (path, saved_path)) filetools.mkdir(saved_path) config_paths = [["folder_movies", "Film"], ["folder_tvshows", "Serie TV"]] for path, default in config_paths: saved_path = get_setting(path) if not saved_path: saved_path = default set_setting(path, saved_path) content_path = filetools.join(get_videolibrary_path(), saved_path) if not filetools.exists(content_path): logger.debug("Creating %s: %s" % (path, content_path)) # if the directory is created filetools.mkdir(content_path) from platformcode import xbmc_videolibrary xbmc_videolibrary.update_sources(get_setting("videolibrarypath")) xbmc_videolibrary.update_sources(get_setting("downloadpath")) try: from core import scrapertools # We look for the addon.xml file of the active skin skindir = filetools.join(xbmc.translatePath("special://home"), 'addons', xbmc.getSkinDir(), 'addon.xml') if not os.path.isdir(skindir): return # No need to show error in log if folder doesn't exist # We extract the name of the default resolution folder folder = "" data = filetools.read(skindir) res = scrapertools.find_multiple_matches(data, '(<res .*?>)') for r in res: if 'default="true"' in r: folder = scrapertools.find_single_match(r, 'folder="([^"]+)"') break # We check if it exists in the addon and if not, we create it default = filetools.join(get_runtime_path(), 'resources', 'skins', 'Default') if folder and not filetools.exists(filetools.join(default, folder)): filetools.mkdir(filetools.join(default, folder)) # We copy the file to said folder from the 720p folder if it does not exist or if the size is different if folder and folder != '720p': for root, folders, files in filetools.walk( filetools.join(default, '720p')): for f in files: if not filetools.exists(filetools.join( default, folder, f)) or (filetools.getsize( filetools.join( default, folder, f)) != filetools.getsize( filetools.join(default, '720p', f))): filetools.copy(filetools.join(default, '720p', f), filetools.join(default, folder, f), True) except: import traceback logger.error("When checking or creating the resolution folder") logger.error(traceback.format_exc())
def verify_directories_created(): """ Test if all the required directories are created """ from platformcode import logger from core import filetools from platformcode import xbmc_videolibrary logger.info() time.sleep(1) config_paths = [["videolibrarypath", "videolibrary"], ["downloadpath", "downloads"], ["downloadlistpath", "downloads/list"], ["settings_path", "settings_channels"]] for path, default in config_paths: saved_path = get_setting(path) # videoteca if path == "videolibrarypath": if not saved_path: saved_path = xbmc_videolibrary.search_library_path() if saved_path: set_setting(path, saved_path) if not saved_path: saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default set_setting(path, saved_path) saved_path = translatePath(saved_path) if not filetools.exists(saved_path): logger.debug("Creating %s: %s" % (path, saved_path)) filetools.mkdir(saved_path) config_paths = [["folder_movies", "CINE"], ["folder_tvshows", "SERIES"]] for path, default in config_paths: saved_path = get_setting(path) if not saved_path: saved_path = default set_setting(path, saved_path) content_path = filetools.join(get_videolibrary_path(), saved_path) if not filetools.exists(content_path): logger.debug("Creating %s: %s" % (path, content_path)) # si se crea el directorio filetools.mkdir(content_path) try: # from core import scrapertools # Buscamos el archivo addon.xml del skin activo skindir = filetools.join("special://home", 'addons', xbmc.getSkinDir(), 'addon.xml') if not os.path.isdir(skindir): return # No hace falta mostrar error en el log si no existe la carpeta # Extraemos el nombre de la carpeta de resolución por defecto folder = "" data = filetools.read(skindir) # res = scrapertools.find_multiple_matches(data, '(<res .*?>)') res = re.compile('(<res .*?>)', re.DOTALL).findall(data) for r in res: if 'default="true"' in r: # folder = scrapertools.find_single_match(r, 'folder="([^"]+)"') folder = re.search('folder="([^"]+)"', r).group(1) break # Comprobamos si existe en el addon y sino es así, la creamos default = filetools.join(get_runtime_path(), 'resources', 'skins', 'Default') if folder and not filetools.exists(filetools.join(default, folder)): filetools.mkdir(filetools.join(default, folder)) # Copiamos el archivo a dicha carpeta desde la de 720p si éste no existe o si el tamaño es diferente if folder and folder != '720p': for root, folders, files in filetools.walk(filetools.join(default, '720p')): for f in files: if not filetools.exists(filetools.join(default, folder, f)) or \ (filetools.getsize(filetools.join(default, folder, f)) != filetools.getsize(filetools.join(default, '720p', f))): filetools.copy(filetools.join(default, '720p', f), filetools.join(default, folder, f), True) except: import traceback logger.error("Al comprobar o crear la carpeta de resolución") logger.error(traceback.format_exc())
def update_libtorrent(): logger.info() if not config.get_setting("mct_buffer", server="torrent", default=""): default = config.get_setting("torrent_client", server="torrent", default=0) config.set_setting("torrent_client", default, server="torrent") config.set_setting("mct_buffer", "50", server="torrent") config.set_setting("mct_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_background_download", True, server="torrent") config.set_setting("mct_rar_unpack", True, server="torrent") config.set_setting("bt_buffer", "50", server="torrent") config.set_setting("bt_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_download_limit", "", server="torrent") config.set_setting("magnet2torrent", False, server="torrent") if not filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) or not \ config.get_setting("unrar_path", server="torrent", default=""): path = filetools.join(config.get_runtime_path(), 'lib', 'rarfiles') creationflags = '' sufix = '' unrar = '' for device in filetools.listdir(path): if xbmc.getCondVisibility( "system.platform.android") and 'android' not in device: continue if xbmc.getCondVisibility( "system.platform.windows") and 'windows' not in device: continue if not xbmc.getCondVisibility("system.platform.windows") and not xbmc.getCondVisibility("system.platform.android") \ and ('android' in device or 'windows' in device): continue if 'windows' in device: creationflags = 0x08000000 sufix = '.exe' else: creationflags = '' sufix = '' unrar = filetools.join(path, device, 'unrar%s') % sufix if not filetools.exists(unrar): unrar = '' if unrar: if not xbmc.getCondVisibility("system.platform.windows"): try: if xbmc.getCondVisibility("system.platform.android"): # Para Android copiamos el binario a la partición del sistema unrar_org = unrar unrar = filetools.join( xbmc.translatePath('special://xbmc/'), 'files').replace('/cache/apk/assets', '') if not filetools.exists(unrar): filetools.mkdir(unrar) unrar = filetools.join(unrar, 'unrar') filetools.copy(unrar_org, unrar, silent=True) command = ['chmod', '777', '%s' % unrar] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() command = ['ls', '-l', unrar] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() xbmc.log('######## UnRAR file: %s' % str(output_cmd), xbmc.LOGNOTICE) except: xbmc.log( '######## UnRAR ERROR in path: %s' % str(unrar), xbmc.LOGNOTICE) logger.error(traceback.format_exc(1)) try: if xbmc.getCondVisibility("system.platform.windows"): p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags) else: p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() if p.returncode != 0 or error_cmd: xbmc.log('######## UnRAR returncode in module %s: %s, %s in %s' % \ (device, str(p.returncode), str(error_cmd), unrar), xbmc.LOGNOTICE) unrar = '' else: xbmc.log( '######## UnRAR OK in %s: %s' % (device, unrar), xbmc.LOGNOTICE) break except: xbmc.log( '######## UnRAR ERROR in module %s: %s' % (device, unrar), xbmc.LOGNOTICE) logger.error(traceback.format_exc(1)) unrar = '' if unrar: config.set_setting("unrar_path", unrar, server="torrent") if filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) and \ config.get_setting("libtorrent_path", server="torrent", default="") : return try: from lib.python_libtorrent.python_libtorrent import get_libtorrent except Exception, e: logger.error(traceback.format_exc(1)) e = unicode(str(e), "utf8", errors="replace").encode("utf8") config.set_setting("libtorrent_path", "", server="torrent") if not config.get_setting( "libtorrent_error", server="torrent", default=''): config.set_setting("libtorrent_error", str(e), server="torrent")
def submenu_tools(item): logger.info() itemlist = list() # Herramientas personalizadas import os channel_custom = os.path.join(config.get_runtime_path(), 'channels', 'custom.py') if not filetools.exists(channel_custom): user_custom = os.path.join(config.get_data_path(), 'custom.py') if filetools.exists(user_custom): filetools.copy(user_custom, channel_custom, silent=True) if filetools.exists(channel_custom): itemlist.append( Item(channel='custom', action='mainlist', title='Custom Channel', thumbnail=get_thumb('setting_0.png'), viewType='files')) itemlist.append( Item(action="check_quickfixes", channel=CHANNELNAME, folder=False, plot="Versión actual: {}".format( config.get_addon_version(from_xml=True)), thumbnail=get_thumb("update.png"), title="Comprobar actualizaciones urgentes (Actual: Alfa {})". format(config.get_addon_version(from_xml=True)))) itemlist.append( Item(action="update_quasar", channel=CHANNELNAME, folder=False, thumbnail=get_thumb("update.png"), title="Actualizar addon externo Quasar")) itemlist.append( Item( action="reset_trakt", channel=CHANNELNAME, folder=False, plot= "Reinicia la vinculacion, no se pierden los datos de seguimiento", thumbnail= "https://trakt.tv/assets/logos/white-bg@2x-626e9680c03d0542b3e26c3305f58050d2178e5d4222fac7831d83cf37fef42b.png", title="Reiniciar vinculación con Trakt")) itemlist.append( Item(channel=CHANNELNAME, title=config.get_localized_string(60564) + ":", action="", folder=False, text_bold=True, thumbnail=get_thumb("channels.png"))) itemlist.append( Item(channel=CHANNELNAME, title="- {}".format(config.get_localized_string(60565)), action="conf_tools", folder=True, extra="lib_check_datajson", thumbnail=get_thumb("channels.png"))) if config.get_videolibrary_support(): itemlist.append( Item(channel=CHANNELNAME, title=config.get_localized_string(60566) + ":", action="", folder=False, text_bold=True, thumbnail=get_thumb("videolibrary.png"))) itemlist.append( Item(channel=CHANNELNAME, action="overwrite_tools", folder=False, thumbnail=get_thumb("videolibrary.png"), title="- " + config.get_localized_string(60567))) itemlist.append( Item(channel="videolibrary", action="update_videolibrary", folder=False, thumbnail=get_thumb("videolibrary.png"), title="- " + config.get_localized_string(60568))) return itemlist
def update_libtorrent(): logger.info() if not config.get_setting("mct_buffer", server="torrent", default=""): default = config.get_setting("torrent_client", server="torrent", default=0) config.set_setting("torrent_client", default, server="torrent") config.set_setting("mct_buffer", "50", server="torrent") if config.get_setting("mct_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("mct_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_background_download", True, server="torrent") config.set_setting("mct_rar_unpack", True, server="torrent") config.set_setting("bt_buffer", "50", server="torrent") if config.get_setting("bt_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("bt_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_download_limit", "", server="torrent") config.set_setting("magnet2torrent", False, server="torrent") if not filetools.exists( filetools.join( config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')): filetools.mkdir( filetools.join( config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')) if not filetools.exists( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')): filetools.mkdir( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')) filetools.mkdir( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrents')) if not filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) or not \ config.get_setting("unrar_path", server="torrent", default=""): path = filetools.join(config.get_runtime_path(), 'lib', 'rarfiles') creationflags = '' sufix = '' unrar = '' for device in filetools.listdir(path): if xbmc.getCondVisibility( "system.platform.android") and 'android' not in device: continue if xbmc.getCondVisibility( "system.platform.windows") and 'windows' not in device: continue if not xbmc.getCondVisibility("system.platform.windows") and not xbmc.getCondVisibility("system.platform.android") \ and ('android' in device or 'windows' in device): continue if 'windows' in device: creationflags = 0x08000000 sufix = '.exe' else: creationflags = '' sufix = '' unrar = filetools.join(path, device, 'unrar%s') % sufix if not filetools.exists(unrar): unrar = '' if unrar: if not xbmc.getCondVisibility("system.platform.windows"): try: if xbmc.getCondVisibility("system.platform.android"): # Para Android copiamos el binario a la partición del sistema unrar_org = unrar unrar = filetools.join('special://xbmc/', 'files').replace( '/cache/apk/assets', '') if not filetools.exists(unrar): filetools.mkdir(unrar) unrar = filetools.join(unrar, 'unrar') filetools.copy(unrar_org, unrar, silent=True) filetools.chmod(unrar, '777') except: logger.info('######## UnRAR ERROR in path: %s' % str(unrar), force=True) logger.error(traceback.format_exc()) try: if xbmc.getCondVisibility("system.platform.windows"): p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags) else: p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() if p.returncode != 0 or error_cmd: logger.info('######## UnRAR returncode in module %s: %s, %s in %s' % \ (device, str(p.returncode), str(error_cmd), unrar), force=True) unrar = '' else: logger.info('######## UnRAR OK in %s: %s' % (device, unrar), force=True) break except: logger.info('######## UnRAR ERROR in module %s: %s' % (device, unrar), force=True) logger.error(traceback.format_exc(1)) unrar = '' if unrar: config.set_setting("unrar_path", unrar, server="torrent") # Ahora descargamos la última versión disponible de Libtorrent para esta plataforma try: version_base = filetools.join(config.get_runtime_path(), 'lib', 'python_libtorrent') if config.get_setting("libtorrent_version", server="torrent", default=""): current_system, current_version = config.get_setting( "libtorrent_version", server="torrent", default="").split('/') else: current_system = '' current_version = '' version_base = filetools.join(version_base, current_system) if current_version: old_version = current_version new_version = sorted(filetools.listdir(version_base)) new_version_alt = new_version[:] if new_version: for folder in new_version_alt: if not filetools.isdir(filetools.join( version_base, folder)): new_version.remove(folder) if old_version != new_version[-1]: current_version = '' else: current_version = '' except: current_version = '' logger.error(traceback.format_exc(1)) custom_code_json = filetools.exists( filetools.join(config.get_runtime_path(), "custom_code.json")) if custom_code_json and current_version: msg = 'Libtorrent_path: %s' % config.get_setting( "libtorrent_path", server="torrent", default="") if current_version not in msg: msg += ' - Libtorrent_version: %s/%s' % (current_system, current_version) logger.info(msg, force=True) return try: logger.info('Libtorrent stored version: %s, %s' % (config.get_setting("libtorrent_version", \ server="torrent", default=""), str(custom_code_json)), force=True) from lib.python_libtorrent.python_libtorrent import get_libtorrent except Exception as e: logger.error(traceback.format_exc(1)) if not PY3: e = unicode(str(e), "utf8", errors="replace").encode("utf8") config.set_setting("libtorrent_path", "", server="torrent") if not config.get_setting( "libtorrent_error", server="torrent", default=''): config.set_setting("libtorrent_error", str(e), server="torrent") return
def 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 list_storage(item): logger.info() from core import filetools from lib import generictools itemlist = [] torrent_params = { 'url': item.url, 'torrents_path': '', 'local_torr': item.torrents_path, 'lookup': False, 'force': True, 'data_torrent': True, 'subtitles': True, 'file_list': True } #logger.debug(item) browse_type = 0 path_out = item.url if not filetools.exists(path_out): path_out = '' if not path_out: msg = 'Seleccione carpeta de destino:' path_out = platformtools.dialog_browse(browse_type, msg, shares='') path_list = filetools.listdir(path_out) VIDEOLIBRARY_PATH = config.get_videolibrary_path() FOLDER_MOVIES = config.get_setting("folder_movies") FOLDER_TVSHOWS = config.get_setting("folder_tvshows") FOLDER = '' if VIDEOLIBRARY_PATH in path_out: if FOLDER_MOVIES in path_out: FOLDER = FOLDER_MOVIES elif FOLDER_TVSHOWS in path_out: FOLDER = FOLDER_TVSHOWS MOVIES_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_MOVIES) TVSHOWS_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_TVSHOWS) VIDEO_FOLDER = filetools.join(VIDEOLIBRARY_PATH, FOLDER) TEMP_TORRENT_FOLDER = filetools.join( config.get_setting('downloadpath', default=''), 'cached_torrents_Alfa') MIS_TORRENT_FOLDER = filetools.join( config.get_setting('downloadpath', default=''), 'Mis_Torrents') for file in path_list: if FOLDER and file.endswith('.json') and file.split( '.')[0] + '_01.torrent' in str(path_list): json_video = Item().fromjson( filetools.read(filetools.join(path_out, file))) json_video.channel = 'url' json_video.action = 'findvideos' json_video.torrents_path = json_video.url itemlist.append(json_video) elif FOLDER and filetools.isdir(filetools.join(path_out, file)): if '.torrent' in str(filetools.listdir(filetools.join(path_out, file))) \ or '.magnet' in str(filetools.listdir(filetools.join(path_out, file))): itemlist.append( Item(channel=item.channel, action="list_storage", url=filetools.join(path_out, file), title=file.title(), contentTitle=file.title(), contentType="list", unify=False, context=context)) if len(itemlist) > 1: itemlist = sorted(itemlist, key=lambda it: it.title) #clasificamos elif not FOLDER and filetools.isdir(filetools.join(path_out, file)): if MIS_TORRENT_FOLDER in path_out: title = file.title() if 'BTDigg' in file: title = title.replace( 'Btdigg', '[B][COLOR limegreen]BT[/COLOR][COLOR red]Digg[/COLOR][/B]' ) itemlist.append( Item(channel=item.channel, action="list_storage", url=filetools.join(path_out, file), title=title, contentTitle=title, contentType="list", unify=False, btdigg=True if 'BTDigg' in file else False, url_org=filetools.join(path_out, file), context=context)) if len(itemlist) > 1: itemlist = sorted(itemlist, key=lambda it: it.title) #clasificamos elif not FOLDER and ('.torrent' in file or '.magnet' in file): btdigg = False if '.torrent' in file: url = filetools.join(TEMP_TORRENT_FOLDER, file) filetools.copy(filetools.join(path_out, file), url, silent=True) if not filetools.exists(url): continue else: url = filetools.read(filetools.join(path_out, file), silent=True) if btdigg_magnet in url: btdigg = True size = 'MAGNET' if not url: continue torrent_params['url'] = url torrent_params['torrents_path'] = '' torrent_params['local_torr'] = filetools.join( TEMP_TORRENT_FOLDER, file) torrent_params = generictools.get_torrent_size( url, torrent_params=torrent_params) if '.magnet' in file and 'ERROR' in torrent_params['size']: torrent_params['size'] = 'MAGNET' size = torrent_params['size'] itemlist.append( Item(channel=item.channel, action="play", url=url, url_org=filetools.join(path_out, file), server='torrent', title=filetools.join( filetools.basename(path_out.rstrip('/').rstrip('\\')), file).title() + " [%s]" % size, contentTitle=filetools.join( filetools.basename(path_out.rstrip('/').rstrip('\\')), file).title(), contentType="movie", unify=False, torrents_path=torrent_params['torrents_path'], infoLabels={"tmdb_id": "111"}, context=context, btdigg=btdigg)) if len(itemlist) > 1: itemlist = sorted(itemlist, key=lambda it: it.title) #clasificamos return itemlist
def run(item=None): # from core.support import dbg;dbg() logger.debug() if not item: # Extract item from sys.argv if sys.argv[2]: sp = sys.argv[2].split('&') url = sp[0] item = Item().fromurl(url) if len(sp) > 1: for e in sp[1:]: key, val = e.split('=') item.__setattr__(key, val) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): if not config.get_all_settings_addon(): logger.error('corrupted settings.xml!!') settings_xml = os.path.join(config.get_data_path(), "settings.xml") settings_bak = os.path.join(config.get_data_path(), "settings.bak") if filetools.exists(settings_bak): filetools.copy(settings_bak, settings_xml, True) logger.info('restored settings.xml from backup') else: filetools.write(settings_xml, '<settings version="2">\n</settings>' ) # resetted settings else: from platformcode import xbmc_videolibrary xbmc_videolibrary.ask_set_content(silent=False) config.set_setting('show_once', True) logger.info(item.tostring()) try: if not config.get_setting('tmdb_active'): config.set_setting('tmdb_active', True) # If item has no action, stops here if item.action == "": logger.debug("Item without action") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() elif item.channel == "infoplus": from platformcode import infoplus return infoplus.Main(item) elif item.channel == "backup": from platformcode import backup return getattr(backup, item.action)(item) elif item.channel == "elementum_download": from platformcode import elementum_download return getattr(elementum_download, item.action)(item) elif item.channel == "shortcuts": from platformcode import shortcuts return getattr(shortcuts, item.action)(item) elif item.channel == "autorenumber": from platformcode import autorenumber return getattr(autorenumber, item.action)(item) elif item.action == "delete_key": from platformcode import keymaptools return keymaptools.delete_key() elif item.action == "script": from core import tmdb if tmdb.drop_bd(): platformtools.dialog_notification( config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) elif item.action == "itemInfo": platformtools.dialog_textviewer('Item info', item.parent) elif item.action == "open_browser": import webbrowser if not webbrowser.open(item.url): import xbmc if xbmc.getCondVisibility( 'system.platform.linux') and xbmc.getCondVisibility( 'system.platform.android'): # android xbmc.executebuiltin( 'StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")' % (item.url)) else: try: import urllib.request as urllib except ImportError: import urllib short = urllib.urlopen( 'https://u.nu/api.php?action=shorturl&format=simple&url=' + item.url).read().decode('utf-8') platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(70740) % short) # Action in certain channel specified in "action" and "channel" parameters elif item.action == "check_channels": from platformcode import checkhost checkhost.check_channels() else: # Checks if channel exists if os.path.isfile( os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py")): CHANNELS = 'channels' else: CHANNELS = 'specials' channel_file = os.path.join(config.get_runtime_path(), CHANNELS, item.channel + ".py") logger.debug("channel_file= " + channel_file + ' - ' + CHANNELS + ' - ' + item.channel) channel = None if os.path.exists(channel_file): try: channel = __import__('%s.%s' % (CHANNELS, item.channel), None, None, ['%s.%s' % (CHANNELS, item.channel)]) except ImportError: exec("import " + CHANNELS + "." + item.channel + " as channel") logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": # define la info para trakt try: from core import trakt_tools trakt_tools.set_trakt_info(item) except: pass logger.debug("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.debug("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el Channel elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(60339)) # If player don't have a "play" function, not uses the standard play from platformtools else: logger.debug("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": from core import servertools # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.debug("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": from core import videolibrarytools videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": from core import videolibrarytools videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from specials import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": # from core.support import dbg;dbg() if filetools.isfile(temp_search_file) and config.get_setting( 'videolibrary_kodi'): itemlist = [] f = filetools.read(temp_search_file) strList = f.split(',') if strList[0] == '[V]' and strList[1] == item.channel: for it in strList: if it and it not in ['[V]', item.channel]: itemlist.append(Item().fromurl(it)) filetools.write(temp_search_file, f[4:]) return platformtools.render_items(itemlist, item) else: filetools.remove(temp_search_file) logger.debug("item.action=%s" % item.action.upper()) from core import channeltools if config.get_setting('last_search'): last_search = channeltools.get_channel_setting( 'Last_searched', 'search', '') else: last_search = '' search_text = platformtools.dialog_input(last_search) if search_text is not None: channeltools.set_channel_setting('Last_searched', search_text, 'search') itemlist = new_search(item.clone(text=search_text), channel) else: return platformtools.render_items(itemlist, item) # For all other actions else: # import web_pdb; web_pdb.set_trace() logger.debug("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) if config.get_setting('trakt_sync'): from core import trakt_tools token_auth = config.get_setting("token_trakt", "trakt") if not token_auth: trakt_tools.auth_trakt() else: import xbmc if not xbmc.getCondVisibility( 'System.HasAddon(script.trakt)' ) and config.get_setting('install_trakt'): trakt_tools.ask_install_script() itemlist = trakt_tools.trakt_check(itemlist) else: config.set_setting('install_trakt', True) platformtools.render_items(itemlist, item) except WebErrorException as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) platformtools.dialog_ok( config.get_localized_string(59985) % e.channel, config.get_localized_string(60013) % e.url) except Exception as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + r'([^.]+)\.py"' Channel = scrapertools.find_single_match(traceback.format_exc(), patron) if Channel or e.__class__ == logger.ChannelScraperException: if item.url: if platformtools.dialog_yesno( config.get_localized_string(60087) % Channel, config.get_localized_string(60014), nolabel='ok', yeslabel=config.get_localized_string(70739)): run(Item(action="open_browser", url=item.url)) else: platformtools.dialog_ok( config.get_localized_string(60087) % Channel, config.get_localized_string(60014)) else: if platformtools.dialog_yesno(config.get_localized_string(60038), config.get_localized_string(60015)): run(Item(channel="setting", action="report_menu"))
def install_alfa_now(silent=True): logger.info() import json from core import ziptools from core import httptools try: versiones = config.get_versions_from_repo() except: versiones = {} logger.error(traceback.format_exc()) if not versiones: return addons_path = filetools.translatePath("special://home/addons") alfa_addon = ['plugin.video.alfa', '3.4.2', '*'] addonid = alfa_addon[0] new_version = versiones.get(addonid, alfa_addon[1]) package = addonid + '-%s.zip' % new_version logger.info("Downloading %s" % package) url = '%s%s/%s' % (versiones.get('url', ''), addonid, package) response = httptools.downloadpage(url, ignore_response_code=True, alfa_s=True, json_to_utf8=False) if response.code == 200: zip_data = response.data pkg_updated = filetools.join(addons_path, 'packages', package) res = filetools.write(pkg_updated, zip_data, mode='wb') if res and filetools.exists(pkg_updated): logger.info("backing and removing installed version... %s" % package) backup_path = filetools.join(addons_path, "temp", addonid) if filetools.exists(backup_path): res = filetools.rmdirtree(backup_path, silent=silent) if not res: return time.sleep(3) if not filetools.exists(backup_path): filetools.copy(ADDON_PATH, backup_path) time.sleep(3) res = filetools.rmdirtree(ADDON_PATH, silent=silent) time.sleep(3) if filetools.exists(ADDON_PATH): logger.error("backing and removing installed version FAILED ... %s" % package) filetools.copy(backup_path, ADDON_PATH) time.sleep(3) return else: logger.error("backing and removing installed version FAILED ... %s" % package) return else: logger.error("Unable to download %s" % package) return # Si el .zip es correcto los extraemos e instalamos try: unzipper = ziptools.ziptools() unzipper.extract(pkg_updated, addons_path, silent=silent) time.sleep(3) except: try: xbmc.executebuiltin('Extract("%s", "%s")' % (pkg_updated, addons_path)) time.sleep(3) except: filetools.copy(backup_path, ADDON_PATH) time.sleep(3) return logger.info("Installing %s" % package) xbmc.executebuiltin('UpdateLocalAddons') time.sleep(2) method = "Addons.SetAddonEnabled" xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "id":1, "method": "%s", "params": {"addonid": "%s", "enabled": true}}' % (method, addonid)) profile = json.loads(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id":1, "method": "Profiles.GetCurrentProfile"}')) logger.info("Reloading Profile...") user = profile["result"]["label"] xbmc.executebuiltin('LoadProfile(%s)' % user)
def verify_directories_created(): from core import logger from core import filetools from platformcode import xbmc_videolibrary config_paths = [["videolibrarypath", "videolibrary"], ["downloadpath", "downloads"], ["downloadlistpath", "downloads/list"], ["settings_path", "settings_channels"]] for path, default in config_paths: saved_path = get_setting(path) # videoteca if path == "videolibrarypath": if not saved_path: saved_path = xbmc_videolibrary.search_library_path() if saved_path: set_setting(path, saved_path) if not saved_path: saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default set_setting(path, saved_path) saved_path = xbmc.translatePath(saved_path) if not filetools.exists(saved_path): logger.debug("Creating %s: %s" % (path, saved_path)) filetools.mkdir(saved_path) config_paths = [["folder_movies", "CINE"], ["folder_tvshows", "SERIES"]] flag_call = True for path, default in config_paths: saved_path = get_setting(path) if not saved_path: saved_path = default set_setting(path, saved_path) content_path = filetools.join(get_videolibrary_path(), saved_path) if not filetools.exists(content_path): logger.debug("Creating %s: %s" % (path, content_path)) # si se crea el directorio if filetools.mkdir(content_path): if flag_call: # le pasamos el valor para que sepamos que se ha pasado por creación de directorio xbmc_videolibrary.ask_set_content(1) flag_call = False try: from core import scrapertools # Buscamos el archivo addon.xml del skin activo skindir = filetools.join(xbmc.translatePath("special://home"), 'addons', xbmc.getSkinDir(), 'addon.xml') # Extraemos el nombre de la carpeta de resolución por defecto folder = "" data = filetools.read(skindir) res = scrapertools.find_multiple_matches(data, '(<res .*?>)') for r in res: if 'default="true"' in r: folder = scrapertools.find_single_match(r, 'folder="([^"]+)"') break # Comprobamos si existe en el addon y sino es así, la creamos default = filetools.join(get_runtime_path(), 'resources', 'skins', 'Default') if folder and not filetools.exists(filetools.join(default, folder)): filetools.mkdir(filetools.join(default, folder)) # Copiamos el archivo a dicha carpeta desde la de 720p si éste no existe o si el tamaño es diferente if folder and folder != '720p': for root, folders, files in filetools.walk( filetools.join(default, '720p')): for f in files: if not filetools.exists(filetools.join(default, folder, f)) or \ (filetools.getsize(filetools.join(default, folder, f)) != filetools.getsize(filetools.join(default, '720p', f))): filetools.copy(filetools.join(default, '720p', f), filetools.join(default, folder, f), True) except: import traceback logger.error("Al comprobar o crear la carpeta de resolución") logger.error(traceback.format_exc())
def update_libtorrent(): logger.info() if not config.get_setting("mct_buffer", server="torrent", default=""): default = config.get_setting("torrent_client", server="torrent", default=0) config.set_setting("torrent_client", default, server="torrent") config.set_setting("mct_buffer", "50", server="torrent") if config.get_setting("mct_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("mct_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_background_download", True, server="torrent") config.set_setting("mct_rar_unpack", True, server="torrent") config.set_setting("bt_buffer", "50", server="torrent") if config.get_setting("bt_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("bt_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_download_limit", "", server="torrent") config.set_setting("magnet2torrent", False, server="torrent") if not filetools.exists(filetools.join(config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')): filetools.mkdir(filetools.join(config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')) if not filetools.exists(filetools.join(config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')): filetools.mkdir(filetools.join(config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')) filetools.mkdir(filetools.join(config.get_setting("mct_download_path", server="torrent"), 'MCT-torrents')) if not filetools.exists(ADDON_USERDATA_BIN_PATH): filetools.mkdir(ADDON_USERDATA_BIN_PATH) if not filetools.exists(ADDON_CUSTOMCODE_JSON) or not config.get_setting("unrar_path", server="torrent", default="") \ or (not 'unrar' in str(filetools.listdir(ADDON_USERDATA_BIN_PATH)).lower() and \ not xbmc.getCondVisibility("system.platform.android")) \ or xbmc.getCondVisibility("system.platform.android"): path = filetools.join(ADDON_PATH, 'lib', 'rarfiles') sufix = '' unrar = '' for device in filetools.listdir(path): if xbmc.getCondVisibility("system.platform.android") and 'android' not in device: continue if xbmc.getCondVisibility("system.platform.windows") and 'windows' not in device: continue if not xbmc.getCondVisibility("system.platform.windows") and not xbmc.getCondVisibility("system.platform.android") \ and ('android' in device or 'windows' in device): continue if 'windows' in device: sufix = '.exe' else: sufix = '' unrar = filetools.join(path, device, 'unrar%s') % sufix unrar_dest = filetools.join(ADDON_USERDATA_BIN_PATH, 'unrar%s') % sufix if not filetools.exists(unrar): unrar = '' if unrar: if not xbmc.getCondVisibility("system.platform.windows"): try: if xbmc.getCondVisibility("system.platform.android"): # Para Android copiamos el binario a la partición del sistema unrar_org = unrar unrar = filetools.join('special://xbmc/', 'files').replace('/cache/apk/assets', '') if not filetools.exists(unrar): filetools.mkdir(unrar) unrar = filetools.join(unrar, 'unrar') res = filetools.copy(unrar_org, unrar, silent=True) if not res: raise filetools.chmod(unrar, '777') except: logger.info('######## UnRAR ERROR in path: %s' % str(unrar), force=True) logger.error(traceback.format_exc()) if not xbmc.getCondVisibility("system.platform.android"): res = filetools.copy(unrar, unrar_dest, ch_mod='777', silent=True) if not res: logger.info('######## UnRAR ERROR in path: %s' % str(unrar_dest), force=True) continue unrar = unrar_dest try: p = execute_binary_from_alfa_assistant('openBinary', [unrar], wait=True, init=True) try: output_cmd, error_cmd = p.communicate() if p.returncode != 0 or error_cmd: logger.info('######## UnRAR returncode in module %s: %s, %s in %s' % \ (device, str(p.returncode), str(error_cmd), unrar), force=True) unrar = '' else: logger.info('######## UnRAR OK in %s: %s' % (device, unrar), force=True) break except: if p.returncode == 0: logger.info('######## UnRAR OK in %s: %s' % (device, unrar), force=True) break except: logger.info('######## UnRAR ERROR in module %s: %s' % (device, unrar), force=True) logger.error(traceback.format_exc(1)) unrar = '' if unrar: config.set_setting("unrar_path", unrar, server="torrent") config.set_setting("unrar_device", device, server="torrent") else: config.set_setting("unrar_path", "", server="torrent") config.set_setting("unrar_device", "", server="torrent") # Ahora descargamos la última versión disponible de Libtorrent para esta plataforma try: # Saltamos plataformas no soportadas if PY3 and (xbmc.getCondVisibility("system.platform.Windows") or xbmc.getCondVisibility("system.platform.android")): config.set_setting("libtorrent_path", "", server="torrent") config.set_setting("libtorrent_version", "ERROR/UNSUPPORTED", server="torrent") return version_base = filetools.join(ADDON_PATH, 'lib', 'python_libtorrent') libt_dir = filetools.listdir(filetools.join(ADDON_USERDATA_PATH, 'custom_code', 'lib')) if 'libtorrent' in str(libt_dir) or (not 'libtorrent' in str(filetools.listdir(ADDON_USERDATA_BIN_PATH)) and \ not xbmc.getCondVisibility("system.platform.android")): for libt_file in libt_dir: if 'libtorrent' in libt_file: filetools.remove(filetools.join(ADDON_USERDATA_PATH, 'custom_code', 'lib', libt_file), silent=True) current_system = '' current_version = '' elif config.get_setting("libtorrent_version", server="torrent", default="") \ and config.get_setting("libtorrent_path", server="torrent", default=""): current_system, current_version = config.get_setting("libtorrent_version", server="torrent", default="").split('/') else: current_system = '' current_version = '' if '1.1.1' not in current_version and ('arm' in current_system or 'aarch64' in current_system): current_version = '' version_base = filetools.join(version_base, current_system) if current_version: old_version = current_version new_version = sorted(filetools.listdir(version_base)) new_version_alt = new_version[:] if new_version: for folder in new_version_alt: if not filetools.isdir(filetools.join(version_base, folder)): new_version.remove(folder) if old_version != new_version[-1]: current_version = '' else: current_version = '' except: current_version = '' logger.error(traceback.format_exc(1)) custom_code_json = filetools.exists(ADDON_CUSTOMCODE_JSON) if custom_code_json and current_version: msg = 'Libtorrent_path: %s' % config.get_setting("libtorrent_path", server="torrent", default="") if current_version not in msg: msg += ' - Libtorrent_version: %s/%s' % (current_system, current_version) logger.info(msg, force=True) return try: logger.info('Libtorrent stored version: %s, %s' % (config.get_setting("libtorrent_version", \ server="torrent", default=""), str(custom_code_json)), force=True) from lib.python_libtorrent.python_libtorrent import get_libtorrent except Exception as e: logger.error(traceback.format_exc(1)) if not PY3: e = unicode(str(e), "utf8", errors="replace").encode("utf8") config.set_setting("libtorrent_path", "", server="torrent") if not config.get_setting("libtorrent_error", server="torrent", default=''): config.set_setting("libtorrent_error", str(e), server="torrent") return