def updateFromZip(): platformtools.dialog_notification('Kodi on Demand', 'Aggiornamento in corso...') remotefilename = 'https://github.com/' + user + "/" + repo + "/archive/" + branch + ".zip" localfilename = xbmc.translatePath( "special://home/addons/") + "plugin.video.kod.update.zip" logger.info("kodiondemand.core.updater remotefilename=%s" % remotefilename) logger.info("kodiondemand.core.updater localfilename=%s" % localfilename) logger.info("kodiondemand.core.updater descarga fichero...") import urllib urllib.urlretrieve(remotefilename, localfilename) # Lo descomprime logger.info("kodiondemand.core.updater descomprime fichero...") destpathname = xbmc.translatePath("special://home/addons/") logger.info("kodiondemand.core.updater destpathname=%s" % destpathname) unzipper = ziptools() unzipper.extract(localfilename, destpathname) # puliamo tutto shutil.rmtree(addonDir) filetools.rename(destpathname + "addon-" + branch, addonDir) # Borra el zip descargado logger.info("kodiondemand.core.updater borra fichero...") os.remove(localfilename) # os.remove(temp_dir) platformtools.dialog_notification('Kodi on Demand', 'Aggiornamento completato!')
def check_bookmark(readpath): # Create a list with favorite entries itemlist = [] if readpath.startswith("special://") and config.is_xbmc(): import xbmc readpath = xbmc.translatePath(readpath) for fichero in sorted(filetools.listdir(readpath)): # Old files (".txt") if fichero.endswith(".txt"): # We wait 0.1 seconds between files, so that the file names do not overlap time.sleep(0.1) # We get the item from the .txt canal, titulo, thumbnail, plot, server, url, contentTitle = readbookmark(filetools.join(readpath, fichero)) if canal == "": canal = "favorites" item = Item(channel=canal, action="play", url=url, server=server, title=contentTitle, thumbnail=thumbnail, plot=plot, fanart=thumbnail, contentTitle=contentTitle, folder=False) filetools.rename(filetools.join(readpath, fichero), fichero[:-4] + ".old") itemlist.append(item) # If there are Favorites to save if itemlist: favourites_list = read_favourites() for item in itemlist: data = "ActivateWindow(10025,"plugin://plugin.video.kod/?" + item.tourl() + "",return)" favourites_list.append((item.title, item.thumbnail, data)) if save_favourites(favourites_list): logger.debug("Correct txt to xml conversion")
def check_bookmark(readpath): # Crea un listado con las entradas de favoritos itemlist = [] if readpath.startswith("special://") and config.is_xbmc(): import xbmc readpath = xbmc.translatePath(readpath) for fichero in sorted(filetools.listdir(readpath)): # Ficheros antiguos (".txt") if fichero.endswith(".txt"): # Esperamos 0.1 segundos entre ficheros, para que no se solapen los nombres de archivo time.sleep(0.1) # Obtenemos el item desde el .txt canal, titulo, thumbnail, plot, server, url, fulltitle = readbookmark(filetools.join(readpath, fichero)) if canal == "": canal = "favoritos" item = Item(channel=canal, action="play", url=url, server=server, title=fulltitle, thumbnail=thumbnail, plot=plot, fanart=thumbnail, fulltitle=fulltitle, folder=False) filetools.rename(filetools.join(readpath, fichero),fichero[:-4] + ".old") itemlist.append(item) # Si hay Favoritos q guardar if itemlist: favourites_list = read_favourites() for item in itemlist: data = "ActivateWindow(10025,"plugin://plugin.video.pelisalacarta/?" + item.tourl() + "",return)" favourites_list.append((item.title, item.thumbnail, data)) if save_favourites(favourites_list): logger.debug("Conversion de txt a xml correcta")
def verify_Kodi_video_DB(): logger.info() import random platform = {} path = '' db_files = [] try: path = filetools.join("special://masterprofile/", "Database") if filetools.exists(path): platform = config.get_platform(full_version=True) if platform and platform.get('video_db', ''): db_files = filetools.walk(path) if filetools.exists(filetools.join(path, platform['video_db'])): for root, folders, files in db_files: for file in files: if platform['video_db'] not in file: if file.startswith('MyVideos'): randnum = str(random.randrange(1, 999999)) filetools.rename(filetools.join(path, file), 'OLD_' + randnum +'_' + file) logger.error('BD obsoleta: ' + file) else: logger.error('Video_DB: ' + str(platform['video_db']) + ' para versión Kodi ' + str(platform['num_version']) + ' NO EXISTE. Analizar carpeta: ' + str(db_files)) else: logger.error('Estructura de get_platform(full_version=True) incorrecta') else: logger.error('Path a Userdata/Database (' + path + ') no encontrado') except: logger.error('Platform: ' + str(platform) + ' / Path: ' + str(path) + ' / Files: ' + str(db_files)) logger.error(traceback.format_exc()) return
def create_tvshows_from_json(_actualizado): logger.info( "streamondemand.platformcode.library_service create_tvshows_from_json") fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE) if filetools.exists(fname): if not _actualizado: platformtools.dialog_ok( "Biblioteca: Actualizando formato", "Espere por favor mientras se completa el proceso") try: data = jsontools.loads(filetools.read(fname)) for tvshow in data: for channel in data[tvshow]["channels"]: serie = Item(contentSerieName=data[tvshow]["channels"] [channel]["tvshow"], url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios", title=data[tvshow]["name"], active=True) if not tvshow.startswith("t_"): serie.infoLabels["tmdb_id"] = tvshow library.save_library_tvshow(serie, list()) filetools.rename(fname, "series.json.old") except EnvironmentError: logger.info("ERROR al leer el archivo: {0}".format(fname))
def create_tvshows_from_json(_actualizado): logger.info("pelisalacarta.platformcode.library_service create_tvshows_from_json") fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE) if filetools.exists(fname): if not _actualizado: platformtools.dialog_ok("Biblioteca: Actualizando formato", "Espere por favor mientras se completa el proceso") try: data = jsontools.loads(filetools.read(fname)) for tvshow in data: for channel in data[tvshow]["channels"]: serie = Item(contentSerieName=data[tvshow]["channels"][channel]["tvshow"], url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios", title=data[tvshow]["name"], active=True) if not tvshow.startswith("t_"): serie.infoLabels["tmdb_id"] = tvshow library.save_library_tvshow(serie, list()) filetools.rename(fname, "series.json.old") except EnvironmentError: logger.info("ERROR al leer el archivo: {0}".format(fname))
def check_bookmark(readpath): # Crea un listado con las entradas de favoritos itemlist = [] if readpath.startswith("special://") and config.is_xbmc(): import xbmc readpath = xbmc.translatePath(readpath) for fichero in sorted(filetools.listdir(readpath)): # Ficheros antiguos (".txt") if fichero.endswith(".txt"): # Esperamos 0.1 segundos entre ficheros, para que no se solapen los nombres de archivo time.sleep(0.1) # Obtenemos el item desde el .txt canal, titulo, thumbnail, plot, server, url, fulltitle = readbookmark(filetools.join(readpath, fichero)) if canal == "": canal = "favoritos" item = Item(channel=canal, action="play", url=url, server=server, title=fulltitle, thumbnail=thumbnail, plot=plot, fanart=thumbnail, fulltitle=fulltitle, folder=False) filetools.rename(filetools.join(readpath, fichero), fichero[:-4] + ".old") itemlist.append(item) # Si hay Favoritos q guardar if itemlist: favourites_list = read_favourites() for item in itemlist: data = "ActivateWindow(10025,"plugin://plugin.video.pelisalacarta/?" + item.tourl() + "",return)" favourites_list.append((item.title, item.thumbnail, data)) if save_favourites(favourites_list): logger.debug("Conversion de txt a xml correcta")
def rename(dir1, dir2): renamed = False while not renamed: try: filetools.rename(dir1, dir2) renamed = True except: logger.info('cartella ' + dir1 + ' NON rinominata')
def rename(File): jsonPath = xbmc.translatePath(config.get_setting('downloadlistpath')) json = jsontools.load(open(filetools.join(jsonPath, File), "r").read()) filePath = filetools.join(xbmc.translatePath(config.get_setting('downloadpath')), json['downloadFilename']) if json['infoLabels']['mediatype'] == 'movie': if filetools.isdir(filePath): extension = '' files = filetools.listdir(filePath) oldName = json['downloadFilename'] newName = json['backupFilename'] for f in files: ext = os.path.splitext(f)[-1] if ext in extensions_list: extension = ext filetools.rename(filetools.join(filePath, f), f.replace(oldName, newName)) filetools.rename(filePath, newName) jsontools.update_node(filetools.join(newName, newName + extension), File, 'downloadFilename', jsonPath) else: oldName = json['downloadFilename'] newName = json['backupFilename'] + os.path.splitext(oldName)[-1] filetools.rename(filePath, newName) jsontools.update_node(newName, File, 'downloadFilename', jsonPath) else: sep = '/' if filePath.lower().startswith("smb://") else os.sep FolderName = json['backupFilename'].split(sep)[0] Title = re.sub(r'(\s*\[[^\]]+\])', '', FolderName) if filetools.isdir(filePath): files = filetools.listdir(filePath) file_dict = {} for f in files: title = process_filename(f, Title, ext=False) ext = os.path.splitext(f)[-1] name = os.path.splitext(f)[0] if title not in file_dict and ext in extensions_list: file_dict[title] = name for title, name in file_dict.items(): for f in files: if name in f: filetools.rename(filetools.join(filePath, f), f.replace(name, title)) filetools.rename(filePath, FolderName) jsontools.update_node(FolderName, File, 'downloadFilename', jsonPath) else: filename = filetools.split(filePath)[-1] title = process_filename(filename, Title) NewFolder = filetools.join(config.get_setting('downloadpath'), FolderName) if not filetools.isdir(NewFolder): filetools.mkdir(NewFolder) from_folder = filetools.join(config.get_setting('downloadpath'), filename) to_folder = filetools.join(config.get_setting('downloadpath'), FolderName, title) filetools.move(from_folder, to_folder) jsontools.update_node(filetools.join(FolderName, title), File, 'downloadFilename', jsonPath)
def create_tvshows_from_xml(): logger.info("fusionse.platformcode.library_service create_tvshows_from_xml") fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE_OLD) if filetools.exists(fname): platformtools.dialog_ok("Libreria: Si aggiornerà al nuovo formato", "Selezionare il nome corretto di ogni serie, se non siete sicuri potete 'Annulla'.", "Ci sono nuove opzioni per la 'Libreria' in 'configurazione'.") filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD") if not filetools.exists(library.TVSHOWS_PATH): filetools.mkdir(library.TVSHOWS_PATH) if filetools.exists(library.TVSHOWS_PATH): try: data = filetools.read(fname) for line in data.splitlines(): aux = line.rstrip('\n').split(",") tvshow = aux[0].strip() url = aux[1].strip() channel = aux[2].strip() serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios", title=tvshow, active=True) patron = "^(.+)[\s]\((\d{4})\)$" matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName) if matches: serie.infoLabels['title'] = matches[0][0] serie.infoLabels['year'] = matches[0][1] else: serie.infoLabels['title'] = tvshow library.save_library_tvshow(serie, list()) filetools.rename(fname, "series.xml.old") # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen library.clean() except EnvironmentError: logger.info("ERROR al leer el archivo: {0}".format(fname)) else: logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES") else: logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES") return True return False
def create_tvshows_from_xml(): logger.info("streamondemand.platformcode.library_service create_tvshows_from_xml") fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE_OLD) if filetools.exists(fname): platformtools.dialog_ok("Libreria: Si aggiornerà al nuovo formato", "Selezionare il nome corretto di ogni serie, se non siete sicuri potete 'Annulla'.", "Ci sono nuove opzioni per la 'Libreria' in 'configurazione'.") filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD") if not filetools.exists(library.TVSHOWS_PATH): filetools.mkdir(library.TVSHOWS_PATH) if filetools.exists(library.TVSHOWS_PATH): try: data = filetools.read(fname) for line in data.splitlines(): aux = line.rstrip('\n').split(",") tvshow = aux[0].strip() url = aux[1].strip() channel = aux[2].strip() serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios", title=tvshow, active=True) patron = "^(.+)[\s]\((\d{4})\)$" matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName) if matches: serie.infoLabels['title'] = matches[0][0] serie.infoLabels['year'] = matches[0][1] else: serie.infoLabels['title'] = tvshow library.save_library_tvshow(serie, list()) filetools.rename(fname, "series.xml.old") # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen library.clean() except EnvironmentError: logger.info("ERROR al leer el archivo: {0}".format(fname)) else: logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES") else: logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES") return True return False
def create_tvshows_from_xml(): logger.info("pelisalacarta.platformcode.library_service create_tvshows_from_xml") fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE_OLD) if filetools.exists(fname): platformtools.dialog_ok("Biblioteca: Se va a actualizar al nuevo formato", "Seleccione el nombre correcto de cada serie, si no está seguro pulse 'Cancelar'.", "Hay nuevas opciones en 'Biblioteca' y en la 'configuración' del addon.") filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD") if not filetools.exists(library.TVSHOWS_PATH): filetools.mkdir(library.TVSHOWS_PATH) if filetools.exists(library.TVSHOWS_PATH): try: data = filetools.read(fname) for line in data.splitlines(): aux = line.rstrip('\n').split(",") tvshow = aux[0].strip() url = aux[1].strip() channel = aux[2].strip() serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios", title=tvshow, active=True) patron = "^(.+)[\s]\((\d{4})\)$" matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName) if matches: serie.infoLabels['title'] = matches[0][0] serie.infoLabels['year'] = matches[0][1] else: serie.infoLabels['title'] = tvshow library.save_library_tvshow(serie, list()) filetools.rename(fname, "series.xml.old") # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen library.clean() except EnvironmentError: logger.info("ERROR al leer el archivo: {0}".format(fname)) else: logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES") else: logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES") return True return False
def renombrar_lista(item): logger.debug() fullfilename_current = os.path.join(config.get_data_path(), item.lista) if not os.path.exists(fullfilename_current): platformtools.dialog_ok('KoD', config.get_localized_string(70630) + '\n' + fullfilename_current) return False nombre = get_name_from_filename(item.lista) titulo = platformtools.dialog_input(default=nombre, heading=config.get_localized_string(70612)) if titulo is None or titulo == '' or titulo == nombre: return False titulo = text_clean(titulo, blank_char='_') filename = get_filename_from_name(titulo) fullfilename = os.path.join(config.get_data_path(), filename) # Check that the new name does not exist if os.path.exists(fullfilename): platformtools.dialog_ok('KoD', config.get_localized_string(70613) + '\n' + fullfilename) return False # Rename the file if not filetools.rename(fullfilename_current, filename): platformtools.dialog_ok('KoD', config.get_localized_string(70631) + '\n' + fullfilename) return False # Update settings if it is the active list if item.lista == get_lista_activa(): config.set_setting('lista_activa', filename) platformtools.itemlist_refresh() return True
def renombrar_lista(item): logger.info() fullfilename_current = os.path.join(config.get_data_path(), item.lista) if not os.path.exists(fullfilename_current): platformtools.dialog_ok('Alfa', 'Error, no se encuentra la lista!', fullfilename_current) return False nombre = get_name_from_filename(item.lista) titulo = platformtools.dialog_input(default=nombre, heading='Nombre de la lista') if titulo is None or titulo == '' or titulo == nombre: return False titulo = text_clean(titulo, blank_char='_') filename = get_filename_from_name(titulo) fullfilename = os.path.join(config.get_data_path(), filename) # Comprobar que el nuevo nombre no exista if os.path.exists(fullfilename): platformtools.dialog_ok('Alfa', 'Error, ya existe una lista con este nombre!', fullfilename) return False # Rename del fichero if not filetools.rename(fullfilename_current, filename): platformtools.dialog_ok('Alfa', 'Error, no se ha podido renombrar la lista!', fullfilename) return False # Update settings si es la lista activa if item.lista == get_lista_activa(): config.set_setting('lista_activa', filename) platformtools.itemlist_refresh() return True
def renombrar_lista(item): logger.info() fullfilename_current = filetools.join(trackingtools.get_tracking_path(), item.lista) if not filetools.exists(fullfilename_current): platformtools.dialog_ok(config.__addon_name, 'Error, no se encuentra la lista!', item.lista) return False nombre = item.lista.replace('.sqlite', '') titulo = platformtools.dialog_input(default=nombre, heading='Nombre de la lista') if titulo is None or titulo == '' or titulo == nombre: return False filename = titulo + '.sqlite' fullfilename = filetools.join(trackingtools.get_tracking_path(), filename) # Comprobar que el nuevo nombre no exista if filetools.exists(fullfilename): platformtools.dialog_ok(config.__addon_name, 'Error, ya existe una lista con este nombre!', filename) return False # Rename del fichero if not filetools.rename(fullfilename_current, filename): platformtools.dialog_ok(config.__addon_name, 'Error, no se ha podido renombrar la lista!', filename) return False # Update settings si es la lista activa if item.lista.replace('.sqlite', '') == trackingtools.get_current_dbname(): trackingtools.set_current_dbname(filename) platformtools.itemlist_refresh() return True
def updateFromZip(): dp = platformtools.dialog_progress_bg('Kodi on Demand', 'Aggiornamento in corso...') dp.update(0) remotefilename = 'https://github.com/' + user + "/" + repo + "/archive/" + branch + ".zip" localfilename = xbmc.translatePath( "special://home/addons/") + "plugin.video.kod.update.zip" logger.info("remotefilename=%s" % remotefilename) logger.info("localfilename=%s" % localfilename) import urllib urllib.urlretrieve( remotefilename, localfilename, lambda nb, bs, fs, url=remotefilename: _pbhook(nb, bs, fs, url, dp)) # Lo descomprime logger.info("decompressione...") destpathname = xbmc.translatePath("special://home/addons/") logger.info("destpathname=%s" % destpathname) try: hash = fixZipGetHash(localfilename) unzipper = ziptools() unzipper.extract(localfilename, destpathname) except Exception as e: logger.info('Non sono riuscito ad estrarre il file zip') logger.info(e) return False dp.update(95) # puliamo tutto shutil.rmtree(addonDir) filetools.rename(destpathname + "addon-" + branch, addonDir) logger.info("Cancellando il file zip...") remove(localfilename) dp.update(100) return hash
def check_bookmark(readpath): # Create favorite list itemlist = [] if readpath.startswith("special://") and config.is_xbmc(): readpath = xbmc.translatePath(readpath) for fichero in sorted(filetools.listdir(readpath)): # Old files (".txt") if fichero.endswith(".txt"): # Wait 0.1 seconds between files, so that the file names do not overlap xbmc.sleep(0.1 * 1000) # Itemo of .txt canal, titulo, thumbnail, plot, server, url, fulltitle = readbookmark( filetools.join(readpath, fichero)) if canal == "": canal = "favoritos" item = Item(channel=canal, action="play", url=url, server=server, title=fulltitle, thumbnail=thumbnail, plot=plot, fanart=thumbnail, fulltitle=fulltitle, folder=False) filetools.rename(filetools.join(readpath, fichero), fichero[:-4] + ".old") itemlist.append(item) # Save favorites if itemlist: favourites_list = read_favourites() for item in itemlist: data = "ActivateWindow(10025,"plugin://plugin.video.streamondemand/?" + item.tourl( ) + "",return)" favourites_list.append((item.title, item.thumbnail, data)) if save_favourites(favourites_list): logger.debug("Conversion de txt a xml correcta")
def rename_rar_dir(rar_file, save_path_videos, video_path, torr_client): logger.info() rename_status = False folders = rar_file.split("/") if filetools.exists(filetools.join(save_path_videos, folders[0])): src = filetools.join(save_path_videos, folders[0]).decode("utf8") dst = filetools.join(save_path_videos, video_path).decode("utf8") dst_file = video_path.decode("utf8") # Se para la actividad para que libere los archivos descargados if torr_client in ['quasar', 'elementum']: torr_data, deamon_url, index = get_tclient_data(folders[0], torr_client) log("##### Client URL: %s" % '%spause/%s' % (deamon_url, index)) if torr_data and deamon_url: data = httptools.downloadpage('%spause/%s' % (deamon_url, index), timeout=5, alfa_s=True).data for x in range(10): if xbmc.abortRequested: return rename_status, rar_file xbmc.sleep(1000) try: if filetools.exists(src): filetools.rename(src, dst_file) else: break except: log("##### Rename ERROR: SRC: %s" % src) log(traceback.format_exc(1)) else: if filetools.exists(dst): log("##### Renamed: SRC: %s" % src) log("##### TO: DST: %s" % dst) rar_file = video_path + '/' + folders[1] rename_status = True break return rename_status, rar_file
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 convert_old_to_v4(): logger.info() path_series_xml = filetools.join(config.get_data_path(), "series.xml") path_series_json = filetools.join(config.get_data_path(), "series.json") series_insertadas = 0 series_fallidas = 0 version = 'v?' # Renombrar carpeta Series y crear una vacia import time new_name = str(time.time()) path_series_old = filetools.join(library.LIBRARY_PATH, "SERIES_OLD_" + new_name) if filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD_" + new_name): if not filetools.mkdir(library.TVSHOWS_PATH): logger.error("ERROR, no se ha podido crear la nueva carpeta de SERIES") return False else: logger.error("ERROR, no se ha podido renombrar la antigua carpeta de SERIES") return False path_cine_old = filetools.join(library.LIBRARY_PATH, "CINE_OLD_" + new_name) if filetools.rename(library.MOVIES_PATH, "CINE_OLD_" + new_name): if not filetools.mkdir(library.MOVIES_PATH): logger.error("ERROR, no se ha podido crear la nueva carpeta de CINE") return False else: logger.error("ERROR, no se ha podido renombrar la antigua carpeta de CINE") return False # Convertir libreria de v1(xml) a v4 if filetools.exists(path_series_xml): try: data = filetools.read(path_series_xml) for line in data.splitlines(): try: aux = line.rstrip('\n').split(",") tvshow = aux[0].strip() url = aux[1].strip() channel = aux[2].strip() serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios", title=tvshow, active=True) patron = "^(.+)[\s]\((\d{4})\)$" matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName) if matches: serie.infoLabels['title'] = matches[0][0] serie.infoLabels['year'] = matches[0][1] else: serie.infoLabels['title'] = tvshow insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification("Serie actualizada", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 filetools.rename(path_series_xml, "series.xml.old") version = 'v4' except EnvironmentError: logger.error("ERROR al leer el archivo: %s" % path_series_xml) return False # Convertir libreria de v2(json) a v4 if filetools.exists(path_series_json): try: data = jsontools.load_json(filetools.read(path_series_json)) for tvshow in data: for channel in data[tvshow]["channels"]: try: serie = Item(contentSerieName=data[tvshow]["channels"][channel]["tvshow"], url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios", title=data[tvshow]["name"], active=True) if not tvshow.startswith("t_"): serie.infoLabels["tmdb_id"] = tvshow insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification("Serie actualizada", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 filetools.rename(path_series_json, "series.json.old") version = 'v4' except EnvironmentError: logger.error("ERROR al leer el archivo: %s" % path_series_json) return False # Convertir libreria de v3 a v4 if version != 'v4': # Obtenemos todos los tvshow.json de la biblioteca de SERIES_OLD recursivamente for raiz, subcarpetas, ficheros in filetools.walk(path_series_old): for f in ficheros: if f == "tvshow.json": try: serie = Item().fromjson(filetools.read(filetools.join(raiz, f))) insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification("Serie actualizada", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 movies_insertadas = 0 movies_fallidas = 0 for raiz, subcarpetas, ficheros in filetools.walk(path_cine_old): for f in ficheros: if f.endswith(".strm.json"): try: movie = Item().fromjson(filetools.read(filetools.join(raiz, f))) insertados, sobreescritos, fallidos = library.save_library_movie(movie) if fallidos == 0: movies_insertadas += 1 platformtools.dialog_notification("Película actualizada", movie.infoLabels['title']) else: movies_fallidas += 1 except: movies_fallidas += 1 config.set_setting("library_version", 'v4') platformtools.dialog_notification("Biblioteca actualizada al nuevo formato", "%s series convertidas y %s series descartadas.\n" "%s peliculas convertidas y %s peliculas descartadas." "A continuación se va a obtener la información de todos los episodios" % (series_insertadas, series_fallidas, movies_insertadas, movies_fallidas), time=12000) # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.clean() return True
def convert_old_to_v4(): logger.info() path_series_xml = filetools.join(config.get_data_path(), "series.xml") path_series_json = filetools.join(config.get_data_path(), "series.json") series_insertadas = 0 series_fallidas = 0 version = 'v?' # Renombrar carpeta Series y crear una vacia import time new_name = str(time.time()) path_series_old = filetools.join(library.LIBRARY_PATH, "SERIES_OLD_" + new_name) if filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD_" + new_name): if not filetools.mkdir(library.TVSHOWS_PATH): logger.error( "ERROR, no se ha podido crear la nueva carpeta de SERIES") return False else: logger.error( "ERROR, no se ha podido renombrar la antigua carpeta de SERIES") return False path_cine_old = filetools.join(library.LIBRARY_PATH, "CINE_OLD_" + new_name) if filetools.rename(library.MOVIES_PATH, "CINE_OLD_" + new_name): if not filetools.mkdir(library.MOVIES_PATH): logger.error( "ERROR, no se ha podido crear la nueva carpeta de CINE") return False else: logger.error( "ERROR, no se ha podido renombrar la antigua carpeta de CINE") return False # Convertir libreria de v1(xml) a v4 if filetools.exists(path_series_xml): try: data = filetools.read(path_series_xml) for line in data.splitlines(): try: aux = line.rstrip('\n').split(",") tvshow = aux[0].strip() url = aux[1].strip() channel = aux[2].strip() serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios", title=tvshow, active=True) patron = "^(.+)[\s]\((\d{4})\)$" matches = re.compile(patron, re.DOTALL).findall( serie.contentSerieName) if matches: serie.infoLabels['title'] = matches[0][0] serie.infoLabels['year'] = matches[0][1] else: serie.infoLabels['title'] = tvshow insertados, sobreescritos, fallidos = library.save_library_tvshow( serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification( "Serie actualizada", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 filetools.rename(path_series_xml, "series.xml.old") version = 'v4' except EnvironmentError: logger.error("ERROR al leer el archivo: %s" % path_series_xml) return False # Convertir libreria de v2(json) a v4 if filetools.exists(path_series_json): try: data = jsontools.load_json(filetools.read(path_series_json)) for tvshow in data: for channel in data[tvshow]["channels"]: try: serie = Item( contentSerieName=data[tvshow]["channels"][channel] ["tvshow"], url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios", title=data[tvshow]["name"], active=True) if not tvshow.startswith("t_"): serie.infoLabels["tmdb_id"] = tvshow insertados, sobreescritos, fallidos = library.save_library_tvshow( serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification( "Serie actualizada", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 filetools.rename(path_series_json, "series.json.old") version = 'v4' except EnvironmentError: logger.error("ERROR al leer el archivo: %s" % path_series_json) return False # Convertir libreria de v3 a v4 if version != 'v4': # Obtenemos todos los tvshow.json de la biblioteca de SERIES_OLD recursivamente for raiz, subcarpetas, ficheros in filetools.walk(path_series_old): for f in ficheros: if f == "tvshow.json": try: serie = Item().fromjson( filetools.read(filetools.join(raiz, f))) insertados, sobreescritos, fallidos = library.save_library_tvshow( serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification( "Serie actualizada", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 movies_insertadas = 0 movies_fallidas = 0 for raiz, subcarpetas, ficheros in filetools.walk(path_cine_old): for f in ficheros: if f.endswith(".strm.json"): try: movie = Item().fromjson( filetools.read(filetools.join(raiz, f))) insertados, sobreescritos, fallidos = library.save_library_movie( movie) if fallidos == 0: movies_insertadas += 1 platformtools.dialog_notification( "Película actualizada", movie.infoLabels['title']) else: movies_fallidas += 1 except: movies_fallidas += 1 config.set_setting("library_version", 'v4') platformtools.dialog_notification( "Biblioteca actualizada al nuevo formato", "%s series convertidas y %s series descartadas.\n" "%s peliculas convertidas y %s peliculas descartadas." "A continuación se va a obtener la información de todos los episodios" % (series_insertadas, series_fallidas, movies_insertadas, movies_fallidas), time=12000) # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.clean() return True
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) 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('XBMC.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 rename(dir1, dir2): try: filetools.rename(dir1, dir2, silent=True, vfs=False) except: logger.info('cartella ' + dir1 + ' NON rinominata')
def convert_old_to_v4(): logger.info() path_series_xml = filetools.join(config.get_data_path(), "series.xml") path_series_json = filetools.join(config.get_data_path(), "series.json") series_insertadas = 0 series_fallidas = 0 version = 'v?' # Rename and create Series directory import time new_name = str(time.time()) path_series_old = filetools.join(library.LIBRARY_PATH, "SERIES_OLD_" + new_name) if filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD_" + new_name): if not filetools.mkdir(library.TVSHOWS_PATH): logger.error("ERROR, impossibile creare la directory SERIES") return False else: logger.error("ERROR,impossibile rinominare la directory SERIES") return False path_cine_old = filetools.join(library.LIBRARY_PATH, "CINE_OLD_" + new_name) if filetools.rename(library.MOVIES_PATH, "CINE_OLD_" + new_name): if not filetools.mkdir(library.MOVIES_PATH): logger.error("ERROR, impossibile creare la directory CINE") return False else: logger.error("ERROR, impossibile rinominare la directory CINE") return False # Convert library from v1 to v4 (xml) if filetools.exists(path_series_xml): try: data = filetools.read(path_series_xml) for line in data.splitlines(): try: aux = line.rstrip('\n').split(",") tvshow = aux[0].strip() url = aux[1].strip() channel = aux[2].strip() serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios", title=tvshow, active=True) patron = "^(.+)[\s]\((\d{4})\)$" matches = re.compile(patron, re.DOTALL).findall( serie.contentSerieName) if matches: serie.infoLabels['title'] = matches[0][0] serie.infoLabels['year'] = matches[0][1] else: serie.infoLabels['title'] = tvshow insertados, sobreescritos, fallidos = library.save_library_tvshow( serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification( "Serie aggiornata", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 filetools.rename(path_series_xml, "series.xml.old") version = 'v4' except EnvironmentError: logger.error("ERROR al leer el archivo: %s" % path_series_xml) return False # Convert library from v2 to v4 (json) if filetools.exists(path_series_json): try: data = jsontools.load_json(filetools.read(path_series_json)) for tvshow in data: for channel in data[tvshow]["channels"]: try: serie = Item( contentSerieName=data[tvshow]["channels"][channel] ["tvshow"], url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios", title=data[tvshow]["name"], active=True) if not tvshow.startswith("t_"): serie.infoLabels["tmdb_id"] = tvshow insertados, sobreescritos, fallidos = library.save_library_tvshow( serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification( "Serie aggiornata", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 filetools.rename(path_series_json, "series.json.old") version = 'v4' except EnvironmentError: logger.error("ERROR al leer el archivo: %s" % path_series_json) return False # Convert library from v2 to v4 if version != 'v4': # Get old Series recursively for raiz, subcarpetas, ficheros in filetools.walk(path_series_old): for f in ficheros: if f == "tvshow.json": try: serie = Item().fromjson( filetools.read(filetools.join(raiz, f))) insertados, sobreescritos, fallidos = library.save_library_tvshow( serie, list()) if fallidos == 0: series_insertadas += 1 platformtools.dialog_notification( "Serie aggiornata", serie.infoLabels['title']) else: series_fallidas += 1 except: series_fallidas += 1 movies_insertadas = 0 movies_fallidas = 0 for raiz, subcarpetas, ficheros in filetools.walk(path_cine_old): for f in ficheros: if f.endswith(".strm.json"): try: movie = Item().fromjson( filetools.read(filetools.join(raiz, f))) insertados, sobreescritos, fallidos = library.save_library_movie( movie) if fallidos == 0: movies_insertadas += 1 platformtools.dialog_notification( "Film aggiornato", movie.infoLabels['title']) else: movies_fallidas += 1 except: movies_fallidas += 1 config.set_setting("library_version", 'v4') platformtools.dialog_notification( "Libreria aggiornata con il nuovo formato", "%s serie convertite e %s serie scaricate. Continuare per" "ottenere le info sugli episodi" % (series_insertadas, series_fallidas), time=12000) # Cleanup library of empty records if config.is_xbmc(): from platformcode import xbmc_library xbmc_library.clean() return True