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 move_to_libray(item): try: from platformcode import library except: return # Copiamos el archivo a la biblioteca origen = filetools.join(config.get_setting("downloadpath"), item.downloadFilename) destino = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename)) if not filetools.isdir(filetools.dirname(destino)): filetools.mkdir(filetools.dirname(destino)) if filetools.isfile(destino) and filetools.isfile(origen) : filetools.remove(destino) if filetools.isfile(origen): filetools.move(origen, destino) if len(filetools.listdir(filetools.dirname(origen))) == 0: filetools.rmdir(filetools.dirname(origen)) else: logger.error("No se ha encontrado el archivo: %s" % origen) if filetools.isfile(destino): if item.contentType == "movie" and item.infoLabels["tmdb_id"]: library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino) library.save_library_movie(library_item) elif item.contentType == "episode" and item.infoLabels["tmdb_id"]: library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino) tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]}) library.save_library_tvshow(tvshow, [library_item])
def move_to_libray(item): download_path = filetools.join(config.get_setting("downloadpath"), item.downloadFilename) library_path = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename)) final_path = download_path if config.get_setting("library_add", "descargas") == True and config.get_setting("library_move", "descargas") == True: if not filetools.isdir(filetools.dirname(library_path)): filetools.mkdir(filetools.dirname(library_path)) if filetools.isfile(library_path) and filetools.isfile(download_path) : filetools.remove(library_path) if filetools.isfile(download_path): if filetools.move(download_path, library_path): final_path = library_path if len(filetools.listdir(filetools.dirname(download_path))) == 0: filetools.rmdir(filetools.dirname(download_path)) if config.get_setting("library_add", "descargas") == True: if filetools.isfile(final_path): if item.contentType == "movie" and item.infoLabels["tmdb_id"]: library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=final_path) library.save_library_movie(library_item) elif item.contentType == "episode" and item.infoLabels["tmdb_id"]: library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=final_path) tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]}) library.save_library_tvshow(tvshow, [library_item])
def search_for_unrar_in_error(download_paths, init=False): logger.info(str(init) + ' / ' + str(download_paths)) rar_processed = [] for torrent_client, path in download_paths: list_dir = filetools.listdir(path) for folder_w in list_dir: folder = filetools.join(path, folder_w) if filetools.isdir(folder): if not filetools.exists( filetools.join(folder, '_rar_control.json')): continue else: if not '_rar_control.json' in folder: continue if folder in rar_processed: continue rar_processed += [folder] rar_control = jsontools.load( filetools.read(filetools.join(folder, '_rar_control.json'))) rar_control['status'] += ': Recovery' if ('UnRARing' in rar_control['status'] or 'RECOVERY' in rar_control['status']) and not init: continue if 'UnRARing' in rar_control['status'] or 'ERROR' in rar_control[ 'status']: rar_control['status'] = 'RECOVERY: ' + rar_control['status'] rar_control['download_path'] = folder rar_control['torr_client'] = torrent_client if 'ERROR' in rar_control['status'] or 'UnRARing' in rar_control['status'] \ or 'RECOVERY' in rar_control['status']: rar_control['error'] += 1 ret = filetools.write( filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control)) logger.debug('%s, %s, %s, %s, %s, %s' % (rar_control['download_path'], \ rar_control['rar_names'][0], rar_control['password'], \ str(rar_control['error']), rar_control['error_msg'], rar_control['status'])) if ('ERROR' in rar_control['status'] and rar_control['error'] > 2) \ or ('UnRARing' in rar_control['status'] and rar_control['error'] > 3) \ or ('RECOVERY' in rar_control['status'] and rar_control['error'] > 3) \ or 'DONE' in rar_control['status']: continue if ret: try: threading.Thread(target=call_unrar, args=( rar_control, )).start() # Creamos un Thread independiente por UnRAR time.sleep(1) # Dejamos terminar la inicialización... except: # Si hay problemas de threading, pasamos al siguiente logger.error(traceback.format_exc()) if not init: sys.exit(0)
def browser(item): logger.info() itemlist = [] for file in filetools.listdir(item.url): if filetools.isdir(filetools.join(item.url, file)) and not file == "list": itemlist.append(Item(channel=item.channel, title=file, action=item.action, url= filetools.join(item.url, file))) else: itemlist.append(Item(channel=item.channel, title=file, action="play", url= filetools.join(item.url, file))) return itemlist
def move_to_libray(item): if not config.get_setting("library_move", "descargas") == True: return try: from core import library except: return # Copiamos el archivo a la biblioteca origen = filetools.join(config.get_setting("downloadpath"), item.downloadFilename) destino = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename)) if not filetools.isdir(filetools.dirname(destino)): filetools.mkdir(filetools.dirname(destino)) if filetools.isfile(destino) and filetools.isfile(origen): filetools.remove(destino) if filetools.isfile(origen): filetools.move(origen, destino) if len(filetools.listdir(filetools.dirname(origen))) == 0: filetools.rmdir(filetools.dirname(origen)) else: logger.error("No se ha encontrado el archivo: %s" % origen) if filetools.isfile(destino): if item.contentType == "movie" and item.infoLabels["tmdb_id"]: library_item = Item(title="Scaricato: %s" % item.downloadFilename, channel="descargas", action="findvideos", infoLabels=item.infoLabels, url=item.downloadFilename) library.save_library_movie(library_item) elif item.contentType == "episode" and item.infoLabels["tmdb_id"]: library_item = Item(title="Scaricato: %s" % item.downloadFilename, channel="descargas", action="findvideos", infoLabels=item.infoLabels, url=item.downloadFilename) tvshow = Item(channel="descargas", contentType="tvshow", infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]}) library.save_library_tvshow(tvshow, [library_item])
def delete_file(item): logger.info() from core import filetools msg = config.get_localized_string(60044) % item.url_org or item.url if platformtools.dialog_yesno(config.get_localized_string(70221), msg): for file in [item.url, item.url_org]: if filetools.isdir(file): filetools.rmdirtree(file, silent=True) logger.info('Deleting folder: %s' % file) elif filetools.isfile(file): filetools.remove(file, silent=True) logger.info('Deleting file: %s' % file) platformtools.itemlist_refresh()
def list_storage(item): logger.info() from core import filetools from lib import generictools itemlist = [] torrent_params = { 'url': item.url, 'torrents_path': '', 'local_torr': item.torrents_path, 'lookup': False, 'force': True, 'data_torrent': True, 'subtitles': True, 'file_list': True } #logger.debug(item) browse_type = 0 path_out = item.url if not filetools.exists(path_out): path_out = '' if not path_out: msg = 'Seleccione carpeta de destino:' path_out = platformtools.dialog_browse(browse_type, msg, shares='') path_list = filetools.listdir(path_out) VIDEOLIBRARY_PATH = config.get_videolibrary_path() FOLDER_MOVIES = config.get_setting("folder_movies") FOLDER_TVSHOWS = config.get_setting("folder_tvshows") FOLDER = '' if VIDEOLIBRARY_PATH in path_out: if FOLDER_MOVIES in path_out: FOLDER = FOLDER_MOVIES elif FOLDER_TVSHOWS in path_out: FOLDER = FOLDER_TVSHOWS MOVIES_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_MOVIES) TVSHOWS_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_TVSHOWS) VIDEO_FOLDER = filetools.join(VIDEOLIBRARY_PATH, FOLDER) TEMP_TORRENT_FOLDER = filetools.join( config.get_setting('downloadpath', default=''), 'cached_torrents_Alfa') MIS_TORRENT_FOLDER = filetools.join( config.get_setting('downloadpath', default=''), 'Mis_Torrents') for file in path_list: if FOLDER and file.endswith('.json') and file.split( '.')[0] + '_01.torrent' in str(path_list): json_video = Item().fromjson( filetools.read(filetools.join(path_out, file))) json_video.channel = 'url' json_video.action = 'findvideos' json_video.torrents_path = json_video.url itemlist.append(json_video) elif FOLDER and filetools.isdir(filetools.join(path_out, file)): if '.torrent' in str(filetools.listdir(filetools.join(path_out, file))) \ or '.magnet' in str(filetools.listdir(filetools.join(path_out, file))): itemlist.append( Item(channel=item.channel, action="list_storage", url=filetools.join(path_out, file), title=file.title(), contentTitle=file.title(), contentType="list", unify=False, context=context)) if len(itemlist) > 1: itemlist = sorted(itemlist, key=lambda it: it.title) #clasificamos elif not FOLDER and filetools.isdir(filetools.join(path_out, file)): if MIS_TORRENT_FOLDER in path_out: title = file.title() if 'BTDigg' in file: title = title.replace( 'Btdigg', '[B][COLOR limegreen]BT[/COLOR][COLOR red]Digg[/COLOR][/B]' ) itemlist.append( Item(channel=item.channel, action="list_storage", url=filetools.join(path_out, file), title=title, contentTitle=title, contentType="list", unify=False, btdigg=True if 'BTDigg' in file else False, url_org=filetools.join(path_out, file), context=context)) if len(itemlist) > 1: itemlist = sorted(itemlist, key=lambda it: it.title) #clasificamos elif not FOLDER and ('.torrent' in file or '.magnet' in file): btdigg = False if '.torrent' in file: url = filetools.join(TEMP_TORRENT_FOLDER, file) filetools.copy(filetools.join(path_out, file), url, silent=True) if not filetools.exists(url): continue else: url = filetools.read(filetools.join(path_out, file), silent=True) if btdigg_magnet in url: btdigg = True size = 'MAGNET' if not url: continue torrent_params['url'] = url torrent_params['torrents_path'] = '' torrent_params['local_torr'] = filetools.join( TEMP_TORRENT_FOLDER, file) torrent_params = generictools.get_torrent_size( url, torrent_params=torrent_params) if '.magnet' in file and 'ERROR' in torrent_params['size']: torrent_params['size'] = 'MAGNET' size = torrent_params['size'] itemlist.append( Item(channel=item.channel, action="play", url=url, url_org=filetools.join(path_out, file), server='torrent', title=filetools.join( filetools.basename(path_out.rstrip('/').rstrip('\\')), file).title() + " [%s]" % size, contentTitle=filetools.join( filetools.basename(path_out.rstrip('/').rstrip('\\')), file).title(), contentType="movie", unify=False, torrents_path=torrent_params['torrents_path'], infoLabels={"tmdb_id": "111"}, context=context, btdigg=btdigg)) if len(itemlist) > 1: itemlist = sorted(itemlist, key=lambda it: it.title) #clasificamos return itemlist
def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item=None): logger.info() # Importamos el cliente from btserver import Client played = False debug = False save_path_videos = filetools.join(config.get_setting("bt_download_path", server="torrent", default=config.get_setting("downloadpath")), 'BT-torrents') if not save_path_videos: save_path_videos = filetools.join(config.get_data_path(), 'BT-torrents') UNRAR = config.get_setting("unrar_path", server="torrent", default="") BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True) RAR = config.get_setting("mct_rar_unpack", server="torrent", default=True) try: BUFFER = int(config.get_setting("bt_buffer", server="torrent", default="50")) except: BUFFER = 50 DOWNLOAD_LIMIT = config.get_setting("mct_download_limit", server="torrent", default="") if DOWNLOAD_LIMIT: try: DOWNLOAD_LIMIT = int(DOWNLOAD_LIMIT) except: DOWNLOAD_LIMIT = 0 else: DOWNLOAD_LIMIT = 0 UPLOAD_LIMIT = 100 torr_client = 'BT' rar_file = '' rar_names = [] rar = False rar_res = False bkg_user = False video_names = [] video_file = '' video_path = '' videourl = '' msg_header = 'Alfa %s Cliente Torrent' % torr_client extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.mpe', '.mp4', '.ogg', '.rar', '.wmv', '.zip'] for entry in rar_files: for file, path in entry.items(): if file == 'path' and '.rar' in str(path): for file_r in path: rar_names += [file_r] rar = True if RAR and BACKGROUND: bkg_user = True elif file == 'path' and not '.rar' in str(path): for file_r in path: if os.path.splitext(file_r)[1] in extensions_list: video_names += [file_r] elif file == '__name': video_path = path if rar: rar_file = '%s/%s' % (video_path, rar_names[0]) erase_file_path = filetools.join(save_path_videos, video_path) video_path = erase_file_path if video_names: video_file = video_names[0] if not video_file and mediaurl.startswith('magnet'): video_file = urllib.unquote_plus(scrapertools.find_single_match(mediaurl, '(?:\&|&)dn=([^\&]+)\&')) erase_file_path = filetools.join(save_path_videos, video_file) if rar and RAR and not UNRAR: if not platformtools.dialog_yesno(msg_header, 'Se ha detectado un archivo .RAR en la descarga', \ 'No tiene instalado el extractor UnRAR', '¿Desea descargarlo en cualquier caso?'): return # Iniciamos el cliente: c = Client(url=mediaurl, is_playing_fnc=xbmc_player.isPlaying, wait_time=None, auto_shutdown=False, timeout=10, temp_path=save_path_videos, print_status=debug, auto_delete=False) activo = True finalizado = False dp_cerrado = True # Mostramos el progreso if rar and RAR and BACKGROUND: # Si se descarga un RAR... progreso = platformtools.dialog_progress_bg(msg_header) platformtools.dialog_notification("Descarga de RAR en curso", "Puedes realizar otras tareas en Kodi mientrastanto. " + \ "Te informaremos...", time=10000) else: progreso = platformtools.dialog_progress('Alfa %s Cliente Torrent' % torr_client, '') dp_cerrado = False # Mientras el progreso no sea cancelado ni el cliente cerrado while not c.closed and not xbmc.abortRequested: # Obtenemos el estado del torrent s = c.status if debug: # Montamos las tres lineas con la info del torrent txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \ (s.progress_file, s.file_size, s.str_state, s._download_rate) txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d | Pi: %d(%d)' % \ (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes, s.trackers, s.pieces_sum, s.pieces_len) txt3 = 'Origen Peers TRK: %d DHT: %d PEX: %d LSD %d ' % \ (s.trk_peers, s.dht_peers, s.pex_peers, s.lsd_peers) else: txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \ (s.progress_file, s.file_size, s.str_state, s._download_rate) txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d | Pi: %d(%d)' % \ (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes, s.trackers, s.pieces_sum, s.pieces_len) txt3 = video_file if rar and RAR and BACKGROUND or bkg_user: progreso.update(s.buffer, txt, txt2) else: progreso.update(s.buffer, txt, txt2, txt3) time.sleep(1) if (not bkg_user and progreso.iscanceled()) and (not (rar and RAR and BACKGROUND) and progreso.iscanceled()): if not dp_cerrado: progreso.close() dp_cerrado = True if 'Finalizado' in s.str_state or 'Seeding' in s.str_state: """ if not rar and platformtools.dialog_yesno(msg_header, config.get_localized_string(70198)): played = False dp_cerrado = False progreso = platformtools.dialog_progress(msg_header, '') progreso.update(s.buffer, txt, txt2, txt3) else: """ dp_cerrado = False progreso = platformtools.dialog_progress(msg_header, '') break else: if platformtools.dialog_yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)", "Selecciona NO para seguir descargando en segundo plano"): dp_cerrado = False progreso = platformtools.dialog_progress(msg_header, '') break else: bkg_user = True if not dp_cerrado: progreso.close() dp_cerrado = False progreso = platformtools.dialog_progress_bg(msg_header) progreso.update(s.buffer, txt, txt2) if not c.closed: c.set_speed_limits(DOWNLOAD_LIMIT, UPLOAD_LIMIT) # Bajamos la velocidad en background # Si el buffer se ha llenado y la reproduccion no ha sido iniciada, se inicia if ((s.pieces_sum >= BUFFER or 'Finalizado' in s.str_state or 'Seeding' in s.str_state) and not rar and not bkg_user) or \ (s.pieces_sum >= s.pieces_len - 3 and s.pieces_len > 0 and ('Finalizado' in s.str_state or 'Seeding' \ in s.str_state) and (rar or bkg_user)) and not played: if rar and RAR and UNRAR: c.stop() activo = False finalizado = True bkg_user = False dp_cerrado = False video_file, rar_res, video_path, erase_file_path = extract_files(rar_file, \ save_path_videos, password, progreso, item, torr_client) # ... extraemos el vídeo del RAR if rar_res and not xbmc.abortRequested: time.sleep(1) else: break elif (rar and not UNRAR) or (rar and not RAR): break elif bkg_user: finalizado = True break # Cerramos el progreso if not dp_cerrado: progreso.close() dp_cerrado = True # Reproducimos el vídeo extraido, si no hay nada en reproducción if not c.closed: c.set_speed_limits(DOWNLOAD_LIMIT, UPLOAD_LIMIT) # Bajamos la velocidad en background bkg_auto = True while xbmc_player.isPlaying() and not xbmc.abortRequested: time.sleep(3) # Obtenemos el playlist del torrent #videourl = c.get_play_list() if not rar_res: # Es un Magnet ? video_file = filetools.join(save_path_videos, s.file_name) if erase_file_path == save_path_videos: erase_file_path = video_file videourl = video_file else: videourl = filetools.join(video_path, video_file) # Iniciamos el reproductor playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(videourl, xlistitem) # xbmc_player = xbmc_player log("##### videourl: %s" % videourl) xbmc_player.play(playlist) # Marcamos como reproducido para que no se vuelva a iniciar played = True mark_auto_as_watched(item) # Y esperamos a que el reproductor se cierre bkg_auto = True dp_cerrado = True while xbmc_player.isPlaying() and not xbmc.abortRequested: time.sleep(1) if xbmc.getCondVisibility('Player.Playing'): if not dp_cerrado: dp_cerrado = True progreso.close() if xbmc.getCondVisibility('Player.Paused') and not rar_res: if not c.closed: s = c.status txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \ (s.progress_file, s.file_size, s.str_state, s._download_rate) txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d | Pi: %d(%d)' % \ (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes, s.trackers, s.pieces_sum, s.pieces_len) txt3 = video_file[:99] if dp_cerrado: dp_cerrado = False progreso = xbmcgui.DialogProgressBG() progreso.create(msg_header) progreso.update(s.buffer, msg_header, '[CR][CR]' + txt + '[CR]' + txt2) if not dp_cerrado: dp_cerrado = True progreso.close() # Miramos si se ha completado la descarga para borrar o no los archivos if activo: s = c.status if s.pieces_sum == s.pieces_len: finalizado = True break if platformtools.dialog_yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)", "Selecciona NO para seguir descargando en segundo plano"): progreso = platformtools.dialog_progress(msg_header, '') dp_cerrado = False break else: bkg_user = True played = False if not dp_cerrado: progreso.close() progreso = platformtools.dialog_progress_bg(msg_header) progreso.update(s.buffer, txt, txt2) dp_cerrado = False continue # Cuando este cerrado, Volvemos a mostrar el dialogo if not (rar and bkg_user): progreso = platformtools.dialog_progress(msg_header, '') progreso.update(s.buffer, txt, txt2, txt3) dp_cerrado = False break if not dp_cerrado: if rar or bkg_user: progreso.update(100, config.get_localized_string(70200), " ") else: progreso.update(100, config.get_localized_string(70200), " ", " ") # Detenemos el cliente if activo and not c.closed: c.stop() activo = False # Cerramos el progreso if not dp_cerrado: progreso.close() dp_cerrado = True # Y borramos los archivos de descarga restantes time.sleep(1) if filetools.exists(erase_file_path) and not bkg_user: if finalizado and not platformtools.dialog_yesno(msg_header, '¿Borrarmos los archivos descargados? (completos)'): return log("##### erase_file_path: %s" % erase_file_path) for x in range(10): if filetools.isdir(erase_file_path): if erase_file_path != save_path_videos: filetools.rmdirtree(erase_file_path) else: break else: filetools.remove(erase_file_path) time.sleep(5) if not filetools.exists(erase_file_path): break
def check(background=False): if not addon.getSetting('addon_update_enabled'): return False, False logger.info('Cerco aggiornamenti..') commits = loadCommits() if not commits: return False, False try: localCommitFile = open(os.path.join(addonDir, trackingFile), 'r+') except: calcCurrHash() localCommitFile = open(os.path.join(addonDir, trackingFile), 'r+') localCommitSha = localCommitFile.read() localCommitSha = localCommitSha.replace('\n', '') # da testare logger.info('Commit locale: ' + localCommitSha) updated = False serviceChanged = False pos = None for n, c in enumerate(commits): if c['sha'] == localCommitSha: pos = n break else: # evitiamo che dia errore perchè il file è già in uso localCommitFile.close() calcCurrHash() return True, False if pos > 0: changelog = '' poFilesChanged = False try: for c in reversed(commits[:pos]): commit = urllib.urlopen(c['url']).read() commitJson = json.loads(commit) # evitiamo di applicare i merge commit if 'Merge' in commitJson['commit']['message']: continue logger.info('aggiornando a ' + commitJson['sha']) alreadyApplied = True # major update if len(commitJson['files']) > 50: localCommitFile.close() c['sha'] = updateFromZip('Aggiornamento in corso...') localCommitFile = open( os.path.join( xbmc.translatePath("special://home/addons/"), 'plugin.video.kod', trackingFile), 'w') # il file di tracking viene eliminato, lo ricreo changelog += commitJson['commit']['message'] + "\n" poFilesChanged = True break for file in commitJson['files']: if file["filename"] == trackingFile: # il file di tracking non si modifica continue else: logger.info(file["filename"]) if 'resources/language' in file["filename"]: poFilesChanged = True if 'service.py' in file["filename"]: serviceChanged = True if file['status'] == 'modified' or file[ 'status'] == 'added': if 'patch' in file: text = "" try: localFile = io.open(os.path.join( addonDir, file["filename"]), 'r+', encoding="utf8") text = localFile.read() if not PY3: text = text.decode('utf-8') except IOError: # nuovo file # crea le cartelle se non esistono dirname = os.path.dirname( os.path.join(addonDir, file["filename"])) if not os.path.exists(dirname): os.makedirs(dirname) localFile = io.open(os.path.join( addonDir, file["filename"]), 'w', encoding="utf8") patched = apply_patch(text, (file['patch'] + '\n').encode('utf-8')) if patched != text: # non eseguo se già applicata (es. scaricato zip da github) alreadyApplied = False if getShaStr(patched) == file['sha']: localFile.seek(0) localFile.truncate() localFile.writelines(patched) localFile.close() else: # nel caso ci siano stati problemi logger.info( 'lo sha non corrisponde, scarico il file' ) localFile.close() urllib.urlretrieve( file['raw_url'], os.path.join( addonDir, file['filename'])) else: # è un file NON testuale, lo devo scaricare # se non è già applicato filename = os.path.join( addonDir, file['filename']) dirname = os.path.dirname(filename) if not (filetools.isfile( os.path.join(addonDir, file['filename'])) and getSha(filename) == file['sha']): if not os.path.exists(dirname): os.makedirs(dirname) urllib.urlretrieve(file['raw_url'], filename) alreadyApplied = False elif file['status'] == 'removed': remove(os.path.join(addonDir, file["filename"])) alreadyApplied = False elif file['status'] == 'renamed': # se non è già applicato if not (filetools.isfile( os.path.join(addonDir, file['filename'])) and getSha( os.path.join(addonDir, file['filename'])) == file['sha']): dirs = file['filename'].split('/') for d in dirs[:-1]: if not filetools.isdir( os.path.join(addonDir, d)): filetools.mkdir( os.path.join(addonDir, d)) filetools.move( os.path.join(addonDir, file['previous_filename']), os.path.join(addonDir, file['filename'])) alreadyApplied = False if not alreadyApplied: # non mando notifica se già applicata (es. scaricato zip da github) changelog += commitJson['commit']['message'] + "\n" except: import traceback logger.error(traceback.format_exc()) # fallback localCommitFile.close() c['sha'] = updateFromZip('Aggiornamento in corso...') localCommitFile = open( os.path.join(xbmc.translatePath("special://home/addons/"), 'plugin.video.kod', trackingFile), 'w') # il file di tracking viene eliminato, lo ricreo if addon.getSetting("addon_update_message"): if background: platformtools.dialog_notification( config.get_localized_string(20000), config.get_localized_string(80040) % commits[0]['sha'][:7], time=3000, sound=False) with open(xbmc.translatePath(changelogFile), 'a+') as fileC: fileC.write(changelog) elif changelog: platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(80041) + changelog) localCommitFile.seek(0) localCommitFile.truncate() localCommitFile.writelines(c['sha']) localCommitFile.close() xbmc.executebuiltin("UpdateLocalAddons") if poFilesChanged: refreshLang() updated = True else: logger.info('Nessun nuovo aggiornamento') return updated, serviceChanged
def get_temp(): global cur_tmp cur_tmp += 1 if not filetools.isdir(temp_dir): filetools.mkdir(temp_dir) return temp_dir + str(cur_tmp) + '.png'
def remove_files( download, torrent_file, video_file, ses, h, ren_video_file="", erase_file_path='' ): dialog_view = False torrent = False if os.path.isfile( torrent_file ): dialog_view = True torrent = True if download > 0: dialog_view = True if bkg_user and not extracted_rar: dialog_view = False if erase_file_path and erase_file_path != os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ): ren_video_file = erase_file_path if filetools.isfile(ren_video_file) and filetools.split(ren_video_file)[0] != os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ): ren_video_file = filetools.split(ren_video_file)[0] elif filetools.isdir(ren_video_file) and ren_video_file == os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ): ren_video_file = '' if dialog_view and ren_video_file: if h.status().num_pieces >= tot_piece_set: d = xbmcgui.Dialog() ok = d.yesno(msg_header, config.get_localized_string(30031), video_file) else: ok = True # -- SI ------------------------------------------------- if ok: # -- Borrar archivo - torrent ----------------------- if torrent: try: os.remove( torrent_file ) except: pass # -- Borrar carpeta/archivos y sesión - vídeo ------- try: ses.remove_torrent( h, 1 ) ses_lt = False except: ses_lt = False try: if os.path.isdir(ren_video_file): filetools.rmdirtree(ren_video_file, silent=True) elif os.path.exists(ren_video_file) and os.path.isfile(ren_video_file): os.remove(ren_video_file) log("##### erase_file_path: %s" % ren_video_file) except: log("##### erase_file_path: %s" % ren_video_file) log("### End session #########") else: # -- Borrar sesión ---------------------------------- try: ses.remove_torrent( h ) ses_lt = False except: ses_lt = False log("### End session #########") else: # -- Borrar sesión -------------------------------------- try: ses.remove_torrent( h ) ses_lt = False except: ses_lt = False # -- Borrar archivo - torrent ----------------------- if torrent: try: os.remove( torrent_file ) except: pass log("### End session #########") return
def remove_files( download, torrent_file, video_file, ses, h, ren_video_file="", item={} ): dialog_view = False torrent = False if os.path.isfile( torrent_file ): dialog_view = True torrent = True if download > 0: dialog_view = True if bkg_user and not extracted_rar: dialog_view = False if erase_file_path and erase_file_path != \ os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ): ren_video_file = erase_file_path if filetools.isfile(ren_video_file) and filetools.split(ren_video_file)[0] != \ os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ): ren_video_file = filetools.split(ren_video_file)[0] elif filetools.isdir(ren_video_file) and ren_video_file == \ os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ): ren_video_file = '' # Actualizado .json de control de descargas if not torrent_file or item.downloadProgress == 0: item.downloadProgress = 0 #log("##### .torrent borrado: %s" % erase_file_path) else: item.downloadProgress = 100 torr.update_control(item, function='mct_remove_files') if item.downloadStatus in [2, 4] and item.downloadProgress in [100]: dialog_view = False if dialog_view and ren_video_file: if h.status().num_pieces >= tot_piece_set: d = xbmcgui.Dialog() ok = d.yesno(msg_header, '¿Borrarmos los archivos descargados? (completos)' + '\n' + video_file) else: ok = True # -- SI ------------------------------------------------- if ok: # -- Borrar archivo - torrent ----------------------- if torrent: try: os.remove( torrent_file ) except: pass # -- Borrar carpeta/archivos y sesión - vídeo ------- try: ses.remove_torrent( h, 1 ) ses_lt = False except: ses_lt = False try: if os.path.isdir(ren_video_file): filetools.rmdirtree(ren_video_file, silent=True) elif os.path.exists(ren_video_file) and os.path.isfile(ren_video_file): os.remove(ren_video_file) log("##### erase_file_path: %s" % ren_video_file) except: log("##### erase_file_path: %s" % ren_video_file) log("### End session #########") else: # -- Borrar sesión ---------------------------------- try: ses.remove_torrent( h ) ses_lt = False except: ses_lt = False log("### End session #########") else: # -- Borrar sesión -------------------------------------- try: ses.remove_torrent( h ) ses_lt = False except: ses_lt = False # -- Borrar archivo - torrent ----------------------- if torrent: try: os.remove( torrent_file ) except: pass log("### End session #########") filetools.remove(filetools.join( DOWNLOAD_PATH , "MCT-torrent-videos", '.' + \ os.path.splitext(filetools.basename(torrent_file))[0].lower() + '.parts'), silent=True) return
def update_libtorrent(): logger.info() if not config.get_setting("mct_buffer", server="torrent", default=""): default = config.get_setting("torrent_client", server="torrent", default=0) config.set_setting("torrent_client", default, server="torrent") config.set_setting("mct_buffer", "50", server="torrent") if config.get_setting("mct_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("mct_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_background_download", True, server="torrent") config.set_setting("mct_rar_unpack", True, server="torrent") config.set_setting("bt_buffer", "50", server="torrent") if config.get_setting("bt_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("bt_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_download_limit", "", server="torrent") config.set_setting("magnet2torrent", False, server="torrent") if not filetools.exists(filetools.join(config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')): filetools.mkdir(filetools.join(config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')) if not filetools.exists(filetools.join(config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')): filetools.mkdir(filetools.join(config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')) filetools.mkdir(filetools.join(config.get_setting("mct_download_path", server="torrent"), 'MCT-torrents')) if not filetools.exists(ADDON_USERDATA_BIN_PATH): filetools.mkdir(ADDON_USERDATA_BIN_PATH) if not filetools.exists(ADDON_CUSTOMCODE_JSON) or not config.get_setting("unrar_path", server="torrent", default="") \ or (not 'unrar' in str(filetools.listdir(ADDON_USERDATA_BIN_PATH)).lower() and \ not xbmc.getCondVisibility("system.platform.android")) \ or xbmc.getCondVisibility("system.platform.android"): path = filetools.join(ADDON_PATH, 'lib', 'rarfiles') sufix = '' unrar = '' for device in filetools.listdir(path): if xbmc.getCondVisibility("system.platform.android") and 'android' not in device: continue if xbmc.getCondVisibility("system.platform.windows") and 'windows' not in device: continue if not xbmc.getCondVisibility("system.platform.windows") and not xbmc.getCondVisibility("system.platform.android") \ and ('android' in device or 'windows' in device): continue if 'windows' in device: sufix = '.exe' else: sufix = '' unrar = filetools.join(path, device, 'unrar%s') % sufix unrar_dest = filetools.join(ADDON_USERDATA_BIN_PATH, 'unrar%s') % sufix if not filetools.exists(unrar): unrar = '' if unrar: if not xbmc.getCondVisibility("system.platform.windows"): try: if xbmc.getCondVisibility("system.platform.android"): # Para Android copiamos el binario a la partición del sistema unrar_org = unrar unrar = filetools.join('special://xbmc/', 'files').replace('/cache/apk/assets', '') if not filetools.exists(unrar): filetools.mkdir(unrar) unrar = filetools.join(unrar, 'unrar') res = filetools.copy(unrar_org, unrar, silent=True) if not res: raise filetools.chmod(unrar, '777') except: logger.info('######## UnRAR ERROR in path: %s' % str(unrar), force=True) logger.error(traceback.format_exc()) if not xbmc.getCondVisibility("system.platform.android"): res = filetools.copy(unrar, unrar_dest, ch_mod='777', silent=True) if not res: logger.info('######## UnRAR ERROR in path: %s' % str(unrar_dest), force=True) continue unrar = unrar_dest try: p = execute_binary_from_alfa_assistant('openBinary', [unrar], wait=True, init=True) try: output_cmd, error_cmd = p.communicate() if p.returncode != 0 or error_cmd: logger.info('######## UnRAR returncode in module %s: %s, %s in %s' % \ (device, str(p.returncode), str(error_cmd), unrar), force=True) unrar = '' else: logger.info('######## UnRAR OK in %s: %s' % (device, unrar), force=True) break except: if p.returncode == 0: logger.info('######## UnRAR OK in %s: %s' % (device, unrar), force=True) break except: logger.info('######## UnRAR ERROR in module %s: %s' % (device, unrar), force=True) logger.error(traceback.format_exc(1)) unrar = '' if unrar: config.set_setting("unrar_path", unrar, server="torrent") config.set_setting("unrar_device", device, server="torrent") else: config.set_setting("unrar_path", "", server="torrent") config.set_setting("unrar_device", "", server="torrent") # Ahora descargamos la última versión disponible de Libtorrent para esta plataforma try: # Saltamos plataformas no soportadas if PY3 and (xbmc.getCondVisibility("system.platform.Windows") or xbmc.getCondVisibility("system.platform.android")): config.set_setting("libtorrent_path", "", server="torrent") config.set_setting("libtorrent_version", "ERROR/UNSUPPORTED", server="torrent") return version_base = filetools.join(ADDON_PATH, 'lib', 'python_libtorrent') libt_dir = filetools.listdir(filetools.join(ADDON_USERDATA_PATH, 'custom_code', 'lib')) if 'libtorrent' in str(libt_dir) or (not 'libtorrent' in str(filetools.listdir(ADDON_USERDATA_BIN_PATH)) and \ not xbmc.getCondVisibility("system.platform.android")): for libt_file in libt_dir: if 'libtorrent' in libt_file: filetools.remove(filetools.join(ADDON_USERDATA_PATH, 'custom_code', 'lib', libt_file), silent=True) current_system = '' current_version = '' elif config.get_setting("libtorrent_version", server="torrent", default="") \ and config.get_setting("libtorrent_path", server="torrent", default=""): current_system, current_version = config.get_setting("libtorrent_version", server="torrent", default="").split('/') else: current_system = '' current_version = '' if '1.1.1' not in current_version and ('arm' in current_system or 'aarch64' in current_system): current_version = '' version_base = filetools.join(version_base, current_system) if current_version: old_version = current_version new_version = sorted(filetools.listdir(version_base)) new_version_alt = new_version[:] if new_version: for folder in new_version_alt: if not filetools.isdir(filetools.join(version_base, folder)): new_version.remove(folder) if old_version != new_version[-1]: current_version = '' else: current_version = '' except: current_version = '' logger.error(traceback.format_exc(1)) custom_code_json = filetools.exists(ADDON_CUSTOMCODE_JSON) if custom_code_json and current_version: msg = 'Libtorrent_path: %s' % config.get_setting("libtorrent_path", server="torrent", default="") if current_version not in msg: msg += ' - Libtorrent_version: %s/%s' % (current_system, current_version) logger.info(msg, force=True) return try: logger.info('Libtorrent stored version: %s, %s' % (config.get_setting("libtorrent_version", \ server="torrent", default=""), str(custom_code_json)), force=True) from lib.python_libtorrent.python_libtorrent import get_libtorrent except Exception as e: logger.error(traceback.format_exc(1)) if not PY3: e = unicode(str(e), "utf8", errors="replace").encode("utf8") config.set_setting("libtorrent_path", "", server="torrent") if not config.get_setting("libtorrent_error", server="torrent", default=''): config.set_setting("libtorrent_error", str(e), server="torrent") return
def check(background=False): if not addon.getSetting('addon_update_enabled'): return False, False logger.info('Cerco aggiornamenti..') commits = loadCommits() if not commits: return False, False try: localCommitFile = open(os.path.join(addonDir, trackingFile), 'r+') except: calcCurrHash() localCommitFile = open(os.path.join(addonDir, trackingFile), 'r+') localCommitSha = localCommitFile.read() localCommitSha = localCommitSha.replace('\n', '') # da testare logger.info('Commit locale: ' + localCommitSha) updated = False serviceChanged = False pos = None for n, c in enumerate(commits): if c['sha'] == localCommitSha: pos = n break else: # evitiamo che dia errore perchè il file è già in uso localCommitFile.close() calcCurrHash() return True, False if pos > 0: changelog = '' poFilesChanged = False try: for c in reversed(commits[:pos]): commit = urllib.urlopen(c['url']).read() commitJson = json.loads(commit) # evitiamo di applicare i merge commit if 'Merge' in commitJson['commit']['message']: continue logger.info('aggiornando a ' + commitJson['sha']) # major update if len(commitJson['files']) > 50: localCommitFile.close() c['sha'] = updateFromZip('Aggiornamento in corso...') localCommitFile = open( os.path.join( xbmc.translatePath("special://home/addons/"), 'plugin.video.kod', trackingFile), 'w') # il file di tracking viene eliminato, lo ricreo changelog += commitJson['commit']['message'] + "\n" poFilesChanged = True serviceChanged = True break patch_url = commitJson['html_url'] + '.patch' logger.info('applicando ' + patch_url) from lib import patch patchOk = patch.fromurl(patch_url).apply(root=addonDir) for file in commitJson['files']: if file["filename"] == trackingFile: # il file di tracking non si modifica continue else: logger.info(file["filename"]) if 'resources/language' in file["filename"]: poFilesChanged = True if 'service.py' in file["filename"]: serviceChanged = True if (file['status'] == 'modified' and 'patch' not in file) or file['status'] == 'added' or ( file['status'] == 'modified' and not patchOk): # è un file NON testuale che è stato modificato, oppure è un file nuovo (la libreria non supporta la creazione di un nuovo file) # lo devo scaricare filename = os.path.join(addonDir, file['filename']) dirname = os.path.dirname(filename) if not (filetools.isfile( os.path.join(addonDir, file['filename'])) and getSha(filename) == file['sha']): logger.info('scaricando ' + file['raw_url']) if not os.path.exists(dirname): os.makedirs(dirname) urllib.urlretrieve(file['raw_url'], filename) elif file['status'] == 'removed': remove(os.path.join(addonDir, file["filename"])) elif file['status'] == 'renamed': # se non è già applicato if not (filetools.isfile( os.path.join(addonDir, file['filename'])) and getSha( os.path.join(addonDir, file['filename'])) == file['sha']): dirs = file['filename'].split('/') for d in dirs[:-1]: if not filetools.isdir( os.path.join(addonDir, d)): filetools.mkdir( os.path.join(addonDir, d)) filetools.move( os.path.join(addonDir, file['previous_filename']), os.path.join(addonDir, file['filename'])) changelog += commitJson['commit']['message'] + "\n" except: import traceback logger.error(traceback.format_exc()) # fallback localCommitFile.close() c['sha'] = updateFromZip('Aggiornamento in corso...') localCommitFile = open( os.path.join(xbmc.translatePath("special://home/addons/"), 'plugin.video.kod', trackingFile), 'w') # il file di tracking viene eliminato, lo ricreo localCommitFile.seek(0) localCommitFile.truncate() localCommitFile.writelines(c['sha']) localCommitFile.close() xbmc.executebuiltin("UpdateLocalAddons") if poFilesChanged: refreshLang() xbmc.sleep(1000) updated = True if addon.getSetting("addon_update_message"): if background: platformtools.dialog_notification( config.get_localized_string(20000), config.get_localized_string(80040) % commits[0]['sha'][:7], time=3000, sound=False) try: with open(config.changelogFile, 'a+') as fileC: fileC.write(changelog) except: import traceback logger.error(traceback.format_exc()) elif changelog: platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(80041) + changelog) else: logger.info('Nessun nuovo aggiornamento') return updated, serviceChanged
if not filetools.exists(sizefile_path): log('set_version: no default at %s searching for any version' % sizefile_path) try: versions = sorted( filetools.listdir( filetools.join(__root__, platform['system']))) except: versions = [] versions_for = versions[:] for ver in versions_for: if ver not in VERSIONS: versions.remove(ver) continue if not filetools.isdir( filetools.join(__root__, platform['system'], ver)): versions.remove(ver) VERSIONS_for = VERSIONS[:] for ver in VERSIONS_for: if ver not in versions: VERSIONS.remove(ver) if len(versions) > 0: platform['version'] = versions[-1] log('set_version: chose %s out of %s' % (platform['version'], str(versions))) else: e = 'die because the folder is empty' log(e) raise Exception(e)
def extract_files(rar_file, save_path_videos, password, dp, item=None, torr_client=None): logger.info() import sys #reload(sys) #sys.setdefaultencoding('utf-8') sys.path.insert(0, config.get_setting("unrar_path", server="torrent", default="")\ .replace('/unrar', '').replace('\\unrar,exe', '')) import rarfile # Verificamos si hay path para UnRAR rarfile.UNRAR_TOOL = config.get_setting("unrar_path", server="torrent", default="") if not rarfile.UNRAR_TOOL: if xbmc.getCondVisibility("system.platform.Android"): rarfile.UNRAR_TOOL = xbmc.executebuiltin("StartAndroidActivity(com.rarlab.rar)") return rar_file, False, '', '' log("##### unrar_path: %s" % rarfile.UNRAR_TOOL) rarfile.DEFAULT_CHARSET = 'utf-8' # Preparamos un path alternativo más corto para no sobrepasar la longitud máxima video_path = '' if item: if item.contentType == 'movie': video_path = '%s-%s' % (item.contentTitle, item.infoLabels['tmdb_id']) else: video_path = '%s-%sx%s-%s' % (item.contentSerieName, item.contentSeason, \ item.contentEpisodeNumber, item.infoLabels['tmdb_id']) # Renombramos el path dejado en la descarga a uno más corto rename_status = False org_rar_file = rar_file org_save_path_videos = save_path_videos if video_path and '/' in rar_file: log("##### rar_file: %s" % rar_file) rename_status, rar_file = rename_rar_dir(org_rar_file, org_save_path_videos, video_path, torr_client) # Calculamos el path para del RAR if "/" in rar_file: folders = rar_file.split("/") erase_file_path = filetools.join(save_path_videos, folders[0]) file_path = save_path_videos for f in folders: file_path = filetools.join(file_path, f) else: file_path = save_path_videos erase_file_path = save_path_videos # Calculamos el path para la extracción if "/" in rar_file: folders = rar_file.split("/") for f in folders: if not '.rar' in f: save_path_videos = filetools.join(save_path_videos, f) save_path_videos = filetools.join(save_path_videos, 'Extracted') if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos) log("##### save_path_videos: %s" % save_path_videos) # Permite hasta 5 pasadas de extracción de .RARs anidados platformtools.dialog_notification("Empezando extracción...", rar_file, time=5000) for x in range(5): try: archive = rarfile.RarFile(file_path.decode("utf8")) except: log("##### ERROR en Archivo rar: %s" % rar_file) log("##### ERROR en Carpeta del rar: %s" % file_path) log(traceback.format_exc()) platformtools.dialog_notification("Error al abrir el RAR", "Comprueba el log para más detalles") return rar_file, False, '', '' # Analizamos si es necesaria una contraseña, que debería estar en item.password if archive.needs_password(): if not password: pass_path = filetools.split(file_path)[0] password = last_password_search(pass_path) if not password : password = platformtools.dialog_input(heading="Introduce la contraseña (Mira en %s)" % pass_path) if not password: return rar_file, False, '', '' archive.setpassword(password) log("##### Password rar: %s" % password) # Miramos el contenido del RAR a extraer files = archive.infolist() info = [] for idx, i in enumerate(files): if i.file_size == 0: files.pop(idx) continue filename = i.filename if "/" in filename: filename = filename.rsplit("/", 1)[1] info.append("%s - %.2f MB" % (filename, i.file_size / 1048576.0)) if info: info.append("Extraer todo sin reproducir") else: platformtools.dialog_notification("El RAR está vacío", "O no contiene archivos válidos") return rar_file, False, '', erase_file_path # Seleccionamos extraer TODOS los archivos del RAR #selection = xbmcgui.Dialog().select("Selecciona el fichero a extraer y reproducir", info) selection = len(info) - 1 if selection < 0: return rar_file, False, '', erase_file_path else: try: log("##### RAR Extract INI #####") if selection == len(info) - 1: log("##### rar_file 1: %s" % file_path) log("##### save_path_videos 1: %s" % save_path_videos) dp.update(99, "Extrayendo archivos...", "Espera unos minutos....") archive.extractall(save_path_videos) else: log("##### rar_file 2: %s" % file_path) log("##### save_path_videos 2: %s" % save_path_videos) dp.update(99, "Espera unos minutos....", "Extrayendo archivo... %s" % info[selection]) archive.extract(files[selection], save_path_videos) log("##### RAR Extract END #####") except (rarfile.RarWrongPassword, rarfile.RarCRCError): platformtools.dialog_notification("Error al extraer", "Contraseña incorrecta") log(traceback.format_exc(1)) return rar_file, False, '', erase_file_path except rarfile.BadRarFile: platformtools.dialog_notification("Error al extraer", "Archivo rar con errores") log(traceback.format_exc(1)) return rar_file, False, '', erase_file_path except: platformtools.dialog_notification("Error al extraer", "Comprueba el log para más detalles") log(traceback.format_exc(1)) return rar_file, False, '', erase_file_path extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.mpe', '.mp4', '.ogg', '.wmv'] # Localizamos el path donde se ha dejado la extracción folder = True file_result = filetools.listdir(save_path_videos) while folder: for file_r in file_result: if filetools.isdir(filetools.join(save_path_videos, file_r)): file_result_alt = filetools.listdir(filetools.join(save_path_videos, file_r)) if file_result_alt: file_result = file_result_alt save_path_videos = filetools.join(save_path_videos, file_r) else: folder = False break else: folder = False # Si hay RARs anidados, ajustamos los paths para la siguiente pasada if '.rar' in str(file_result): for file_r in file_result: if '.rar' in file_r: rar_file = file_r file_path = str(filetools.join(save_path_videos, rar_file)) save_path_videos = filetools.join(save_path_videos, 'Extracted') if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos) platformtools.dialog_notification("Siguiente extracción...", rar_file, time=5000) # Si ya se ha extraido todo, preparamos el retorno else: video_list = [] for file_r in file_result: if os.path.splitext(file_r)[1] in extensions_list: video_list += [file_r] if len(video_list) == 0: platformtools.dialog_notification("El rar está vacío", "O no contiene archivos válidos") return rar_file, False, '', erase_file_path else: log("##### Archivo extraído: %s" % video_list[0]) platformtools.dialog_notification("Archivo extraído...", video_list[0], time=10000) return str(video_list[0]), True, save_path_videos, erase_file_path
def move_to_libray(item): if item.contentType == 'movie': FOLDER = FOLDER_MOVIES path_title = "%s [%s]" % (item.contentTitle.strip(), item.infoLabels['IMDBNumber']) move_path = filetools.join(config.get_videolibrary_path(), FOLDER, path_title) else: FOLDER = FOLDER_TVSHOWS path_title = "%s [%s]" % (item.contentSerieName, item.infoLabels['IMDBNumber']) move_path = filetools.join(config.get_videolibrary_path(), FOLDER) download_path = filetools.join(config.get_setting("downloadpath"), item.downloadFilename) library_path = filetools.join(move_path, *filetools.split(item.downloadFilename)) final_path = download_path if config.get_setting("library_add", "downloads") == True and config.get_setting( "library_move", "downloads") == True: if not filetools.isdir(filetools.dirname(library_path)): filetools.mkdir(filetools.dirname(library_path)) if filetools.isfile(library_path) and filetools.isfile(download_path): filetools.remove(library_path) if filetools.isfile(download_path): if filetools.move(download_path, library_path): final_path = library_path if len(filetools.listdir(filetools.dirname(download_path))) == 0: filetools.rmdir(filetools.dirname(download_path)) logger.info('ITEM = ' + str(item)) name = item.contentTitle if item.contentType == 'movie' else str( item.infoLabels['season']) + 'x' + str( item.infoLabels['episode']).zfill(2) list_item = os.listdir( filetools.join(config.get_videolibrary_path(), FOLDER, path_title)) clean = False for File in list_item: filename = File.lower() name = name.lower() if filename.startswith(name) and (filename.endswith('.strm') or filename.endswith('.json') or filename.endswith('.nfo')): clean = True logger.info('Delete File: ' + str( os.path.join(config.get_videolibrary_path(), FOLDER, path_title, File))) os.remove( os.path.join(config.get_videolibrary_path(), FOLDER, path_title, File)) from platformcode import xbmc_videolibrary xbmc_videolibrary.update(FOLDER) if clean == True: import xbmc while xbmc.getCondVisibility('Library.IsScanningVideo()'): xbmc.sleep(500) xbmc_videolibrary.clean() if config.get_setting("library_add", "downloads") == True and config.get_setting( "library_move", "downloads") == False: if filetools.isfile(final_path): if item.contentType == "movie" and item.infoLabels["tmdb_id"]: library_item = Item(title=config.get_localized_string(70228) % item.downloadFilename, channel="downloads", action="findvideos", infoLabels=item.infoLabels, url=final_path) videolibrarytools.save_movie(library_item) elif item.contentType == "episode" and item.infoLabels["tmdb_id"]: library_item = Item(title=config.get_localized_string(70228) % item.downloadFilename, channel="downloads", action="findvideos", infoLabels=item.infoLabels, url=final_path) tvshow = Item( channel="downloads", contentType="tvshow", infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]}) videolibrarytools.save_tvshow(tvshow, [library_item])
def check_addon_init(): if not addon.getSetting('addon_update_enabled'): return False logger.info('Cerco aggiornamenti..') commits = loadCommits() try: localCommitFile = open(addonDir + trackingFile, 'r+') except: calcCurrHash() localCommitFile = open(addonDir + trackingFile, 'r+') localCommitSha = localCommitFile.read() localCommitSha = localCommitSha.replace('\n', '') # da testare logger.info('Commit locale: ' + localCommitSha) updated = False pos = None for n, c in enumerate(commits): if c['sha'] == localCommitSha: pos = n break else: # evitiamo che dia errore perchè il file è già in uso localCommitFile.close() updateFromZip() return True if pos > 0: changelog = '' nCommitApplied = 0 for c in reversed(commits[:pos]): commit = httptools.downloadpage(c['url']).data commitJson = json.loads(commit) logger.info('aggiornando a' + commitJson['sha']) alreadyApplied = True for file in commitJson['files']: if file["filename"] == trackingFile: # il file di tracking non si modifica continue else: logger.info(file["filename"]) if file['status'] == 'modified' or file[ 'status'] == 'added': if 'patch' in file: text = "" try: localFile = open(addonDir + file["filename"], 'r+') for line in localFile: text += line except IOError: # nuovo file localFile = open(addonDir + file["filename"], 'w') patched = apply_patch(text, (file['patch'] + '\n').encode('utf-8')) if patched != text: # non eseguo se già applicata (es. scaricato zip da github) if getSha(patched) == file['sha']: localFile.seek(0) localFile.truncate() localFile.writelines(patched) localFile.close() alreadyApplied = False else: # nel caso ci siano stati problemi logger.info( 'lo sha non corrisponde, scarico il file' ) downloadtools.downloadfile( file['raw_url'], addonDir + file['filename'], silent=True, continuar=True) else: # è un file NON testuale, lo devo scaricare # se non è già applicato if not (filetools.isfile(addonDir + file['filename']) and getSha( filetools.read(addonDir + file['filename']) == file['sha'])): downloadtools.downloadfile(file['raw_url'], addonDir + file['filename'], silent=True, continuar=True) alreadyApplied = False elif file['status'] == 'removed': try: filetools.remove(addonDir + file["filename"]) alreadyApplied = False except: pass elif file['status'] == 'renamed': # se non è già applicato if not (filetools.isfile(addonDir + file['filename']) and getSha( filetools.read(addonDir + file['filename']) == file['sha'])): dirs = file['filename'].split('/') for d in dirs[:-1]: if not filetools.isdir(addonDir + d): filetools.mkdir(addonDir + d) filetools.move( addonDir + file['previous_filename'], addonDir + file['filename']) alreadyApplied = False if not alreadyApplied: # non mando notifica se già applicata (es. scaricato zip da github) changelog += commitJson['commit']['message'] + " | " nCommitApplied += 1 if addon.getSetting("addon_update_message"): time = nCommitApplied * 2000 if nCommitApplied < 10 else 20000 platformtools.dialog_notification('Kodi on Demand', changelog, time) localCommitFile.seek(0) localCommitFile.truncate() localCommitFile.writelines(c['sha']) localCommitFile.close() else: logger.info('Nessun nuovo aggiornamento') return updated
def update_libtorrent(): logger.info() if not config.get_setting("mct_buffer", server="torrent", default=""): default = config.get_setting("torrent_client", server="torrent", default=0) config.set_setting("torrent_client", default, server="torrent") config.set_setting("mct_buffer", "50", server="torrent") if config.get_setting("mct_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("mct_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_background_download", True, server="torrent") config.set_setting("mct_rar_unpack", True, server="torrent") config.set_setting("bt_buffer", "50", server="torrent") if config.get_setting("bt_download_path", server="torrent", default=config.get_setting("downloadpath")): config.set_setting("bt_download_path", config.get_setting("downloadpath"), server="torrent") config.set_setting("mct_download_limit", "", server="torrent") config.set_setting("magnet2torrent", False, server="torrent") if not filetools.exists( filetools.join( config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')): filetools.mkdir( filetools.join( config.get_setting("bt_download_path", server="torrent"), 'BT-torrents')) if not filetools.exists( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')): filetools.mkdir( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrent-videos')) filetools.mkdir( filetools.join( config.get_setting("mct_download_path", server="torrent"), 'MCT-torrents')) if not filetools.exists(filetools.join(config.get_runtime_path(), "custom_code.json")) or not \ config.get_setting("unrar_path", server="torrent", default=""): path = filetools.join(config.get_runtime_path(), 'lib', 'rarfiles') creationflags = '' sufix = '' unrar = '' for device in filetools.listdir(path): if xbmc.getCondVisibility( "system.platform.android") and 'android' not in device: continue if xbmc.getCondVisibility( "system.platform.windows") and 'windows' not in device: continue if not xbmc.getCondVisibility("system.platform.windows") and not xbmc.getCondVisibility("system.platform.android") \ and ('android' in device or 'windows' in device): continue if 'windows' in device: creationflags = 0x08000000 sufix = '.exe' else: creationflags = '' sufix = '' unrar = filetools.join(path, device, 'unrar%s') % sufix if not filetools.exists(unrar): unrar = '' if unrar: if not xbmc.getCondVisibility("system.platform.windows"): try: if xbmc.getCondVisibility("system.platform.android"): # Para Android copiamos el binario a la partición del sistema unrar_org = unrar unrar = filetools.join('special://xbmc/', 'files').replace( '/cache/apk/assets', '') if not filetools.exists(unrar): filetools.mkdir(unrar) unrar = filetools.join(unrar, 'unrar') filetools.copy(unrar_org, unrar, silent=True) filetools.chmod(unrar, '777') except: logger.info('######## UnRAR ERROR in path: %s' % str(unrar), force=True) logger.error(traceback.format_exc()) try: if xbmc.getCondVisibility("system.platform.windows"): p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags) else: p = subprocess.Popen(unrar, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output_cmd, error_cmd = p.communicate() if p.returncode != 0 or error_cmd: logger.info('######## UnRAR returncode in module %s: %s, %s in %s' % \ (device, str(p.returncode), str(error_cmd), unrar), force=True) unrar = '' else: logger.info('######## UnRAR OK in %s: %s' % (device, unrar), force=True) break except: logger.info('######## UnRAR ERROR in module %s: %s' % (device, unrar), force=True) logger.error(traceback.format_exc(1)) unrar = '' if unrar: config.set_setting("unrar_path", unrar, server="torrent") # Ahora descargamos la última versión disponible de Libtorrent para esta plataforma try: version_base = filetools.join(config.get_runtime_path(), 'lib', 'python_libtorrent') if config.get_setting("libtorrent_version", server="torrent", default=""): current_system, current_version = config.get_setting( "libtorrent_version", server="torrent", default="").split('/') else: current_system = '' current_version = '' version_base = filetools.join(version_base, current_system) if current_version: old_version = current_version new_version = sorted(filetools.listdir(version_base)) new_version_alt = new_version[:] if new_version: for folder in new_version_alt: if not filetools.isdir(filetools.join( version_base, folder)): new_version.remove(folder) if old_version != new_version[-1]: current_version = '' else: current_version = '' except: current_version = '' logger.error(traceback.format_exc(1)) custom_code_json = filetools.exists( filetools.join(config.get_runtime_path(), "custom_code.json")) if custom_code_json and current_version: msg = 'Libtorrent_path: %s' % config.get_setting( "libtorrent_path", server="torrent", default="") if current_version not in msg: msg += ' - Libtorrent_version: %s/%s' % (current_system, current_version) logger.info(msg, force=True) return try: logger.info('Libtorrent stored version: %s, %s' % (config.get_setting("libtorrent_version", \ server="torrent", default=""), str(custom_code_json)), force=True) from lib.python_libtorrent.python_libtorrent import get_libtorrent except Exception as e: logger.error(traceback.format_exc(1)) if not PY3: e = unicode(str(e), "utf8", errors="replace").encode("utf8") config.set_setting("libtorrent_path", "", server="torrent") if not config.get_setting( "libtorrent_error", server="torrent", default=''): config.set_setting("libtorrent_error", str(e), server="torrent") return