def __init__(self, url, mode="r"): import random try: from core import filetools except: xbmc = None self.url = url self.remote, self.share, self.path = path = connect(url) self.mode = mode self.binary = False self.canread = False self.canwrite = False self.closed = True self.size = 0 self.pos = 0 if xbmc: self.tmp_path = os.path.join( filetools.translatePath("special://temp/"), "%08x" % (random.getrandbits(32))) else: self.tmp_path = os.path.join( os.getenv("TEMP") or os.getenv("TMP") or os.getenv("TMPDIR"), "%08x" % (random.getrandbits(32))) self.tmp_file = None self.__get_mode__()
def get_environment(): """ Devuelve las variables de entorno del OS, de Kodi y de Alfa más habituales, necesarias para el diagnóstico de fallos """ try: import base64 import ast environment = config.get_platform(full_version=True) environment['num_version'] = str(environment['num_version']) environment['python_version'] = '%s (%s, %s)' % (str(platform.python_version()), \ str(sys.api_version), str(platform.python_implementation())) environment['os_release'] = str(platform.release()) environment['prod_model'] = '' try: import multiprocessing environment['proc_num'] = ' (%sx)' % str( multiprocessing.cpu_count()) except: environment['proc_num'] = '' if xbmc.getCondVisibility("system.platform.Windows"): try: if platform.platform(): environment['os_release'] = str( platform.platform()).replace('Windows-', '') elif platform._syscmd_ver()[2]: environment['os_release'] = str(platform._syscmd_ver()[2]) command = ["wmic", "cpu", "get", "name"] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=0x08000000) output_cmd, error_cmd = p.communicate() if PY3 and isinstance(output_cmd, bytes): output_cmd = output_cmd.decode() output_cmd = re.sub(r'\n|\r|\s{2}', '', output_cmd) environment['prod_model'] = str(scrapertools.find_single_match(output_cmd, \ '\w+.*?(?i)(?:Intel\(R\))?(?:\s*Core\(TM\))\s*(.*?CPU.*?)\s*(?:\@|$)')) except: pass if xbmc.getCondVisibility("system.platform.Android"): environment['os_name'] = 'Android' try: for label_a in subprocess.check_output('getprop').split(FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'build.version.release' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, ':\s*\[(.*?)\]$')) if 'product.model' in label_a: environment['prod_model'] = str( scrapertools.find_single_match( label_a, ':\s*\[(.*?)\]$')) except: try: for label_a in filetools.read(os.environ['ANDROID_ROOT'] + '/build.prop').split(): if 'build.version.release' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, '=(.*?)$')) if 'product.model' in label_a: environment['prod_model'] = str( scrapertools.find_single_match( label_a, '=(.*?)$')) except: pass environment['prod_model'] += ' (%s)' % config.is_rooted( silent=True) elif xbmc.getCondVisibility("system.platform.Linux"): environment['os_name'] = 'Linux' try: for label_a in subprocess.check_output('hostnamectl').split( FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'Operating' in label_a: environment['os_release'] = str( scrapertools.find_single_match( label_a, 'Operating\s*S\w+:\s*(.*?)\s*$')) break for label_a in subprocess.check_output( ['cat', '/proc/cpuinfo']).split(FF): if PY3 and isinstance(label_a, bytes): label_a = label_a.decode() if 'model name' in label_a: environment['prod_model'] = str(scrapertools.find_single_match(label_a, \ 'model.*?:\s*(?i)(?:Intel\(R\))?(?:\s*Core\(TM\))\s*(.*?CPU.*?)\s*(?:\@|$)')) break except: pass elif xbmc.getCondVisibility("system.platform.Linux.RaspberryPi"): environment['os_name'] = 'RaspberryPi' else: environment['os_name'] = str(platform.system()) if not environment['os_release']: environment['os_release'] = str(platform.release()) if environment['proc_num'] and environment['prod_model']: environment['prod_model'] += environment['proc_num'] environment['machine'] = str(platform.machine()) environment['architecture'] = str(sys.maxsize > 2**32 and "64-bit" or "32-bit") environment['language'] = str(xbmc.getInfoLabel('System.Language')) environment['cpu_usage'] = str(xbmc.getInfoLabel('System.CpuUsage')) environment['mem_total'] = str( xbmc.getInfoLabel('System.Memory(total)')).replace('MB', '').replace( 'KB', '') environment['mem_free'] = str( xbmc.getInfoLabel('System.Memory(free)')).replace('MB', '').replace( 'KB', '') if not environment['mem_total'] or not environment['mem_free']: try: if environment['os_name'].lower() == 'windows': kernel32 = ctypes.windll.kernel32 c_ulong = ctypes.c_ulong c_ulonglong = ctypes.c_ulonglong class MEMORYSTATUS(ctypes.Structure): _fields_ = [('dwLength', c_ulong), ('dwMemoryLoad', c_ulong), ('dwTotalPhys', c_ulonglong), ('dwAvailPhys', c_ulonglong), ('dwTotalPageFile', c_ulonglong), ('dwAvailPageFile', c_ulonglong), ('dwTotalVirtual', c_ulonglong), ('dwAvailVirtual', c_ulonglong), ('availExtendedVirtual', c_ulonglong)] memoryStatus = MEMORYSTATUS() memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS) kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus)) environment['mem_total'] = str( old_div(int(memoryStatus.dwTotalPhys), (1024**2))) environment['mem_free'] = str( old_div(int(memoryStatus.dwAvailPhys), (1024**2))) else: with open('/proc/meminfo') as f: meminfo = f.read() environment['mem_total'] = str( old_div( int( re.search(r'MemTotal:\s+(\d+)', meminfo).groups()[0]), 1024)) environment['mem_free'] = str( old_div( int( re.search(r'MemAvailable:\s+(\d+)', meminfo).groups()[0]), 1024)) except: environment['mem_total'] = '' environment['mem_free'] = '' try: environment['kodi_buffer'] = '20' environment['kodi_bmode'] = '0' environment['kodi_rfactor'] = '4.0' if filetools.exists( filetools.join("special://userdata", "advancedsettings.xml")): advancedsettings = filetools.read( filetools.join("special://userdata", "advancedsettings.xml")).split('\n') for label_a in advancedsettings: if 'memorysize' in label_a: environment['kodi_buffer'] = str( old_div( int( scrapertools.find_single_match( label_a, '>(\d+)<\/')), 1024**2)) if 'buffermode' in label_a: environment['kodi_bmode'] = str( scrapertools.find_single_match( label_a, '>(\d+)<\/')) if 'readfactor' in label_a: environment['kodi_rfactor'] = str( scrapertools.find_single_match( label_a, '>(.*?)<\/')) except: pass environment['userdata_path'] = str(config.get_data_path()) environment['userdata_path_perm'] = filetools.file_info( environment['userdata_path']) if not environment['userdata_path_perm']: del environment['userdata_path_perm'] try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(environment['userdata_path']), None, None, ctypes.pointer(free_bytes)) environment['userdata_free'] = str( round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['userdata_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['userdata_free'] = '?' if environment['userdata_path_perm']: environment['userdata_path'] = environment['userdata_path_perm'] del environment['userdata_path_perm'] environment['torrent_lang'] = '%s/%s' % (config.get_setting("channel_language", default="").upper(), \ config.get_setting("second_language", default="").upper()) try: environment['videolab_series'] = '?' environment['videolab_episodios'] = '?' environment['videolab_pelis'] = '?' environment['videolab_path'] = str(config.get_videolibrary_path()) environment['videolab_path_perm'] = filetools.file_info( environment['videolab_path']) if not environment['videolab_path_perm']: environment['videolab_path_perm'] = environment[ 'videolab_path'] if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))))) counter = 0 for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \ config.get_setting("folder_tvshows"))): for file in files: if file.endswith('.strm'): counter += 1 environment['videolab_episodios'] = str(counter) if filetools.exists(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))): environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \ config.get_setting("folder_movies"))))) except: pass try: video_updates = [ 'No', 'Inicio', 'Una vez', 'Inicio+Una vez', 'Dos veces al día' ] environment['videolab_update'] = str( video_updates[config.get_setting("update", "videolibrary")]) except: environment['videolab_update'] = '?' try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(environment['videolab_path']), None, None, ctypes.pointer(free_bytes)) environment['videolab_free'] = str( round(float(free_bytes.value) / (1024**3), 3)) else: disk_space = os.statvfs(environment['videolab_path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)) except: environment['videolab_free'] = '?' environment['torrent_list'] = [] environment['torrentcli_option'] = '' environment['torrent_error'] = '' environment['torrentcli_rar'] = config.get_setting("mct_rar_unpack", server="torrent", default=True) environment['torrentcli_backgr'] = config.get_setting( "mct_background_download", server="torrent", default=True) environment['torrentcli_lib_path'] = config.get_setting( "libtorrent_path", server="torrent", default="") if environment['torrentcli_lib_path']: lib_path = 'Activo' else: lib_path = 'Inactivo' if config.get_setting("libtorrent_version", server="torrent", default=""): lib_path += '-%s' % config.get_setting( "libtorrent_version", server="torrent", default="") environment['torrentcli_unrar'] = config.get_setting("unrar_path", server="torrent", default="") if environment['torrentcli_unrar']: if xbmc.getCondVisibility("system.platform.Android"): unrar = 'Android' else: unrar = filetools.dirname(environment['torrentcli_unrar']) unrar = filetools.basename(unrar).capitalize() else: unrar = 'Inactivo' torrent_id = config.get_setting("torrent_client", server="torrent", default=0) environment['torrentcli_option'] = str(torrent_id) torrent_options = platformtools.torrent_client_installed() if lib_path != 'Inactivo': torrent_options = ['MCT'] + torrent_options torrent_options = ['BT'] + torrent_options environment['torrent_list'].append({'Torrent_opt': str(torrent_id), 'Libtorrent': lib_path, \ 'RAR_Auto': str(environment['torrentcli_rar']), \ 'RAR_backgr': str(environment['torrentcli_backgr']), \ 'UnRAR': unrar}) environment['torrent_error'] = config.get_setting("libtorrent_error", server="torrent", default="") if environment['torrent_error']: environment['torrent_list'].append( {'Libtorrent_error': environment['torrent_error']}) for torrent_option in torrent_options: cliente = dict() cliente['D_load_Path'] = '' cliente['Libre'] = '?' cliente['Plug_in'] = torrent_option.replace('Plugin externo: ', '') if cliente['Plug_in'] == 'BT': cliente['D_load_Path'] = str( config.get_setting("bt_download_path", server="torrent", default='')) if not cliente['D_load_Path']: continue cliente['D_load_Path'] = filetools.join( cliente['D_load_Path'], 'BT-torrents') cliente['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) if not cliente['D_load_Path_perm']: del cliente['D_load_Path_perm'] cliente['Buffer'] = str( config.get_setting("bt_buffer", server="torrent", default=50)) elif cliente['Plug_in'] == 'MCT': cliente['D_load_Path'] = str( config.get_setting("mct_download_path", server="torrent", default='')) if not cliente['D_load_Path']: continue cliente['D_load_Path'] = filetools.join( cliente['D_load_Path'], 'MCT-torrent-videos') cliente['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) if not cliente['D_load_Path_perm']: del cliente['D_load_Path_perm'] cliente['Buffer'] = str( config.get_setting("mct_buffer", server="torrent", default=50)) elif xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % cliente['Plug_in']): try: __settings__ = xbmcaddon.Addon(id="plugin.video.%s" % cliente['Plug_in']) except: continue cliente['Plug_in'] = cliente['Plug_in'].capitalize() if cliente['Plug_in'] == 'Torrenter': cliente['D_load_Path'] = str( filetools.translatePath( __settings__.getSetting('storage'))) if not cliente['D_load_Path']: cliente['D_load_Path'] = str(filetools.join("special://home/", \ "cache", "xbmcup", "plugin.video.torrenter", "Torrenter")) cliente['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) if not cliente['D_load_Path_perm']: del cliente['D_load_Path_perm'] cliente['Buffer'] = str( __settings__.getSetting('pre_buffer_bytes')) else: cliente['D_load_Path'] = str( filetools.translatePath( __settings__.getSetting('download_path'))) cliente['D_load_Path_perm'] = filetools.file_info( cliente['D_load_Path']) if not cliente['D_load_Path_perm']: del cliente['D_load_Path_perm'] cliente['Buffer'] = str( __settings__.getSetting('buffer_size')) if __settings__.getSetting( 'download_storage' ) == '1' and __settings__.getSetting('memory_size'): cliente['Memoria'] = str( __settings__.getSetting('memory_size')) if cliente['D_load_Path']: try: if environment['os_name'].lower() == 'windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(cliente['D_load_Path']), None, None, ctypes.pointer(free_bytes)) cliente['Libre'] = str(round(float(free_bytes.value) / \ (1024**3), 3)).replace('.', ',') else: disk_space = os.statvfs(cliente['D_load_Path']) if not disk_space.f_frsize: disk_space.f_frsize = disk_space.f_frsize.f_bsize cliente['Libre'] = str(round((float(disk_space.f_bavail) / \ (1024**3)) * float(disk_space.f_frsize), 3)).replace('.', ',') except: pass if cliente['D_load_Path_perm']: cliente['D_load_Path'] = cliente['D_load_Path_perm'] del cliente['D_load_Path_perm'] environment['torrent_list'].append(cliente) environment['proxy_active'] = '' try: proxy_channel_bloqued_str = base64.b64decode( config.get_setting('proxy_channel_bloqued')).decode('utf-8') proxy_channel_bloqued = dict() proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str) for channel_bloqued, proxy_active in list( proxy_channel_bloqued.items()): if proxy_active != 'OFF': environment['proxy_active'] += channel_bloqued + ', ' except: pass if not environment['proxy_active']: environment['proxy_active'] = 'OFF' environment['proxy_active'] = environment['proxy_active'].rstrip(', ') for root, folders, files in filetools.walk("special://logpath/"): for file in files: if file.lower() in ['kodi.log', 'jarvis.log', 'spmc.log', 'cemc.log', \ 'mygica.log', 'wonderbox.log', 'leiapp,log', \ 'leianmc.log', 'kodiapp.log', 'anmc.log', \ 'latin-anmc.log']: environment['log_path'] = str(filetools.join(root, file)) break else: environment['log_path'] = '' break if environment['log_path']: environment['log_size_bytes'] = str( filetools.getsize(environment['log_path'])) environment['log_size'] = str(round(float(environment['log_size_bytes']) / \ (1024*1024), 3)) else: environment['log_size_bytes'] = '' environment['log_size'] = '' environment['debug'] = str(config.get_setting('debug')) environment['addon_version'] = '%s (Upd: %s h.)' % (str(config.get_addon_version()), \ str(config.get_setting("addon_update_timer", default=12)).replace('0', 'No')) environment['assistant_version'] = str(None) if filetools.exists( filetools.join(config.get_data_path(), 'alfa-mobile-assistant.version')): environment['assistant_version'] = filetools.read( filetools.join(config.get_data_path(), 'alfa-mobile-assistant.version')) environment['assistant_cf_ua'] = str( config.get_setting('cf_assistant_ua', None)) except: logger.error(traceback.format_exc()) environment = {} environment['log_size'] = '' environment['cpu_usage'] = '' environment['python_version'] = '' environment['log_path'] = '' environment['userdata_free'] = '' environment['mem_total'] = '' environment['machine'] = '' environment['platform'] = '' environment['videolab_path'] = '' environment['num_version'] = '' environment['os_name'] = '' environment['video_db'] = '' environment['userdata_path'] = '' environment['log_size_bytes'] = '' environment['name_version'] = '' environment['language'] = '' environment['mem_free'] = '' environment['prod_model'] = '' environment['proxy_active'] = '' environment['architecture'] = '' environment['os_release'] = '' environment['videolab_free'] = '' environment['kodi_buffer'] = '' environment['kodi_bmode'] = '' environment['kodi_rfactor'] = '' environment['videolab_series'] = '' environment['videolab_episodios'] = '' environment['videolab_pelis'] = '' environment['videolab_update'] = '' environment['videolab_path_perm'] = '' environment['debug'] = '' environment['addon_version'] = '' environment['torrent_list'] = [] environment['torrent_lang'] = '' environment['torrentcli_option'] = '' environment['torrentcli_rar'] = '' environment['torrentcli_lib_path'] = '' environment['torrentcli_unrar'] = '' environment['torrent_error'] = '' environment['assistant_version'] = '' environment['assistant_cf_ua'] = '' return environment
def 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
from core import ziptools from platformcode import config ### Alfa #__libbaseurl__ = "https://github.com/DiMartinoXBMC/script.module.libtorrent/raw/master/python_libtorrent" __libbaseurl__ = [ "https://github.com/DiMartinoXBMC/script.module.libtorrent/raw/master/python_libtorrent" ] #__settings__ = xbmcaddon.Addon(id='script.module.libtorrent') #__version__ = __settings__.getAddonInfo('version') #__plugin__ = __settings__.getAddonInfo('name') + " v." + __version__ #__icon__= filetools.join(filetools.translatePath('special://home'), 'addons', # 'script.module.libtorrent', 'icon.png') #__settings__ = xbmcaddon.Addon(id='plugin.video.alfa') ### Alfa __version__ = '2.0.2' ### Alfa __plugin__ = "python-libtorrent v.2.0.2" ### Alfa __icon__ = filetools.join(filetools.translatePath('special://home'), 'addons', 'plugin.video.alfa', 'icon.png') ### Alfa #__language__ = __settings__.getLocalizedString ### Alfa #from python_libtorrent.platform_pulsar import get_platform, get_libname ### Alfa from lib.python_libtorrent.python_libtorrent.platform_pulsar import get_platform, get_libname ### Alfa def log(msg): if PY3: try: xbmc.log("### [%s]: %s" % ( __plugin__, msg, ), level=xbmc.LOGINFO) except UnicodeEncodeError:
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(ADDON_PATH, "lib") alfa_addon_updates = filetools.join(alfa_addon_updates_mig, addon_name) #Está el addon activo? try: __settings__ = xbmcaddon.Addon(id="plugin.video." + addon_name) except: logger.error('Addon %s desactivado' % (addon_name.upper())) return True #Path de destino en addon externo if addon_name.lower() in ['quasar', 'elementum']: addon_path_root = filetools.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 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_script_alfa_update_helper(silent=True): logger.info() import json from core import ziptools from core import httptools from platformcode import xbmc_videolibrary addons_path = filetools.translatePath("special://home/addons") repos_dir = 'downloads/repos/' alfa_repo = ['repository.alfa-addon', '1.0.6', '*'] alfa_helper = ['script.alfa-update-helper', '0.0.6', '*'] torrest_repo = ['repository.github', '0.0.6', '*'] torrest_addon = 'plugin.video.torrest' futures_script = ['%sscript.module.futures' % repos_dir, '2.2.1', 'PY2'] try: versiones = config.get_versions_from_repo() except: versiones = {} logger.error(traceback.format_exc()) if not versiones: return repos = [futures_script, alfa_repo, torrest_repo] # Comprobamos si hay acceso a Github if not 'github' in versiones.get('url', '') or bool(xbmc.getCondVisibility("System.HasAddon(%s)" % alfa_helper[0])): repos += [alfa_helper] for addon_name, version, py in repos: if py != '*': if py == 'PY2' and PY3: continue if py == 'PY3' and not PY3: continue if repos_dir in addon_name: addonid = addon_name.replace(repos_dir, '') path_folder = repos_dir[:-1] else: addonid = addon_name path_folder = addonid new_version = versiones.get(addonid, version) package = addonid + '-%s.zip' % new_version filetools.remove(filetools.join('special://home', 'addons', 'packages', package), silent=silent) updated = bool(xbmc.getCondVisibility("System.HasAddon(%s)" % addonid)) if updated: installed_version = xbmc.getInfoLabel('System.AddonVersion(%s)' % addonid) if installed_version != new_version: updated = False if not updated: url_repo = '%s%s/%s' % (versiones.get('url', ''), path_folder, package) response = httptools.downloadpage(url_repo, 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') # Si el .zip es correcto los extraemos e instalamos try: unzipper = ziptools.ziptools() unzipper.extract(pkg_updated, addons_path, silent=silent) except: xbmc.executebuiltin('Extract("%s", "%s")' % (pkg_updated, addons_path)) time.sleep(1) logger.info("Installing %s" % package) try: 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)) except: logger.error(traceback.format_exc()) if versiones.get('addons_db', ''): repos = [(alfa_repo[0], alfa_repo[0]), (alfa_repo[0], ADDON_NAME), (alfa_repo[0], alfa_helper[0]), \ (torrest_repo[0], torrest_repo[0]), (torrest_repo[0], torrest_addon), \ ('repository.xbmc.org', futures_script[0].replace(repos_dir, ''))] try: for repo, addon in repos: sql = 'update installed set origin = "%s" where addonID = "%s" and origin <> "%s"' % (repo, addon, repo) nun_records, records = xbmc_videolibrary.execute_sql_kodi(sql, silent=silent, file_db=versiones['addons_db']) except: logger.error(traceback.format_exc()) addonid = ADDON_NAME new_version = versiones.get(addonid, ADDON_VERSION) updated = bool(xbmc.getCondVisibility("System.HasAddon(%s)" % addonid)) if updated: if ADDON_VERSION != new_version: def check_alfa_version(): logger.info(new_version) xbmc.executebuiltin('UpdateAddonRepos') for x in range(40): addon_version = config.get_addon_version(with_fix=False, from_xml=True) if addon_version == new_version: break time.sleep(2) if addon_version != new_version: logger.info("Notifying obsolete version %s ==> %s" % (addon_version, new_version), force=True) platformtools.dialog_notification("Alfa: versión oficial: [COLOR hotpink][B]%s[/B][/COLOR]" % new_version, \ "[COLOR yellow]Tienes una versión obsoleta: [B]%s[/B][/COLOR]" % addon_version) try: threading.Thread(target=check_alfa_version).start() time.sleep(1) except: logger.error(traceback.format_exc())
for folder in dest_path_dir: if 'arm' in folder or 'aarch' in folder: dest_path = filetools.join(dest_path, folder) break else: dest_path = '' if dest_path and filetools.exists(dest_path): dest_path = lm.android_workaround(dest_path) if not filetools.exists( filetools.join(dest_path, 'liblibtorrent.so')): dest_path = '' else: dest_path = '' if not dest_path: dest_path_ini = filetools.translatePath( 'special://xbmc/').replace('/cache/apk/assets', '') dest_path_dir = filetools.listdir(dest_path_ini, file_inf=True) log(dest_path_ini) log(dest_path_dir) if dest_path_dir: if filetools.exists( filetools.join(dest_path_ini, 'lib')): dest_path = lm.android_workaround( filetools.join(dest_path_ini, 'lib')) if not filetools.exists( filetools.join(dest_path, 'liblibtorrent.so')): if filetools.exists( os.environ['KODI_BINADDON_PATH']): dest_path = lm.android_workaround( os.environ['KODI_BINADDON_PATH'])
def verify_script_alfa_update_helper(): logger.info() import json from zipfile import ZipFile from core import httptools addonid = 'script.alfa-update-helper' package = addonid + '-0.0.1.zip' filetools.remove( filetools.join('special://home', 'addons', 'packages', package), True) # Comprobamos si hay acceso a Github url = 'https://github.com/alfa-addon/alfa-repo/raw/master/plugin.video.alfa/addon.xml' response = httptools.downloadpage(url, timeout=5, ignore_response_code=True, alfa_s=True) if response.code != 200 and not bool( xbmc.getCondVisibility("System.HasAddon(%s)" % addonid)): # Si no lo hay, descargamos el Script desde Bitbucket y lo salvamos a disco url = 'https://bitbucket.org/alfa_addon/alfa-repo/raw/master/script.alfa-update-helper/%s' % package response = httptools.downloadpage(url, ignore_response_code=True, alfa_s=True, json_to_utf8=False) if response.code == 200: zip_data = response.data addons_path = filetools.translatePath("special://home/addons") pkg_updated = filetools.join(addons_path, 'packages', package) res = filetools.write(pkg_updated, zip_data, mode='wb') # Verificamos el .zip ret = None try: with ZipFile(pkg_updated, "r") as zf: ret = zf.testzip() except Exception as e: ret = str(e) if ret is not None: logger.error("Corrupted .zip, error: %s" % (str(ret))) else: # Si el .zip es correcto los extraemos e instalamos with ZipFile(pkg_updated, "r") as zf: zf.extractall(addons_path) 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 add_sources(path): logger.info() from xml.dom import minidom SOURCES_PATH = filetools.translatePath("special://userdata/sources.xml") if os.path.exists(SOURCES_PATH): xmldoc = minidom.parse(SOURCES_PATH) else: # Crear documento xmldoc = minidom.Document() nodo_sources = xmldoc.createElement("sources") for type in ['programs', 'video', 'music', 'picture', 'files']: nodo_type = xmldoc.createElement(type) element_default = xmldoc.createElement("default") element_default.setAttribute("pathversion", "1") nodo_type.appendChild(element_default) nodo_sources.appendChild(nodo_type) xmldoc.appendChild(nodo_sources) # Buscamos el nodo video nodo_video = xmldoc.childNodes[0].getElementsByTagName("video")[0] # Buscamos el path dentro de los nodos_path incluidos en el nodo_video nodos_paths = nodo_video.getElementsByTagName("path") list_path = [p.firstChild.data for p in nodos_paths] logger.debug(list_path) if path in list_path: logger.debug("La ruta %s ya esta en sources.xml" % path) return logger.debug("La ruta %s NO esta en sources.xml" % path) # Si llegamos aqui es por q el path no esta en sources.xml, asi q lo incluimos nodo_source = xmldoc.createElement("source") # Nodo <name> nodo_name = xmldoc.createElement("name") sep = os.sep if path.startswith("special://") or scrapertools.find_single_match(path, '(^\w+:\/\/)'): sep = "/" name = path if path.endswith(sep): name = path[:-1] nodo_name.appendChild(xmldoc.createTextNode(name.rsplit(sep)[-1])) nodo_source.appendChild(nodo_name) # Nodo <path> nodo_path = xmldoc.createElement("path") nodo_path.setAttribute("pathversion", "1") nodo_path.appendChild(xmldoc.createTextNode(path)) nodo_source.appendChild(nodo_path) # Nodo <allowsharing> nodo_allowsharing = xmldoc.createElement("allowsharing") nodo_allowsharing.appendChild(xmldoc.createTextNode('true')) nodo_source.appendChild(nodo_allowsharing) # Añadimos <source> a <video> nodo_video.appendChild(nodo_source) # Guardamos los cambios if not PY3: filetools.write(SOURCES_PATH, '\n'.join([x for x in xmldoc.toprettyxml().encode("utf-8").splitlines() if x.strip()])) else: filetools.write(SOURCES_PATH, b'\n'.join([x for x in xmldoc.toprettyxml().encode("utf-8").splitlines() if x.strip()]), vfs=False)
def sync_trakt_addon(path_folder): """ Actualiza los valores de episodios vistos si """ logger.info() # si existe el addon hacemos la busqueda if xbmc.getCondVisibility('System.HasAddon("script.trakt")'): # importamos dependencias paths = ["special://home/addons/script.module.dateutil/lib/", "special://home/addons/script.module.six/lib/", "special://home/addons/script.module.arrow/lib/", "special://home/addons/script.module.trakt/lib/", "special://home/addons/script.trakt/"] for path in paths: sys.path.append(filetools.translatePath(path)) # se obtiene las series vistas try: from resources.lib.traktapi import traktAPI traktapi = traktAPI() except: return shows = traktapi.getShowsWatched({}) shows = list(shows.items()) # obtenemos el id de la serie para comparar _id = re.findall("\[(.*?)\]", path_folder, flags=re.DOTALL)[0] logger.debug("el id es %s" % _id) if "tt" in _id: type_id = "imdb" elif "tvdb_" in _id: _id = _id.strip("tvdb_") type_id = "tvdb" elif "tmdb_" in _id: type_id = "tmdb" _id = _id.strip("tmdb_") else: logger.error("No hay _id de la serie") return # obtenemos los valores de la serie from core import videolibrarytools tvshow_file = filetools.join(path_folder, "tvshow.nfo") head_nfo, serie = videolibrarytools.read_nfo(tvshow_file) # buscamos en las series de trakt for show in shows: show_aux = show[1].to_dict() try: _id_trakt = show_aux['ids'].get(type_id, None) # logger.debug("ID ES %s" % _id_trakt) if _id_trakt: if _id == _id_trakt: logger.debug("ENCONTRADO!! %s" % show_aux) # creamos el diccionario de trakt para la serie encontrada con el valor que tiene "visto" dict_trakt_show = {} for idx_season, season in enumerate(show_aux['seasons']): for idx_episode, episode in enumerate(show_aux['seasons'][idx_season]['episodes']): sea_epi = "%sx%s" % (show_aux['seasons'][idx_season]['number'], str(show_aux['seasons'][idx_season]['episodes'][idx_episode][ 'number']).zfill(2)) dict_trakt_show[sea_epi] = show_aux['seasons'][idx_season]['episodes'][idx_episode][ 'watched'] logger.debug("dict_trakt_show %s " % dict_trakt_show) # obtenemos las keys que son episodios regex_epi = re.compile('\d+x\d+') keys_episodes = [key for key in serie.library_playcounts if regex_epi.match(key)] # obtenemos las keys que son temporadas keys_seasons = [key for key in serie.library_playcounts if 'season ' in key] # obtenemos los numeros de las keys temporadas seasons = [key.strip('season ') for key in keys_seasons] # marcamos los episodios vistos for k in keys_episodes: serie.library_playcounts[k] = dict_trakt_show.get(k, 0) for season in seasons: episodios_temporada = 0 episodios_vistos_temporada = 0 # obtenemos las keys de los episodios de una determinada temporada keys_season_episodes = [key for key in keys_episodes if key.startswith("%sx" % season)] for k in keys_season_episodes: episodios_temporada += 1 if serie.library_playcounts[k] > 0: episodios_vistos_temporada += 1 # se comprueba que si todos los episodios están vistos, se marque la temporada como vista if episodios_temporada == episodios_vistos_temporada: serie.library_playcounts.update({"season %s" % season: 1}) temporada = 0 temporada_vista = 0 for k in keys_seasons: temporada += 1 if serie.library_playcounts[k] > 0: temporada_vista += 1 # se comprueba que si todas las temporadas están vistas, se marque la serie como vista if temporada == temporada_vista: serie.library_playcounts.update({serie.title: 1}) logger.debug("los valores nuevos %s " % serie.library_playcounts) res = videolibrarytools.write_nfo(tvshow_file, head_nfo, serie) break else: continue else: logger.error("no se ha podido obtener el id, trakt tiene: %s" % show_aux['ids']) except: import traceback logger.error(traceback.format_exc())
def set_content(content_type, silent=False): """ Procedimiento para auto-configurar la videoteca de kodi con los valores por defecto @type content_type: str ('movie' o 'tvshow') @param content_type: tipo de contenido para configurar, series o peliculas """ continuar = True msg_text = "" videolibrarypath = config.get_setting("videolibrarypath") if content_type == 'movie': scraper = [config.get_localized_string(70093), config.get_localized_string(70096)] seleccion = platformtools.dialog_select(config.get_localized_string(70094), scraper) # Instalar The Movie Database if seleccion == -1 or seleccion == 0: if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno(config.get_localized_string(60046)) else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin('InstallAddon(metadata.themoviedb.org)', True) logger.info("Instalado el Scraper de películas de TheMovieDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = config.get_localized_string(60047) if continuar: xbmc.executebuiltin('Addon.OpenSettings(metadata.themoviedb.org)', True) # Instalar Universal Movie Scraper elif seleccion == 1: if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.universal)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.universal install = platformtools.dialog_yesno(config.get_localized_string(70095)) else: install = True if install: try: xbmc.executebuiltin('InstallAddon(metadata.universal)', True) if xbmc.getCondVisibility('System.HasAddon(metadata.universal)'): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = config.get_localized_string(70097) if continuar: xbmc.executebuiltin('Addon.OpenSettings(metadata.universal)', True) else: # SERIES scraper = [config.get_localized_string(70098), config.get_localized_string(70093)] seleccion = platformtools.dialog_select(config.get_localized_string(70107), scraper) # Instalar The TVDB if seleccion == -1 or seleccion == 0: if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno(config.get_localized_string(60048)) else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin('InstallAddon(metadata.tvdb.com)', True) logger.info("Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = config.get_localized_string(70099) if continuar: xbmc.executebuiltin('Addon.OpenSettings(metadata.tvdb.com)', True) # Instalar The Movie Database elif seleccion == 1: if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno(config.get_localized_string(70100)) else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org xbmc.executebuiltin('InstallAddon(metadata.tvshows.themoviedb.org)', True) if xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = config.get_localized_string(60047) if continuar: xbmc.executebuiltin('Addon.OpenSettings(metadata.tvshows.themoviedb.org)', True) idPath = 0 idParentPath = 0 if continuar: continuar = False # Buscamos el idPath sql = 'SELECT MAX(idPath) FROM path' nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idPath = records[0][0] + 1 sql_videolibrarypath = videolibrarypath if sql_videolibrarypath.startswith("special://"): sql_videolibrarypath = sql_videolibrarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/') sep = '/' elif scrapertools.find_single_match(sql_videolibrarypath, '(^\w+:\/\/)'): sep = '/' else: sep = os.sep if not sql_videolibrarypath.endswith(sep): sql_videolibrarypath += sep # Buscamos el idParentPath sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_videolibrarypath nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idParentPath = records[0][0] videolibrarypath = records[0][1][:-1] continuar = True else: # No existe videolibrarypath en la BD: la insertamos sql_videolibrarypath = videolibrarypath if not sql_videolibrarypath.endswith(sep): sql_videolibrarypath += sep sql = 'INSERT INTO path (idPath, strPath, scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \ '(%s, "%s", 0, 0, 0, 0)' % (idPath, sql_videolibrarypath) nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True idParentPath = idPath idPath += 1 else: msg_text = config.get_localized_string(70101) if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == 'movie': strContent = 'movies' scanRecursive = 2147483647 useFolderNames = 1 if seleccion == -1 or seleccion == 0: strScraper = 'metadata.themoviedb.org' path_settings = filetools.translatePath("special://profile/addon_data/metadata.themoviedb.org/settings.xml") elif seleccion == 1: strScraper = 'metadata.universal' path_settings = filetools.translatePath("special://profile/addon_data/metadata.universal/settings.xml") settings_data = filetools.read(path_settings) strSettings = ' '.join(settings_data.split()).replace("> <", "><") strSettings = strSettings.replace("\"","\'") strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para películas?" if not videolibrarypath.endswith(sep): videolibrarypath += sep strPath = videolibrarypath + config.get_setting("folder_movies") + sep else: strContent = 'tvshows' scanRecursive = 0 useFolderNames = 0 if seleccion == -1 or seleccion == 0: strScraper = 'metadata.tvdb.com' path_settings = filetools.translatePath("special://profile/addon_data/metadata.tvdb.com/settings.xml") elif seleccion == 1: strScraper = 'metadata.tvshows.themoviedb.org' path_settings = filetools.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml") settings_data = filetools.read(path_settings) strSettings = ' '.join(settings_data.split()).replace("> <", "><") strSettings = strSettings.replace("\"","\'") strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para series?" if not videolibrarypath.endswith(sep): videolibrarypath += sep strPath = videolibrarypath + config.get_setting("folder_tvshows") + sep logger.info("%s: %s" % (content_type, strPath)) # Comprobamos si ya existe strPath en la BD para evitar duplicados sql = 'SELECT idPath FROM path where strPath="%s"' % strPath nun_records, records = execute_sql_kodi(sql) sql = "" if nun_records == 0: # Insertamos el scraper sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \ 'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, %s, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno(config.get_localized_string(70098), strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, useFolderNames=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, useFolderNames, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = config.get_localized_string(60055) if not continuar: heading = config.get_localized_string(70102) % content_type elif content_type == 'SERIES' and not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = config.get_localized_string(70103) % content_type msg_text = config.get_localized_string(60058) else: heading = config.get_localized_string(70103) % content_type msg_text = config.get_localized_string(70104) platformtools.dialog_notification(heading, msg_text, icon=1, time=3000) logger.info("%s: %s" % (heading, msg_text))
def faq(item): if item.extra == "onoff_canales": respuesta = platformtools.dialog_yesno("Alfa", "Esto se puede hacer en 'Configuración'>'Activar/Desactivar canales'. " "Puedes activar/desactivar los canales uno por uno o todos a la vez. ", "¿Deseas gestionar ahora los canales?") if respuesta == 1: from channels import setting setting.conf_tools(Item(extra='channels_onoff')) elif item.extra == "trakt_sync": respuesta = platformtools.dialog_yesno("Alfa", "Actualmente se puede activar la sincronización (silenciosa) " "tras marcar como visto un episodio (esto se hace automáticamente). " "Esta opción se puede activar en 'Configuración'>'Ajustes " "de la videoteca'.", "¿Deseas acceder a dichos ajustes?") if respuesta == 1: from channels import videolibrary videolibrary.channel_config(Item(channel='videolibrary')) elif item.extra == "tiempo_enlaces": respuesta = platformtools.dialog_yesno("Alfa", "Esto puede mejorarse limitando el número máximo de " "enlaces o mostrandolos en una ventana emergente. " "Estas opciones se encuentran en 'Configuración'>'Ajustes " "de la videoteca'.", "¿Deseas acceder a dichos ajustes?") if respuesta == 1: from channels import videolibrary videolibrary.channel_config(Item(channel='videolibrary')) elif item.extra == "prob_busquedacont": title = "Alfa - FAQ - %s" % item.title[6:] text = ("Puede que no hayas escrito la ruta de la librería correctamente en " "'Configuración'>'Preferencias'.\n" "La ruta específicada debe ser exactamente la misma de la 'fuente' " "introducida en 'Archivos' de la videoteca de Kodi.\n" "AVANZADO: Esta ruta también se encuentra en 'sources.xml'.\n" "También puedes estar experimentando problemas por estar " "usando algun fork de Kodi y rutas con 'special://'. " "SPMC, por ejemplo, tiene problemas con esto, y no parece tener solución, " "ya que es un problema ajeno a Alfa que existe desde hace mucho.\n" "Puedes intentar subsanar estos problemas en 'Configuración'>'Ajustes de " "la videoteca', cambiando el ajuste 'Realizar búsqueda de contenido en' " "de 'La carpeta de cada serie' a 'Toda la videoteca'." "También puedes acudir a 'http://alfa-addon.com' en busca de ayuda.") return TextBox("DialogTextViewer.xml", os.getcwd(), "Default", title=title, text=text) elif item.extra == "canal_fallo": title = "Alfa - FAQ - %s" % item.title[6:] text = ("Puede ser que la página web del canal no funcione. " "En caso de que funcione la página web puede que no seas el primero" " en haberlo visto y que el canal este arreglado. " "Puedes mirar en 'alfa-addon.com' o en el " "repositorio de GitHub (github.com/alfa-addon/addon). " "Si no encuentras el canal arreglado puedes reportar un " "problema en el foro.") return TextBox("DialogTextViewer.xml", os.getcwd(), "Default", title=title, text=text) elif item.extra == "prob_bib": platformtools.dialog_ok("Alfa", "Puede ser que hayas actualizado el plugin recientemente " "y que las actualizaciones no se hayan aplicado del todo " "bien. Puedes probar en 'Configuración'>'Otras herramientas', " "comprobando los archivos *_data.json o " "volviendo a añadir toda la videoteca.") respuesta = platformtools.dialog_yesno("Alfa", "¿Deseas acceder ahora a esa seccion?") if respuesta == 1: itemlist = [] from channels import setting new_item = Item(channel="setting", action="submenu_tools", folder=True) itemlist.extend(setting.submenu_tools(new_item)) return itemlist elif item.extra == "prob_torrent": title = "Alfa - FAQ - %s" % item.title[6:] text = ("Puedes probar descargando el modulo 'libtorrent' de Kodi o " "instalando algun addon como 'Quasar' o 'Torrenter', " "los cuales apareceran entre las opciones de la ventana emergente " "que aparece al pulsar sobre un enlace torrent. " "'Torrenter' es más complejo pero también más completo " "y siempre funciona.") return TextBox("DialogTextViewer.xml", os.getcwd(), "Default", title=title, text=text) elif item.extra == "buscador_juntos": respuesta = platformtools.dialog_yesno("Alfa", "Si. La opcion de mostrar los resultados juntos " "o divididos por canales se encuentra en " "'setting'>'Ajustes del buscador global'>" "'Otros ajustes'.", "¿Deseas acceder a ahora dichos ajustes?") if respuesta == 1: from channels import search search.settings("") elif item.extra == "report_error": from core import filetools if config.get_platform(True)['num_version'] < 14: log_name = "xbmc.log" else: log_name = "kodi.log" ruta = filetools.translatePath("special://logpath") + log_name title = "Alfa - FAQ - %s" % item.title[6:] text = ("Para reportar un problema en 'http://alfa-addon.com' es necesario:\n" " - Versión que usas de Alfa.\n" " - Versión que usas de kodi, mediaserver, etc.\n" " - Versión y nombre del sistema operativo que usas.\n" " - Nombre del skin (en el caso que uses Kodi) y si se " "te ha resuelto el problema al usar el skin por defecto.\n" " - Descripción del problema y algún caso de prueba.\n" " - Agregar el log en modo detallado, una vez hecho esto, " "zipea el log y lo puedes adjuntar en un post.\n\n" "Para activar el log en modo detallado, ingresar a:\n" " - Configuración.\n" " - Preferencias.\n" " - En la pestaña General - Marcar la opción: Generar log detallado.\n\n" "El archivo de log detallado se encuentra en la siguiente ruta: \n\n" "%s" % ruta) return TextBox("DialogTextViewer.xml", os.getcwd(), "Default", title=title, text=text) else: platformtools.dialog_ok("Alfa", "Entérate de novedades, consejos u opciones que desconoces en Telegram: @alfa_addon.\n" "Si tienes problemas o dudas, puedes acudir al Foro: http://alfa-addon.com")
import urllib.parse as urllib # Es muy lento en PY2. En PY3 es nativo else: import urllib # Usamos el nativo de PY2 que es más rápido import time from core import filetools from core import scrapertools from core.item import Item from platformcode import config, logger from platformcode import platformtools # Fijamos la ruta a favourites.xml if config.is_xbmc(): FAVOURITES_PATH = filetools.translatePath( "special://profile/favourites.xml") else: FAVOURITES_PATH = filetools.join(config.get_data_path(), "favourites.xml") def mainlist(item): logger.info() itemlist = [] for name, thumb, data in read_favourites(): if "plugin://plugin.video.%s/?" % config.PLUGIN_NAME in data: url = scrapertools.find_single_match(data, 'plugin://plugin.video.%s/\?([^;]*)' % config.PLUGIN_NAME) \ .replace(""", "") item = Item().fromurl(url) item.title = name
def __init__(self, url, path, filename=None, headers=[], resume=True, max_connections=10, block_size=2**17, part_size=2**24, max_buffer=10): # Parametros self._resume = resume self._path = path self._filename = filename self._max_connections = max_connections self._block_size = block_size self._part_size = part_size self._max_buffer = max_buffer try: self.tmp_path = filetools.translatePath("special://temp/") except: self.tmp_path = os.getenv("TEMP") or os.getenv("TMP") or os.getenv( "TMPDIR") self.states = type( 'states', (), { "stopped": 0, "connecting": 1, "downloading": 2, "completed": 3, "error": 4, "saving": 5 }) self._state = self.states.stopped self._download_lock = Lock() self._headers = { "User-Agent": "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013" } self._speed = 0 self._buffer = {} self._seekable = True self._threads = [ Thread(target=self.__start_part__, name="Downloader %s/%s" % (x + 1, self._max_connections)) for x in range(self._max_connections) ] self._speed_thread = Thread(target=self.__speed_metter__, name="Speed Meter") self._save_thread = Thread(target=self.__save_file__, name="File Writer") # Actualizamos los headers self._headers.update(dict(headers)) # Separamos los headers de la url self.__url_to_headers__(url) # Obtenemos la info del servidor self.__get_download_headers__() self._file_size = int(self.response_headers.get("content-length", "0")) if not self.response_headers.get( "accept-ranges") == "bytes" or self._file_size == 0: self._max_connections = 1 self._part_size = 0 self._resume = False # Obtenemos el nombre del archivo self.__get_download_filename__() # Abrimos en modo "a+" para que cree el archivo si no existe, luego en modo "r+b" para poder hacer seek() self.file = filetools.file_open(filetools.join(self._path, self._filename), "a+", vfs=VFS) if self.file: self.file.close() self.file = filetools.file_open(filetools.join(self._path, self._filename), "r+b", vfs=VFS) if not self.file: return if self._file_size >= 2**31 or not self._file_size: try: self.file.seek(2**31, 0) except OverflowError: self._seekable = False logger.info( "No se puede hacer seek() ni tell() en ficheros mayores de 2GB" ) self.__get_download_info__() try: logger.info("Descarga inicializada: Partes: %s | Ruta: %s | Archivo: %s | Tamaño: %s" % \ (str(len(self._download_info["parts"])), self._pathencode('utf-8'), \ self._filenameencode('utf-8'), str(self._download_info["size"]))) except: pass
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 = filetools.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 = filetools.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 = filetools.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 = filetools.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 = filetools.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 = filetools.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 = filetools.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