def update(): #download ZIP file start = time.clock() localfile = ROOT_DIR+"/update.zip" response = urllib2.urlopen(REMOTE_FILE_XML) html = response.read() remote_file = common.parseDOM(html,"file")[0].encode("utf-8") #remote version downloadtools.downloadfile(remote_file, localfile, notStop=False) end = time.clock() logger.info("org.harddevelop.kodi.tv Downloaded in %d seconds " % (end-start+1)) separatorChar = XBMCUtils.getSeparatorChar() #unzip unzipper = ziptools.ziptools() logger.info("org.harddevelop.kodi.tv destpathname=%s" % ROOT_DIR) addons_dir = XBMCUtils.getAddonsDir() current_plugin_dir = XBMCUtils.getPathFixedFrom(XBMCUtils.getAddonInfo('path')) logger.debug("using dir: "+addons_dir+" to extract content") unzipper.extractReplacingMainFolder(localfile,addons_dir,current_plugin_dir) #github issues #unzipper.extract(localfile,ROOT_DIR) #clean downloaded zip file logger.info("org.harddevelop.kodi.tv clean zip file...") os.remove(localfile) logger.info("org.harddevelop.kodi.tv clean done!")
def update(): #download ZIP file start = time.clock() localfile = ROOT_DIR+"/update.zip" response = urllib2.urlopen(REMOTE_FILE_XML) html = response.read() remote_file = common.parseDOM(html,"file")[0].encode("utf-8") #remote version downloadtools.downloadfile(remote_file, localfile, notStop=False) end = time.clock() logger.info("org.harddevelop.kodi.tv Downloaded in %d seconds " % (end-start+1)) separatorChar = "/" if xbmc.getCondVisibility( "system.platform.windows" ): logger.debug("Detected Windows system...") separatorChar = "\\" #unzip unzipper = ziptools.ziptools() logger.info("org.harddevelop.kodi.tv destpathname=%s" % ROOT_DIR) addons_dir = xbmc.translatePath(ROOT_DIR[:ROOT_DIR.rfind(separatorChar)+1]) current_plugin_dir = xbmc.translatePath(ROOT_DIR[ROOT_DIR.rfind(separatorChar)+1:]) logger.debug("using dir: "+addons_dir+" to extract content") unzipper.extractReplacingMainFolder(localfile,addons_dir,current_plugin_dir) #github issues #unzipper.extract(localfile,ROOT_DIR) #clean downloaded zip file logger.info("org.harddevelop.kodi.tv clean zip file...") os.remove(localfile) logger.info("org.harddevelop.kodi.tv clean done!")
def install(remote_file,id,folder): #first check if plexus exists, and where logger.info("installing "+id+"... ") addons_dir = XBMCUtils.getAddonsDir() logger.debug("Addons dir set to: "+addons_dir) localfile = ROOT_DIR+"/install.zip" downloadtools.downloadfile(remote_file, localfile, notStop=False) logger.debug("Download done, now it's time to unzip") unzipper = ziptools.ziptools() if folder == '': unzipper.extract(localfile,addons_dir) #github issues else: unzipper.extractReplacingMainFolder(localfile,addons_dir,folder) logger.debug("Unzip done! cleaning...") os.remove(localfile) logger.info("Additional addon clean done!")
def set_content(content_type, silent=False): """ Procedimiento para auto-configurar la biblioteca de kodi con los valores por defecto @type content_type: str ('CINE' o 'SERIES') @param content_type: tipo de contenido para configurar, series o peliculas """ if config.is_xbmc(): continuar = True msg_text = "" librarypath = config.get_setting("librarypath") if content_type == 'CINE': if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "TheMovieDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True) logger.info("Instalado el Scraper de películas de TheMovieDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = "The Movie Database no instalado." else: # SERIES # Instalar The TVDB if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno("The TVDB", "The TVDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True) logger.info("Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = "The TVDB no instalado." # Instalar TheMovieDB if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "TheMovieDB non presente.", "Installare ora?") else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org # 1º Probar desde el repositorio ... xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True) if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): # ...si no funciona descargar e instalar desde la web url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip" path_down = xbmc.translatePath( "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip") path_unzip = xbmc.translatePath("special://home/addons/") header = ("User-Agent", "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013") from core import downloadtools from core import ziptools downloadtools.downloadfile(url, path_down, continuar=True, headers=[header]) unzipper = ziptools.ziptools() unzipper.extract(path_down, path_unzip) xbmc.executebuiltin('UpdateLocalAddons') strSettings = '<settings>\n' \ ' <setting id="fanart" value="true" />\n' \ ' <setting id="keeporiginaltitle" value="false" />\n' \ ' <setting id="language" value="it" />\n' \ '</settings>' path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml") tv_themoviedb_addon_path = filetools.dirname(path_settings) if not filetools.exists(tv_themoviedb_addon_path): filetools.mkdir(tv_themoviedb_addon_path) if filetools.write(path_settings,strSettings): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = "The Movie Database non installato." idPath = 0 idParentPath = 0 strPath = "" if continuar: continuar = False # Buscamos el idPath sql = 'SELECT MAX(idPath) FROM path' nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idPath = records[0][0] + 1 sql_librarypath = librarypath if sql_librarypath.startswith("special://"): sql_librarypath = sql_librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/') sep = '/' elif sql_librarypath.startswith("smb://"): sep = '/' else: sep = os.sep if not sql_librarypath.endswith(sep): sql_librarypath += sep # Buscamos el idParentPath sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_librarypath nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idParentPath = records[0][0] librarypath = records[0][1][:-1] continuar = True else: # No existe librarypath en la BD: la insertamos sql_librarypath = librarypath if not sql_librarypath.endswith(sep): sql_librarypath += sep sql = 'INSERT INTO path (idPath, strPath, scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \ '(%s, "%s", 0, 0, 0, 0)' % (idPath, sql_librarypath) nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True idParentPath = idPath idPath += 1 else: msg_text = "Omesso di impostare LibraryPath in BD" if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == 'CINE': strContent = 'movies' strScraper = 'metadata.themoviedb.org' scanRecursive = 2147483647 strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \ "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \ "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \ "<setting id='trailer' value='true' /></settings>" strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per i film ?" if not librarypath.endswith(sep): librarypath += sep strPath = librarypath + config.get_setting("folder_movies") + sep else: strContent = 'tvshows' strScraper = 'metadata.tvdb.com' scanRecursive = 0 strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \ "<setting id='absolutenumber' value='false' />" \ "<setting id='dvdorder' value='false' />" \ "<setting id='fallback' value='true' />" \ "<setting id='fanart' value='true' />" \ "<setting id='language' value='it' /></settings>" strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per le serie ?" if not librarypath.endswith(sep): librarypath += sep strPath = librarypath + config.get_setting("folder_tvshows") + sep logger.info("%s: %s" % (content_type, strPath)) # Comprobamos si ya existe strPath en la BD para evitar duplicados sql = 'SELECT idPath FROM path where strPath="%s"' % strPath nun_records, records = execute_sql_kodi(sql) sql = "" if nun_records == 0: # Insertamos el scraper sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \ 'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno("The TVDB", strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = "Omesso impostare LibraryPath in BD" if not continuar: heading = "Biblioteca %s no configurada" % content_type elif content_type == 'SERIES' and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = "Biblioteca %s configurata" % content_type msg_text = "Riavviare Kodi per attuare le modifiche." else: heading = "Biblioteca %s configurata" % content_type msg_text = "Libreria di Kodi configurata correttamente." platformtools.dialog_notification(heading, msg_text, icon=1, time=10000) logger.info("%s: %s" % (heading,msg_text))
def set_content(content_type, silent=False): """ Procedimiento para auto-configurar la 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': if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "No se ha encontrado el Scraper de películas de TheMovieDB.", "¿Desea instalarlo ahora?") else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True) logger.info("Instalado el Scraper de películas de TheMovieDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = "The Movie Database no instalado." else: # SERIES # Instalar The TVDB if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno("The TVDB", "No se ha encontrado el Scraper de series de The TVDB.", "¿Desea instalarlo ahora?") else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True) logger.info("Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = "The TVDB no instalado." # Instalar TheMovieDB if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "No se ha encontrado el Scraper de series de TheMovieDB.", "¿Desea instalarlo ahora?") else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org # 1º Probar desde el repositorio ... xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True) if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): # ...si no funciona descargar e instalar desde la web url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip" path_down = xbmc.translatePath( "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip") path_unzip = xbmc.translatePath("special://home/addons/") header = ("User-Agent", "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013") from core import downloadtools from core import ziptools downloadtools.downloadfile(url, path_down, continuar=True, headers=[header]) unzipper = ziptools.ziptools() unzipper.extract(path_down, path_unzip) xbmc.executebuiltin('UpdateLocalAddons') strSettings = '<settings>\n' \ ' <setting id="fanart" value="true" />\n' \ ' <setting id="keeporiginaltitle" value="false" />\n' \ ' <setting id="language" value="es" />\n' \ '</settings>' path_settings = xbmc.translatePath( "special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml") tv_themoviedb_addon_path = filetools.dirname(path_settings) if not filetools.exists(tv_themoviedb_addon_path): filetools.mkdir(tv_themoviedb_addon_path) if filetools.write(path_settings, strSettings): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = "The Movie Database no instalado." idPath = 0 idParentPath = 0 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 sql_videolibrarypath.startswith("smb://"): 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 = "Error al fijar videolibrarypath en BD" if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == 'movie': strContent = 'movies' strScraper = 'metadata.themoviedb.org' scanRecursive = 2147483647 strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \ "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \ "<setting id='language' value='es' /><setting id='tmdbcertcountry' value='us' />" \ "<setting id='trailer' value='true' /></settings>" strActualizar = "¿Desea configurar este Scraper en español como opción por defecto para películas?" if not videolibrarypath.endswith(sep): videolibrarypath += sep strPath = videolibrarypath + config.get_setting("folder_movies") + sep else: strContent = 'tvshows' strScraper = 'metadata.tvdb.com' scanRecursive = 0 strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \ "<setting id='absolutenumber' value='false' />" \ "<setting id='dvdorder' value='false' />" \ "<setting id='fallback' value='true' />" \ "<setting id='fanart' value='true' />" \ "<setting id='language' value='es' /></settings>" 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, 0, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno("The TVDB", strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = "Error al configurar el scraper en la BD." if not continuar: heading = "Videoteca %s no configurada" % content_type elif content_type == 'SERIES' and not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = "Videoteca %s configurada" % content_type msg_text = "Es necesario reiniciar Kodi para que los cambios surtan efecto." else: heading = "Videoteca %s configurada" % content_type msg_text = "Felicidades la videoteca de Kodi ha sido configurada correctamente." platformtools.dialog_notification(heading, msg_text, icon=1, time=10000) logger.info("%s: %s" % (heading, msg_text))
def play( item ): #Permite preparar la descarga de los .torrents y subtítulos externos logger.info() itemlist = [] headers = [] from core import downloadtools from core import ziptools from core import filetools #buscamos la url del .torrent patron = '<tr><td align="(?:[^"]+)?"\s*class="(?:[^"]+)?"\s*width="(?:[^"]+)?">\s*Torrent:<\/td><td class="(?:[^"]+)?">\s*<img src="(?:[^"]+)?"\s*alt="(?:[^"]+)?"\s*border="(?:[^"]+)?"\s*\/>\s*<a onmouseover="(?:[^"]+)?"\s*onmouseout="(?:[^"]+)?" href="([^"]+)".*?<\/a>' try: data = re.sub(r"\n|\r|\t|\s{2}|(<!--.*?-->)", "", httptools.downloadpage(item.url, timeout=timeout).data) if not PY3: data = unicode(data, "utf-8", errors="replace").encode("utf-8") except: pass status, itemlist = check_blocked_IP( data, itemlist) #Comprobamos si la IP ha sido bloqueada if status: return itemlist #IP bloqueada if not scrapertools.find_single_match(data, patron): logger.error( 'ERROR 02: PLAY: No hay enlaces o ha cambiado la estructura de la Web. Verificar en la Web esto último y reportar el error con el log: PATRON: ' + patron + ' / DATA: ' + data) itemlist.append( item.clone( action='', title=item.channel.capitalize() + ': ERROR 02: PLAY: No hay enlaces o ha cambiado la estructura de la Web. Verificar en la Web esto último y reportar el error con el log' )) return itemlist item.url = urlparse.urljoin(host, scrapertools.find_single_match(data, patron)) #buscamos subtítulos en español patron = '<tr><td align="(?:[^"]+)?"\s*class="(?:[^"]+)?"\s*>\s*Subs.*?<\/td><td class="(?:[^"]+)?"\s*>(.*?)(?:<br\/>)?<\/td><\/tr>' data_subt = scrapertools.find_single_match(data, patron) if data_subt: patron = '<a href="([^"]+)"\s*onmouseover="return overlib\(' patron += "'Download Spanish subtitles'" patron += '\)"\s*onmouseout="(?:[^"]+)?"\s*><img src="(?:[^"]+)?"\s*><\/a>' subt = scrapertools.find_single_match(data_subt, patron) if subt: item.subtitle = urlparse.urljoin(host, subt) if item.subtitle: #Si hay urls de sub-títulos, se descargan headers.append(["User-Agent", httptools.get_user_agent() ]) #Se busca el User-Agent por defecto videolibrary_path = config.get_videolibrary_path( ) #Calculamos el path absoluto a partir de la Videoteca if videolibrary_path.lower().startswith( "smb://"): #Si es una conexión SMB, usamos userdata local videolibrary_path = config.get_data_path( ) #Calculamos el path absoluto a partir de Userdata videolibrary_path = filetools.join(videolibrary_path, "subtitles") #Primero se borra la carpeta de subtitulos para limpiar y luego se crea if filetools.exists(videolibrary_path): filetools.rmtree(videolibrary_path) time.sleep(1) if not filetools.exists(videolibrary_path): filetools.mkdir(videolibrary_path) subtitle_name = 'Rarbg-ES_SUBT.zip' #Nombre del archivo de sub-títulos subtitle_folder_path = filetools.join(videolibrary_path, subtitle_name) #Path de descarga ret = downloadtools.downloadfile(item.subtitle, subtitle_folder_path, headers=headers, continuar=True, silent=True) if filetools.exists(subtitle_folder_path): # Descomprimir zip dentro del addon # --------------------------------- try: unzipper = ziptools.ziptools() unzipper.extract(subtitle_folder_path, videolibrary_path) except: import xbmc xbmc.executebuiltin('Extract("%s", "%s")' % (subtitle_folder_path, videolibrary_path)) time.sleep(1) # Borrar el zip descargado # ------------------------ filetools.remove(subtitle_folder_path) #Tomo el primer archivo de subtítulos como valor por defecto for raiz, subcarpetas, ficheros in filetools.walk( videolibrary_path): for f in ficheros: if f.endswith(".srt"): #f_es = 'rarbg_subtitle.spa.srt' f_es = scrapertools.find_single_match( item.url, '&f=(.*?).torrent$').replace('.', ' ').replace( '-', ' ').lower() + '.spa.srt' if not f_es: f_es = item.infoLabels['originaltitle'] + '.spa.srt' f_es = f_es.replace(':', '').lower() filetools.rename( filetools.join(videolibrary_path, f), filetools.join(videolibrary_path, f_es)) item.subtitle = filetools.join( videolibrary_path, f_es) #Archivo de subtitulos break break itemlist.append(item.clone()) #Reproducción normal return itemlist
def check_addon_updates(verbose=False): logger.info() ADDON_UPDATES_JSON = 'https://extra.alfa-addon.com/addon_updates/updates.json' ADDON_UPDATES_ZIP = 'https://extra.alfa-addon.com/addon_updates/updates.zip' try: get_ua_list() except: pass try: last_fix_json = os.path.join(config.get_runtime_path(), 'last_fix.json') # información de la versión fixeada del usuario # Se guarda en get_runtime_path en lugar de get_data_path para que se elimine al cambiar de versión try: localfilename = os.path.join(config.get_data_path(), 'temp_updates.zip') if os.path.exists(localfilename): os.remove(localfilename) except: pass # Descargar json con las posibles actualizaciones # ----------------------------------------------- data = httptools.downloadpage(ADDON_UPDATES_JSON, timeout=5).data if data == '': logger.info('No se encuentran actualizaciones del addon') if verbose: platformtools.dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente') check_update_to_others(verbose=verbose) # Comprueba las actualuzaciones de otros productos return False data = jsontools.load(data) if 'addon_version' not in data or 'fix_version' not in data: logger.info('No hay actualizaciones del addon') if verbose: platformtools.dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente') check_update_to_others(verbose=verbose) # Comprueba las actualuzaciones de otros productos return False # Comprobar versión que tiene instalada el usuario con versión de la actualización # -------------------------------------------------------------------------------- current_version = config.get_addon_version(with_fix=False) if current_version != data['addon_version']: logger.info('No hay actualizaciones para la versión %s del addon' % current_version) if verbose: platformtools.dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente') check_update_to_others(verbose=verbose) # Comprueba las actualuzaciones de otros productos return False if os.path.exists(last_fix_json): try: lastfix = {} lastfix = jsontools.load(open(last_fix_json, "r").read()) if lastfix['addon_version'] == data['addon_version'] and lastfix['fix_version'] == data['fix_version']: logger.info('Ya está actualizado con los últimos cambios. Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) if verbose: platformtools.dialog_notification('Alfa ya está actualizado', 'Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) check_update_to_others(verbose=verbose) # Comprueba las actualuzaciones de otros productos return False except: if lastfix: logger.error('last_fix.json: ERROR en: ' + str(lastfix)) else: logger.error('last_fix.json: ERROR desconocido') lastfix = {} # Descargar zip con las actualizaciones # ------------------------------------- downloadtools.downloadfile(ADDON_UPDATES_ZIP, localfilename, silent=True) # Descomprimir zip dentro del addon # --------------------------------- try: unzipper = ziptools.ziptools() unzipper.extract(localfilename, config.get_runtime_path()) except: import xbmc xbmc.executebuiltin('Extract("%s", "%s")' % (localfilename, config.get_runtime_path())) time.sleep(1) # Borrar el zip descargado # ------------------------ try: os.remove(localfilename) except: pass # Guardar información de la versión fixeada # ----------------------------------------- if 'files' in data: data.pop('files', None) open(last_fix_json, "w").write(jsontools.dump(data)) logger.info('Addon actualizado correctamente a %s.fix%d' % (data['addon_version'], data['fix_version'])) if verbose: platformtools.dialog_notification('Alfa actualizado a', 'Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) check_update_to_others(verbose=verbose) # Comprueba las actualuzaciones de otros productos return True except: logger.error('Error al comprobar actualizaciones del addon!') logger.error(traceback.format_exc()) if verbose: platformtools.dialog_notification('Alfa actualizaciones', 'Error al comprobar actualizaciones') check_update_to_others(verbose=verbose) # Comprueba las actualuzaciones de otros productos return False
def actualiza(item): logger.info("deportesalacarta.channels.update_sports actualiza") local_folder = os.path.join(xbmc.translatePath("special://home"), "addons") error = False if not item.url: url = "https://github.com/CmosGit/Mod_pelisalacarta_deportes/raw/addon/plugin.video.deportesalacarta-%s.zip" % item.version else: import servertools urls, puede, msg = servertools.resolve_video_urls_for_playing( item.server, item.url, "", False, True) if puede: data_ = httptools.downloadpage(urls[0], hide=True).data url = scrapertools.find_single_match( data_, '"downloadUrl"\s*:\s*"([^"]+)"') if not url: url = scrapertools.find_single_match( data_, '<a id="download_button".*?href="([^"]+)"') if not item.server and not url: try: name, value = scrapertools.find_single_match( data_, 'method="post">.*?name="([^"]+)" value="([^"]+)"') post = "%s=%s" % (name, value) data_ = httptools.downloadpage(urls[0], post, hide=True).data url = scrapertools.find_single_match( data_, '"downloadUrl"\s*:\s*"([^"]+)"') except: pass if not url: urls, puede, msg = servertools.resolve_video_urls_for_playing( item.server, base64.b64decode(item.url)) url = urls[0][1] progreso = platformtools.dialog_progress("Progreso de la actualización", "Descargando...") filename = 'deportesalacarta-%s.zip' % item.version localfilename = filetools.join(config.get_data_path(), filename) try: result = downloadtools.downloadfile(url, localfilename, [], False, True, False) progreso.update(50, "Descargando archivo", "Descargando...") # Lo descomprime logger.info( "deportesalacarta.channels.configuracion descomprime fichero...") from core import ziptools unzipper = ziptools.ziptools() logger.info("deportesalacarta.channels.configuracion destpathname=%s" % local_folder) unzipper.extract(localfilename, local_folder, update=True) progreso.close() except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) # Borra el zip descargado try: filetools.remove(localfilename) except: pass progreso.close() platformtools.dialog_ok( "Error", "Se ha producido un error extrayendo el archivo") return # Borra el zip descargado logger.info("deportesalacarta.channels.configuracion borra fichero...") try: filetools.remove(localfilename) except: pass logger.info("deportesalacarta.channels.configuracion ...fichero borrado") platformtools.dialog_notification( "Actualizado correctamente", "Versión %s instalada con éxito" % item.version) xbmc.executebuiltin("Container.Refresh")
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://bitbucket.org/alfa_addon/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')), \ 'custom_code', 'lib', libname) ### Alfa filetools.copy(dest, dest_alfa, silent=True) ### Alfa break else: return False return True
def establecer_contenido(content_type, silent=False): if config.is_xbmc(): continuar = False msg_text = "Cartella Libreria personalizzata" librarypath = config.get_setting("librarypath") if librarypath == "": continuar = True if content_type == FOLDER_MOVIES: if not xbmc.getCondVisibility( 'System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno( "The Movie Database", "TheMovieDB. non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin( 'xbmc.installaddon(metadata.themoviedb.org)', True) logger.info( "Instalado el Scraper de películas de TheMovieDB" ) except: pass continuar = (install and xbmc.getCondVisibility( 'System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = "The Movie Database non installato." else: # SERIES # Instalar The TVDB if not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno( "The TVDB", "The TVDB non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin( 'xbmc.installaddon(metadata.tvdb.com)', True) logger.info( "Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility( 'System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = "The TVDB non installato." # Instalar TheMovieDB if continuar and not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno( "The Movie Database", "TheMovieDB non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org # 1º Probar desde el repositorio ... xbmc.executebuiltin( 'xbmc.installaddon(metadata.tvshows.themoviedb.org)', True) if not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)' ): # ...si no funciona descargar e instalar desde la web url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip" path_down = xbmc.translatePath( "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip" ) path_unzip = xbmc.translatePath( "special://home/addons/") header = ( "User-Agent", "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013" ) from core import downloadtools from core import ziptools downloadtools.downloadfile(url, path_down, continuar=True, headers=[header]) unzipper = ziptools.ziptools() unzipper.extract(path_down, path_unzip) xbmc.executebuiltin('xbmc.UpdateLocalAddons') strSettings = '<settings>\n' \ ' <setting id="fanart" value="true" />\n' \ ' <setting id="keeporiginaltitle" value="false" />\n' \ ' <setting id="language" value="it" />\n' \ '</settings>' path_settings = xbmc.translatePath( "special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml" ) tv_themoviedb_addon_path = filetools.dirname( path_settings) if not filetools.exists(tv_themoviedb_addon_path): filetools.mkdir(tv_themoviedb_addon_path) if filetools.write(path_settings, strSettings): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = "The Movie Database non installato." idPath = 0 idParentPath = 0 strPath = "" if continuar: continuar = False librarypath = "special://home/userdata/addon_data/plugin.video." + config.PLUGIN_NAME + "/library/" # Buscamos el idPath sql = 'SELECT MAX(idPath) FROM path' nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idPath = records[0][0] + 1 # Buscamos el idParentPath sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % \ librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/') nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idParentPath = records[0][0] librarypath = records[0][1] continuar = True else: # No existe librarypath en la BD: la insertamos sql = 'INSERT INTO path (idPath, strPath, scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \ '(%s, "%s", 0, 0, 0, 0)' % (idPath, librarypath) nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True idParentPath = idPath idPath += 1 else: msg_text = "Impossibile impostare librarypath in BD" if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == FOLDER_MOVIES: strContent = 'movies' strScraper = 'metadata.themoviedb.org' scanRecursive = 2147483647 strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \ "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \ "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \ "<setting id='trailer' value='true' /></settings>" strActualizar = "Configurare lo scraper per i film in italiano?" else: strContent = 'tvshows' strScraper = 'metadata.tvdb.com' scanRecursive = 0 strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \ "<setting id='absolutenumber' value='false' />" \ "<setting id='dvdorder' value='false' />" \ "<setting id='fallback' value='true' />" \ "<setting id='fanart' value='true' />" \ "<setting id='language' value='it' /></settings>" strActualizar = "Configurare lo scraper per le serie in italiano?" # Fijamos strPath strPath = librarypath + content_type + "/" logger.info("%s: %s" % (content_type, strPath)) # Comprobamos si ya existe strPath en la BD para evitar duplicados sql = 'SELECT idPath FROM path where strPath="%s"' % strPath nun_records, records = execute_sql_kodi(sql) sql = "" if nun_records == 0: # Insertamos el scraper sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \ 'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno( "The TVDB", strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = "Error al configurar el scraper en la BD." if not continuar: heading = "Libreria non %s configurata" % content_type #msg_text = "Assicurarsi di aver installato l'add-on The Movie Database" elif content_type == FOLDER_TVSHOWS and not xbmc.getCondVisibility( 'System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = "Libreria %s configurata" % content_type msg_text = "Kodi deve essere riavviato affinché le modifiche abbiano effetto." else: heading = "Libreria %s configurata" % content_type msg_text = "Complimenti la libreria di Kodi è stata configurata correttamente." platformtools.dialog_notification(heading, msg_text, icon=1, time=10000) logger.info("%s: %s" % (heading, msg_text))
def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=10, lookup=False, data_torrent=False): if torrents_path != None: logger.info("path = " + torrents_path) else: logger.info() if referer and post: logger.info('REFERER: ' + referer) import urllib import re from core import httptools torrent_file = '' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': referer } #Necesario para el Post del .Torrent """ Descarga en el path recibido el .torrent de la url recibida, y pasa el decode Devuelve el path real del .torrent, o el path vacío si la operación no ha tenido éxito """ videolibrary_path = config.get_videolibrary_path( ) #Calculamos el path absoluto a partir de la Videoteca if torrents_path == None: if not videolibrary_path: torrents_path = '' if data_torrent: return (torrents_path, torrent_file) return torrents_path #Si hay un error, devolvemos el "path" vacío torrents_path = filetools.join( videolibrary_path, 'temp_torrents_Alfa', 'cliente_torrent_Alfa.torrent') #path de descarga temporal if '.torrent' not in torrents_path: torrents_path += '.torrent' #path para dejar el .torrent torrents_path_encode = filetools.encode( torrents_path) #encode utf-8 del path if url.endswith(".rar") or url.startswith( "magnet:"): #No es un archivo .torrent logger.error('No es un archivo Torrent: ' + url) torrents_path = '' if data_torrent: return (torrents_path, torrent_file) return torrents_path #Si hay un error, devolvemos el "path" vacío try: #Descargamos el .torrent if referer and post: #Descarga con POST response = httptools.downloadpage(url, headers=headers, post=post, follow_redirects=False, timeout=timeout) else: #Descarga sin post response = httptools.downloadpage(url, timeout=timeout) if not response.sucess: logger.error('Archivo .torrent no encontrado: ' + url) torrents_path = '' if data_torrent: return (torrents_path, torrent_file) return torrents_path #Si hay un error, devolvemos el "path" vacío torrent_file = response.data if "used CloudFlare" in torrent_file: #Si tiene CloudFlare, usamos este proceso response = httptools.downloadpage( "http://anonymouse.org/cgi-bin/anon-www.cgi/" + url.strip(), timeout=timeout) if not response.sucess: logger.error('Archivo .torrent no encontrado: ' + url) torrents_path = '' if data_torrent: return (torrents_path, torrent_file) return torrents_path #Si hay un error, devolvemos el "path" vacío torrent_file = response.data #Si es un archivo .ZIP tratamos de extraer el contenido if torrent_file.startswith("PK"): logger.info('Es un archivo .ZIP: ' + url) torrents_path_zip = filetools.join( videolibrary_path, 'temp_torrents_zip') #Carpeta de trabajo torrents_path_zip = filetools.encode(torrents_path_zip) torrents_path_zip_file = filetools.join( torrents_path_zip, 'temp_torrents_zip.zip') #Nombre del .zip import time filetools.rmdirtree( torrents_path_zip) #Borramos la carpeta temporal time.sleep(1) #Hay que esperar, porque si no da error filetools.mkdir(torrents_path_zip) #La creamos de nuevo if filetools.write(torrents_path_zip_file, torrent_file): #Salvamos el .zip torrent_file = '' #Borramos el contenido en memoria try: #Extraemos el .zip from core import ziptools unzipper = ziptools.ziptools() unzipper.extract(torrents_path_zip_file, torrents_path_zip) except: import xbmc xbmc.executebuiltin( 'XBMC.Extract("%s", "%s")' % (torrents_path_zip_file, torrents_path_zip)) time.sleep(1) import os for root, folders, files in os.walk( torrents_path_zip ): #Recorremos la carpeta para leer el .torrent for file in files: if file.endswith(".torrent"): input_file = filetools.join( root, file) #nombre del .torrent torrent_file = filetools.read( input_file) #leemos el .torrent filetools.rmdirtree( torrents_path_zip) #Borramos la carpeta temporal #Si no es un archivo .torrent (RAR, HTML,..., vacío) damos error if not scrapertools.find_single_match(torrent_file, '^d\d+:.*?\d+:'): logger.error('No es un archivo Torrent: ' + url) torrents_path = '' if data_torrent: return (torrents_path, torrent_file) return torrents_path #Si hay un error, devolvemos el "path" vacío #Salvamos el .torrent if not lookup: if not filetools.write(torrents_path_encode, torrent_file): logger.error('ERROR: Archivo .torrent no escrito: ' + torrents_path_encode) torrents_path = '' #Si hay un error, devolvemos el "path" vacío torrent_file = '' #... y el buffer del .torrent if data_torrent: return (torrents_path, torrent_file) return torrents_path except: torrents_path = '' #Si hay un error, devolvemos el "path" vacío torrent_file = '' #... y el buffer del .torrent logger.error('Error en el proceso de descarga del .torrent: ' + url + ' / ' + torrents_path_encode) logger.error(traceback.format_exc()) #logger.debug(torrents_path) if data_torrent: return (torrents_path, torrent_file) return torrents_path
def play( item ): #Permite preparar la descarga de los .torrents y subtítulos externos logger.info() itemlist = [] headers = [] from core import downloadtools from core import ziptools from core import filetools #buscamos la url del .torrent patron = '<tr><td align="(?:[^"]+)?"\s*class="(?:[^"]+)?"\s*width="(?:[^"]+)?">' patron += '\s*Torrent:<\/td><td class="(?:[^"]+)?">\s*<img src="(?:[^"]+)?"\s*' patron += 'alt="(?:[^"]+)?"\s*border="(?:[^"]+)?"\s*\/>\s*<a onmouseover="' patron += '(?:[^"]+)?"\s*onmouseout="(?:[^"]+)?" href="([^"]+)".*?<\/a>' data, response, item, itemlist = generictools.downloadpage( item.url, timeout=timeout, patron=patron, item=item, itemlist=[], quote_rep=False, check_blocked_IP=True) if not data or response.code in [ 999, 99 ]: # Si ERROR o lista de errores lo reintentamos con otro Host return itemlist # ... Salimos item.url = urlparse.urljoin(host, scrapertools.find_single_match(data, patron)) #buscamos subtítulos en español patron = '<tr><td align="(?:[^"]+)?"\s*class="(?:[^"]+)?"\s*>\s*Subs.*?<\/td><td class="(?:[^"]+)?"\s*>(.*?)(?:<br\/>)?<\/td><\/tr>' data_subt = scrapertools.find_single_match(data, patron) if data_subt: patron = '<a href="([^"]+)"\s*onmouseover="return overlib\(' patron += "'Download Spanish subtitles'" patron += '\)"\s*onmouseout="(?:[^"]+)?"\s*><img src="(?:[^"]+)?"\s*><\/a>' subt = scrapertools.find_single_match(data_subt, patron) if subt: item.subtitle = urlparse.urljoin(host, subt) if item.subtitle: #Si hay urls de sub-títulos, se descargan from core import httptools headers.append(["User-Agent", httptools.get_user_agent() ]) #Se busca el User-Agent por defecto videolibrary_path = config.get_videolibrary_path( ) #Calculamos el path absoluto a partir de la Videoteca if videolibrary_path.lower().startswith( "smb://"): #Si es una conexión SMB, usamos userdata local videolibrary_path = config.get_data_path( ) #Calculamos el path absoluto a partir de Userdata videolibrary_path = filetools.join(videolibrary_path, "subtitles") #Primero se borra la carpeta de subtitulos para limpiar y luego se crea if filetools.exists(videolibrary_path): filetools.rmtree(videolibrary_path) time.sleep(1) if not filetools.exists(videolibrary_path): filetools.mkdir(videolibrary_path) subtitle_name = 'Rarbg-ES_SUBT.zip' #Nombre del archivo de sub-títulos subtitle_folder_path = filetools.join(videolibrary_path, subtitle_name) #Path de descarga ret = downloadtools.downloadfile(item.subtitle, subtitle_folder_path, headers=headers, continuar=True, silent=True) if filetools.exists(subtitle_folder_path): # Descomprimir zip dentro del addon # --------------------------------- try: unzipper = ziptools.ziptools() unzipper.extract(subtitle_folder_path, videolibrary_path) except: import xbmc xbmc.executebuiltin('Extract("%s", "%s")' % (subtitle_folder_path, videolibrary_path)) time.sleep(1) # Borrar el zip descargado # ------------------------ filetools.remove(subtitle_folder_path) #Tomo el primer archivo de subtítulos como valor por defecto for raiz, subcarpetas, ficheros in filetools.walk( videolibrary_path): for f in ficheros: if f.endswith(".srt"): #f_es = 'rarbg_subtitle.spa.srt' f_es = scrapertools.find_single_match( item.url, '&f=(.*?).torrent$').replace('.', ' ').replace( '-', ' ').lower() + '.spa.srt' if not f_es: f_es = item.infoLabels['originaltitle'] + '.spa.srt' f_es = f_es.replace(':', '').lower() filetools.rename( filetools.join(videolibrary_path, f), filetools.join(videolibrary_path, f_es)) item.subtitle = filetools.join( videolibrary_path, f_es) #Archivo de subtitulos break break itemlist.append(item.clone()) #Reproducción normal return itemlist
def verify_script_alfa_update_helper(): 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.5', '*'] 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 addonid = alfa_helper[0] new_version = versiones.get(addonid, alfa_helper[1]) package = addonid + '-%s.zip' % new_version filetools.remove(filetools.join('special://home', 'addons', 'packages', package), silent=True) 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 # Comprobamos si hay acceso a Github if not 'github' in versiones.get('url', '') and not updated: # Si no lo hay, descargamos el Script desde GitLab y lo salvamos a disco 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') # Si el .zip es correcto los extraemos e instalamos try: unzipper = ziptools.ziptools() unzipper.extract(pkg_updated, addons_path) except: xbmc.executebuiltin('Extract("%s", "%s")' % (pkg_updated, addons_path)) time.sleep(1) 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) repos = [futures_script, alfa_repo, torrest_repo] 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=True) 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) 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()) file_db = '' for f in sorted(filetools.listdir("special://userdata/Database"), reverse=True): path_f = filetools.join("special://userdata/Database", f) if filetools.isfile(path_f) and f.lower().startswith( 'addons') and f.lower().endswith('.db'): file_db = path_f break if file_db: repos = [(alfa_repo[0], alfa_repo[0]), (alfa_repo[0], ADDON_NAME), (alfa_repo[0], alfa_helper), \ (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=True, file_db=file_db) except: logger.error(traceback.format_exc()) addonid = ADDON_NAME new_version = versiones.get(addonid, ADDON_VERSION) package = addonid + '-%s.zip' % new_version filetools.remove(filetools.join('special://home', 'addons', 'packages', package), silent=True) 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())
def addchannel(item): import os import time logger.info() tecleado = platformtools.dialog_input("", "Inserire l'URL") if not tecleado: return logger.info("url=%s" % tecleado) local_folder = config.get_runtime_path() if "canal" in item.title: local_folder = filetools.join(local_folder, 'channels') folder_to_extract = "channels" info_accion = "canal" else: local_folder = filetools.join(local_folder, 'servers') folder_to_extract = "servers" info_accion = "conector" # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github) try: extension = tecleado.rsplit(".", 1)[1] except: extension = "" files = [] zip = False if extension == "py" or extension == "xml": filename = tecleado.rsplit("/", 1)[1] localfilename = filetools.join(local_folder, filename) files.append([tecleado, localfilename, filename]) else: import re from core import scrapertools # Comprueba si la url apunta a una carpeta completa (channels o servers) de github if re.search(r'https://github.com/[^\s]+/' + folder_to_extract, tecleado): try: data = scrapertools.downloadpage(tecleado) matches = scrapertools.find_multiple_matches( data, '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"') for url, filename in matches: url = "https://raw.githubusercontent.com" + url.replace( "/blob/", "/") localfilename = filetools.join(local_folder, filename) files.append([url, localfilename, filename]) except: import traceback logger.error("Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_ok( "Errore", "L'URL non è corretto o non disponibile") return else: filename = 'new%s.zip' % info_accion localfilename = filetools.join(config.get_data_path(), filename) files.append([tecleado, localfilename, filename]) zip = True logger.info("localfilename=%s" % localfilename) logger.info("descarga fichero...") try: if len(files) > 1: lista_opciones = ["No", "Si", "Si (Sovrascrivere tutto)"] overwrite_all = False from core import downloadtools for url, localfilename, filename in files: result = downloadtools.downloadfile(url, localfilename, continuar=False) if result == -3: if len(files) == 1: dyesno = platformtools.dialog_yesno( "Il file esiste già", "%s %s esiste già. " "Vuoi sovrascrivere?" % (info_accion, filename)) else: if not overwrite_all: dyesno = platformtools.dialog_select( "Il file %s esiste già, vuoi sovrascrivere?" % filename, lista_opciones) else: dyesno = 1 # Diálogo cancelado if dyesno == -1: return # Caso de carpeta github, opción sobrescribir todos elif dyesno == 2: overwrite_all = True elif dyesno: 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): os.makedirs(backup) import shutil shutil.copy2(localfilename, filetools.join(backup, filename)) downloadtools.downloadfile(url, localfilename, continuar=True) else: if len(files) == 1: return else: continue except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) return if zip: try: # Lo descomprime logger.info("descomprime fichero...") from core import ziptools unzipper = ziptools.ziptools() logger.info("destpathname=%s" % local_folder) unzipper.extract(localfilename, local_folder, folder_to_extract, True, True) except: import traceback logger.error("Detalle del error: %s" % traceback.format_exc()) # Borra el zip descargado filetools.remove(localfilename) platformtools.dialog_ok( "Errore", "C'è stato un errore nell'estrazione del file") return # Borra el zip descargado logger.info("borra fichero...") filetools.remove(localfilename) logger.info("...fichero borrado") platformtools.dialog_ok( "Successo", "Aggiornamento/installazione eseguita correttamente")
def check_addon_updates(verbose=False): logger.info() ADDON_UPDATES_JSON = 'http://extra.alfa-addon.com/addon_updates/updates.json' ADDON_UPDATES_ZIP = 'http://extra.alfa-addon.com/addon_updates/updates.zip' try: last_fix_json = os.path.join( config.get_runtime_path(), 'last_fix.json') # información de la versión fixeada del usuario # Se guarda en get_runtime_path en lugar de get_data_path para que se elimine al cambiar de versión # Descargar json con las posibles actualizaciones # ----------------------------------------------- data = httptools.downloadpage(ADDON_UPDATES_JSON, timeout=2).data if data == '': logger.info('No se encuentran actualizaciones del addon') if verbose: platformtools.dialog_notification( 'Alfa ya está actualizado', 'No hay ninguna actualización urgente') return False data = jsontools.load(data) if 'addon_version' not in data or 'fix_version' not in data: logger.info('No hay actualizaciones del addon') if verbose: platformtools.dialog_notification( 'Alfa ya está actualizado', 'No hay ninguna actualización urgente') return False # Comprobar versión que tiene instalada el usuario con versión de la actualización # -------------------------------------------------------------------------------- current_version = config.get_addon_version(with_fix=False) if current_version != data['addon_version']: logger.info('No hay actualizaciones para la versión %s del addon' % current_version) if verbose: platformtools.dialog_notification( 'Alfa ya está actualizado', 'No hay ninguna actualización urgente') return False if os.path.exists(last_fix_json): lastfix = jsontools.load(filetools.read(last_fix_json)) if lastfix['addon_version'] == data['addon_version'] and lastfix[ 'fix_version'] == data['fix_version']: logger.info( 'Ya está actualizado con los últimos cambios. Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) if verbose: platformtools.dialog_notification( 'Alfa ya está actualizado', 'Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) return False # Descargar zip con las actualizaciones # ------------------------------------- localfilename = os.path.join(config.get_data_path(), 'temp_updates.zip') if os.path.exists(localfilename): os.remove(localfilename) downloadtools.downloadfile(ADDON_UPDATES_ZIP, localfilename, silent=True) # Descomprimir zip dentro del addon # --------------------------------- unzipper = ziptools.ziptools() unzipper.extract(localfilename, config.get_runtime_path()) # Borrar el zip descargado # ------------------------ os.remove(localfilename) # Guardar información de la versión fixeada # ----------------------------------------- if 'files' in data: data.pop('files', None) filetools.write(last_fix_json, jsontools.dump(data)) logger.info('Addon actualizado correctamente a %s.fix%d' % (data['addon_version'], data['fix_version'])) if verbose: platformtools.dialog_notification( 'Alfa actualizado a', 'Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) return True except: logger.error('Error al comprobar actualizaciones del addon!') if verbose: platformtools.dialog_notification( 'Alfa actualizaciones', 'Error al comprobar actualizaciones') return False
def addchannel(item): from platformcode import platformtools import time, os logger.info("pelisalacarta.channels.configuracion addchannel") tecleado = platformtools.dialog_input("", "Introduzca la URL") if not tecleado: return logger.info("pelisalacarta.channels.configuracion url=%s" % tecleado) local_folder = config.get_runtime_path() if "canal" in item.title: local_folder = filetools.join(local_folder, "channels") folder_to_extract = "channels" info_accion = "canal" else: local_folder = filetools.join(local_folder, "servers") folder_to_extract = "servers" info_accion = "conector" # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github) try: extension = tecleado.rsplit(".", 1)[1] except: extension = "" files = [] zip = False if extension == "py" or extension == "xml": filename = tecleado.rsplit("/", 1)[1] localfilename = filetools.join(local_folder, filename) files.append([tecleado, localfilename, filename]) else: import re from core import scrapertools # Comprueba si la url apunta a una carpeta completa (channels o servers) de github if re.search(r"https://github.com/[^\s]+/" + folder_to_extract, tecleado): try: data = scrapertools.downloadpage(tecleado) matches = scrapertools.find_multiple_matches( data, '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"' ) for url, filename in matches: url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/") localfilename = filetools.join(local_folder, filename) files.append([url, localfilename, filename]) except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_ok("Error", "La url no es correcta o no está disponible") return else: filename = "new%s.zip" % info_accion localfilename = filetools.join(config.get_data_path(), filename) files.append([tecleado, localfilename, filename]) zip = True logger.info("pelisalacarta.channels.configuracion localfilename=%s" % localfilename) logger.info("pelisalacarta.channels.configuracion descarga fichero...") try: if len(files) > 1: lista_opciones = ["No", "Sí", "Sí (Sobrescribir todos)"] overwrite_all = False from core import downloadtools for url, localfilename, filename in files: result = downloadtools.downloadfile(url, localfilename, continuar=False) if result == -3: if len(files) == 1: dyesno = platformtools.dialog_yesno( "El archivo ya existe", "Ya existe el %s %s." " ¿Desea sobrescribirlo?" % (info_accion, filename), ) else: if not overwrite_all: dyesno = platformtools.dialog_select( "El archivo %s ya existe, ¿desea sobrescribirlo?" % filename, lista_opciones ) else: dyesno = 1 # Diálogo cancelado if dyesno == -1: return # Caso de carpeta github, opción sobrescribir todos elif dyesno == 2: overwrite_all = True elif dyesno: hora_folder = "Copia seguridad [%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): os.makedirs(backup) import shutil shutil.copy2(localfilename, filetools.join(backup, filename)) result = downloadtools.downloadfile(url, localfilename, continuar=True) else: if len(files) == 1: return else: continue except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) return if zip: try: # Lo descomprime logger.info("pelisalacarta.channels.configuracion descomprime fichero...") from core import ziptools unzipper = ziptools.ziptools() logger.info("pelisalacarta.channels.configuracion destpathname=%s" % local_folder) unzipper.extract(localfilename, local_folder, folder_to_extract, True, True) except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) # Borra el zip descargado filetools.remove(localfilename) platformtools.dialog_ok("Error", "Se ha producido un error extrayendo el archivo") return # Borra el zip descargado logger.info("pelisalacarta.channels.configuracion borra fichero...") filetools.remove(localfilename) logger.info("pelisalacarta.channels.configuracion ...fichero borrado") platformtools.dialog_ok("Éxito", "Actualización/Instalación realizada correctamente")
def addchannel(item): from platformcode import platformtools import os import time logger.info() tecleado = platformtools.dialog_input("", "Inserire l'URL") if not tecleado: return logger.info("url=%s" % tecleado) local_folder = config.get_runtime_path() if "canal" in item.title: local_folder = filetools.join(local_folder, 'channels') folder_to_extract = "channels" info_accion = "canal" else: local_folder = filetools.join(local_folder, 'servers') folder_to_extract = "servers" info_accion = "conector" # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github) try: extension = tecleado.rsplit(".", 1)[1] except: extension = "" files = [] zip = False if extension == "py" or extension == "xml": filename = tecleado.rsplit("/", 1)[1] localfilename = filetools.join(local_folder, filename) files.append([tecleado, localfilename, filename]) else: import re from core import scrapertools # Comprueba si la url apunta a una carpeta completa (channels o servers) de github if re.search(r'https://github.com/[^\s]+/'+folder_to_extract, tecleado): try: data = scrapertools.downloadpage(tecleado) matches = scrapertools.find_multiple_matches(data, '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"') for url, filename in matches: url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/") localfilename = filetools.join(local_folder, filename) files.append([url, localfilename, filename]) except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_ok("Errore", "L'URL non è corretto o non disponibile") return else: filename = 'new%s.zip' % info_accion localfilename = filetools.join(config.get_data_path(), filename) files.append([tecleado, localfilename, filename]) zip = True logger.info("localfilename=%s" % localfilename) logger.info("descarga fichero...") try: if len(files) > 1: lista_opciones = ["No", "Si", "Si (Sovrascrivere tutto)"] overwrite_all = False from core import downloadtools for url, localfilename, filename in files: result = downloadtools.downloadfile(url, localfilename, continuar=False) if result == -3: if len(files) == 1: dyesno = platformtools.dialog_yesno("Il file esiste già", "%s %s esiste già. " "Vuoi sovrascrivere?" % (info_accion, filename)) else: if not overwrite_all: dyesno = platformtools.dialog_select("Il file %s esiste già, vuoi sovrascrivere?" % filename, lista_opciones) else: dyesno = 1 # Diálogo cancelado if dyesno == -1: return # Caso de carpeta github, opción sobrescribir todos elif dyesno == 2: overwrite_all = True elif dyesno: 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): os.makedirs(backup) import shutil shutil.copy2(localfilename, filetools.join(backup, filename)) downloadtools.downloadfile(url, localfilename, continuar=True) else: if len(files) == 1: return else: continue except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) return if zip: try: # Lo descomprime logger.info("descomprime fichero...") from core import ziptools unzipper = ziptools.ziptools() logger.info("destpathname=%s" % local_folder) unzipper.extract(localfilename, local_folder, folder_to_extract, True, True) except: import traceback logger.error("Detalle del error: %s" % traceback.format_exc()) # Borra el zip descargado filetools.remove(localfilename) platformtools.dialog_ok("Errore", "C'è stato un errore nell'estrazione del file") return # Borra el zip descargado logger.info("borra fichero...") filetools.remove(localfilename) logger.info("...fichero borrado") platformtools.dialog_ok("Successo", "Aggiornamento/installazione eseguita correttamente")
def addchannel(item): from platformcode import platformtools from core import filetools import time, os logger.info("pelisalacarta.channels.configuracion addchannel") tecleado = platformtools.dialog_input("", "Introduzca la URL") if not tecleado: return logger.info("pelisalacarta.channels.configuracion url=%s" % tecleado) local_folder = config.get_runtime_path() if "canal" in item.title: local_folder = filetools.join(local_folder, 'channels') folder_to_extract = "channels" info_accion = "canal" else: local_folder = filetools.join(local_folder, 'servers') folder_to_extract = "servers" info_accion = "conector" # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github) try: extension = tecleado.rsplit(".", 1)[1] except: extension = "" files = [] zip = False if extension == "py" or extension == "xml": filename = tecleado.rsplit("/", 1)[1] localfilename = filetools.join(local_folder, filename) files.append([tecleado, localfilename, filename]) else: import re from core import scrapertools # Comprueba si la url apunta a una carpeta completa (channels o servers) de github if re.search(r'https://github.com/[^\s]+/' + folder_to_extract, tecleado): try: data = scrapertools.downloadpage(tecleado) matches = scrapertools.find_multiple_matches( data, '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"') for url, filename in matches: url = "https://raw.githubusercontent.com" + url.replace( "/blob/", "/") localfilename = filetools.join(local_folder, filename) files.append([url, localfilename, filename]) except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) platformtools.dialog_ok( "Error", "La url no es correcta o no está disponible") return else: filename = 'new%s.zip' % info_accion localfilename = filetools.join(config.get_data_path(), filename) files.append([tecleado, localfilename, filename]) zip = True logger.info("pelisalacarta.channels.configuracion localfilename=%s" % localfilename) logger.info("pelisalacarta.channels.configuracion descarga fichero...") try: if len(files) > 1: lista_opciones = ["No", "Sí", "Sí (Sobrescribir todos)"] overwrite_all = False from core import downloadtools for url, localfilename, filename in files: result = downloadtools.downloadfile(url, localfilename, continuar=False) if result == -3: if len(files) == 1: dyesno = platformtools.dialog_yesno("El archivo ya existe", "Ya existe el %s %s." \ " ¿Desea sobrescribirlo?" % (info_accion, filename)) else: if not overwrite_all: dyesno = platformtools.dialog_select( "El archivo %s ya existe, ¿desea sobrescribirlo?" % filename, lista_opciones) else: dyesno = 1 # Diálogo cancelado if dyesno == -1: return # Caso de carpeta github, opción sobrescribir todos elif dyesno == 2: overwrite_all = True elif dyesno: hora_folder = "Copia seguridad [%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): os.makedirs(backup) import shutil shutil.copy2(localfilename, filetools.join(backup, filename)) result = downloadtools.downloadfile(url, localfilename, continuar=True) else: if len(files) == 1: return else: continue except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) return if zip: try: # Lo descomprime logger.info( "pelisalacarta.channels.configuracion descomprime fichero...") from core import ziptools unzipper = ziptools.ziptools() logger.info( "pelisalacarta.channels.configuracion destpathname=%s" % local_folder) unzipper.extract(localfilename, local_folder, folder_to_extract, True, True) except: import traceback logger.info("Detalle del error: %s" % traceback.format_exc()) # Borra el zip descargado filetools.remove(localfilename) platformtools.dialog_ok( "Error", "Se ha producido un error extrayendo el archivo") return # Borra el zip descargado logger.info("pelisalacarta.channels.configuracion borra fichero...") filetools.remove(localfilename) logger.info("pelisalacarta.channels.configuracion ...fichero borrado") platformtools.dialog_ok( "Éxito", "Actualización/Instalación realizada correctamente")
def check_addon_updates(verbose=False): logger.info() # Forzamos la actualización de los repos para facilitar la actualización del addon Alfa xbmc.executebuiltin('UpdateAddonRepos') ADDON_UPDATES_JSON = 'https://extra.alfa-addon.com/addon_updates/updates.json' ADDON_UPDATES_ZIP = 'https://extra.alfa-addon.com/addon_updates/updates.zip' try: get_ua_list() except: pass try: last_fix_json = os.path.join( config.get_runtime_path(), 'last_fix.json') # información de la versión fixeada del usuario # Se guarda en get_runtime_path en lugar de get_data_path para que se elimine al cambiar de versión try: localfilename = os.path.join(config.get_data_path(), 'temp_updates.zip') if os.path.exists(localfilename): os.remove(localfilename) except: pass # Descargar json con las posibles actualizaciones # ----------------------------------------------- resp = httptools.downloadpage(ADDON_UPDATES_JSON, timeout=5, ignore_response_code=True) if not resp.sucess and resp.code != 404: logger.info('ERROR en la descarga de actualizaciones: %s' % resp.code) if verbose: dialog_notification( 'Alfa: error en la actualización', 'Hay un error al descargar la actualización') return False if not resp.data: logger.info('No se encuentran actualizaciones del addon') if verbose: dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente') check_update_to_others( verbose=verbose ) # Comprueba las actualuzaciones de otros productos return False data = jsontools.load(resp.data) if 'addon_version' not in data or 'fix_version' not in data: logger.info('No hay actualizaciones del addon') if verbose: dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente') check_update_to_others( verbose=verbose ) # Comprueba las actualuzaciones de otros productos return False # Comprobar versión que tiene instalada el usuario con versión de la actualización # -------------------------------------------------------------------------------- current_version = config.get_addon_version(with_fix=False, from_xml=True) if current_version != data['addon_version']: logger.info('No hay actualizaciones para la versión %s del addon' % current_version) if verbose: dialog_notification('Alfa ya está actualizado', 'No hay ninguna actualización urgente') check_update_to_others( verbose=verbose ) # Comprueba las actualuzaciones de otros productos return False if os.path.exists(last_fix_json): try: lastfix = {} lastfix = jsontools.load(open(last_fix_json, "r").read()) if lastfix['addon_version'] == data[ 'addon_version'] and lastfix['fix_version'] == data[ 'fix_version']: logger.info( 'Ya está actualizado con los últimos cambios. Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) if verbose: dialog_notification( 'Alfa ya está actualizado', 'Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) check_update_to_others( verbose=verbose ) # Comprueba las actualuzaciones de otros productos return False except: if lastfix: logger.error('last_fix.json: ERROR en: ' + str(lastfix)) else: logger.error('last_fix.json: ERROR desconocido') lastfix = {} # Descargar zip con las actualizaciones # ------------------------------------- downloadtools.downloadfile(ADDON_UPDATES_ZIP, localfilename, silent=True) # Descomprimir zip dentro del addon # --------------------------------- try: unzipper = ziptools.ziptools() unzipper.extract(localfilename, config.get_runtime_path()) except: xbmc.executebuiltin('Extract("%s", "%s")' % (localfilename, config.get_runtime_path())) time.sleep(1) # Borrar el zip descargado # ------------------------ try: os.remove(localfilename) except: pass # Si es PY3 se actualizan los módulos marshal # Se reinicia Proxytools try: if PY3: from platformcode.custom_code import marshal_check marshal_check() if not PY3: from core.proxytools import get_proxy_list else: from core.proxytools_py3 import get_proxy_list get_proxy_list(monitor_start=False) except: logger.error('Error Marshalizando e iniciando Proxytools') logger.error(traceback.format_exc()) # Guardar información de la versión fixeada # ----------------------------------------- if 'files' in data: data.pop('files', None) open(last_fix_json, "w").write(jsontools.dump(data)) logger.info('Addon actualizado correctamente a %s.fix%d' % (data['addon_version'], data['fix_version'])) if verbose: dialog_notification( 'Alfa actualizado a', 'Versión %s.fix%d' % (data['addon_version'], data['fix_version'])) check_update_to_others( verbose=verbose ) # Comprueba las actualuzaciones de otros productos return True except: logger.error('Error al comprobar actualizaciones del addon!') logger.error(traceback.format_exc()) if verbose: dialog_notification('Alfa actualizaciones', 'Error al comprobar actualizaciones') check_update_to_others( verbose=verbose ) # Comprueba las actualuzaciones de otros productos return False
def establecer_contenido(content_type, silent=False): if config.is_xbmc(): continuar = False msg_text = "Cartella Libreria personalizzata" librarypath = config.get_setting("librarypath") if librarypath == "": continuar = True if content_type == FOLDER_MOVIES: if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'): if not silent: # Preguntar si queremos instalar metadata.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "TheMovieDB. non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.themoviedb.org xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True) logger.info("Instalado el Scraper de películas de TheMovieDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)')) if not continuar: msg_text = "The Movie Database non installato." else: # SERIES # Instalar The TVDB if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'): if not silent: # Preguntar si queremos instalar metadata.tvdb.com install = platformtools.dialog_yesno("The TVDB", "The TVDB non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.tvdb.com xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True) logger.info("Instalado el Scraper de series de The TVDB") except: pass continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)')) if not continuar: msg_text = "The TVDB non installato." # Instalar TheMovieDB if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): continuar = False if not silent: # Preguntar si queremos instalar metadata.tvshows.themoviedb.org install = platformtools.dialog_yesno("The Movie Database", "TheMovieDB non presente.", "Installare adesso?") else: install = True if install: try: # Instalar metadata.tvshows.themoviedb.org # 1º Probar desde el repositorio ... xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True) if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): # ...si no funciona descargar e instalar desde la web url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip" path_down = xbmc.translatePath( "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip") path_unzip = xbmc.translatePath("special://home/addons/") header = ("User-Agent", "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013") from core import downloadtools from core import ziptools downloadtools.downloadfile(url, path_down, continuar=True, headers=[header]) unzipper = ziptools.ziptools() unzipper.extract(path_down, path_unzip) xbmc.executebuiltin('xbmc.UpdateLocalAddons') strSettings = '<settings>\n' \ ' <setting id="fanart" value="true" />\n' \ ' <setting id="keeporiginaltitle" value="false" />\n' \ ' <setting id="language" value="it" />\n' \ '</settings>' path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml") tv_themoviedb_addon_path = filetools.dirname(path_settings) if not filetools.exists(tv_themoviedb_addon_path): filetools.mkdir(tv_themoviedb_addon_path) if filetools.write(path_settings,strSettings): continuar = True except: pass continuar = (install and continuar) if not continuar: msg_text = "The Movie Database non installato." idPath = 0 idParentPath = 0 strPath = "" if continuar: continuar = False librarypath = "special://home/userdata/addon_data/plugin.video." + config.PLUGIN_NAME + "/library/" # Buscamos el idPath sql = 'SELECT MAX(idPath) FROM path' nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idPath = records[0][0] + 1 # Buscamos el idParentPath sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % \ librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/') nun_records, records = execute_sql_kodi(sql) if nun_records == 1: idParentPath = records[0][0] librarypath = records[0][1] continuar = True else: # No existe librarypath en la BD: la insertamos sql = 'INSERT INTO path (idPath, strPath, scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \ '(%s, "%s", 0, 0, 0, 0)' % (idPath, librarypath) nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True idParentPath = idPath idPath += 1 else: msg_text = "Impossibile impostare librarypath in BD" if continuar: continuar = False # Fijamos strContent, strScraper, scanRecursive y strSettings if content_type == FOLDER_MOVIES: strContent = 'movies' strScraper = 'metadata.themoviedb.org' scanRecursive = 2147483647 strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \ "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \ "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \ "<setting id='trailer' value='true' /></settings>" strActualizar = "Configurare lo scraper per i film in italiano?" else: strContent = 'tvshows' strScraper = 'metadata.tvdb.com' scanRecursive = 0 strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \ "<setting id='absolutenumber' value='false' />" \ "<setting id='dvdorder' value='false' />" \ "<setting id='fallback' value='true' />" \ "<setting id='fanart' value='true' />" \ "<setting id='language' value='it' /></settings>" strActualizar = "Configurare lo scraper per le serie in italiano?" # Fijamos strPath strPath = librarypath + content_type + "/" logger.info("%s: %s" % (content_type, strPath)) # Comprobamos si ya existe strPath en la BD para evitar duplicados sql = 'SELECT idPath FROM path where strPath="%s"' % strPath nun_records, records = execute_sql_kodi(sql) sql = "" if nun_records == 0: # Insertamos el scraper sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \ 'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \ '"%s", 0, 0, %s)' % ( idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath) else: if not silent: # Preguntar si queremos configurar themoviedb.org como opcion por defecto actualizar = platformtools.dialog_yesno("The TVDB", strActualizar) else: actualizar = True if actualizar: # Actualizamos el scraper idPath = records[0][0] sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \ 'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath) if sql: nun_records, records = execute_sql_kodi(sql) if nun_records == 1: continuar = True if not continuar: msg_text = "Error al configurar el scraper en la BD." if not continuar: heading = "Libreria non %s configurata" % content_type #msg_text = "Assicurarsi di aver installato l'add-on The Movie Database" elif content_type == FOLDER_TVSHOWS and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'): heading = "Libreria %s configurata" % content_type msg_text = "Kodi deve essere riavviato affinché le modifiche abbiano effetto." else: heading = "Libreria %s configurata" % content_type msg_text = "Complimenti la libreria di Kodi è stata configurata correttamente." platformtools.dialog_notification(heading, msg_text, icon=1, time=10000) logger.info("%s: %s" % (heading,msg_text))