def borrar_filtro(item): logger.info() if item: # OBTENEMOS LOS DATOS DEL JSON dict_series = get_tvshows(item.from_channel) tvshow = item.show.strip().lower() heading = "¿Está seguro que desea eliminar el filtro?" line1 = "Pulse 'Si' para eliminar el filtro de [COLOR {0}]{1}[/COLOR], pulse 'No' o cierre la ventana para " \ "no hacer nada.".format(COLOR.get("selected", "auto"), item.show.strip()) if platformtools.dialog_yesno(heading, line1) == 1: lang_selected = dict_series.get(tvshow, {}).get(TAG_LANGUAGE, "") dict_series.pop(tvshow, None) fname, json_data = update_json_data(dict_series, item.from_channel) result = filetools.write(fname, json_data) if result: message = "FILTRO ELIMINADO" else: message = "Error al guardar en disco" heading = "{0} [{1}]".format(item.show.strip(), lang_selected) platformtools.dialog_notification(heading, message) if config.get_platform() == "mediaserver": platformtools.itemlist_refresh()
def remove_from_downloads_error(item): from core import descargas descargas.mover_descarga_error_a_pendiente(item.extra) platformtools.dialog_ok("Pelisalacarta", config.get_localized_string(30101) +"\n"+ item.title +"\n"+ config.get_localized_string(30107)) platformtools.itemlist_refresh() return
def mark_content_as_watched(item): logger.info("pelisalacarta.channels.biblioteca mark_content_as_watched") # logger.debug("item:\n" + item.tostring('\n')) if filetools.exists(item.nfo): url_scraper = filetools.read(item.nfo, 0, 1) it = Item().fromjson(filetools.read(item.nfo, 1)) if item.contentType == "movie": name_file = os.path.splitext(os.path.basename(item.nfo))[0] elif item.contentType == "episode": name_file = item.contentSeason + "x" + item.contentEpisodeNumber else: name_file = item.contentTitle if not hasattr(it, "library_playcounts"): it.library_playcounts = {} it.library_playcounts.update({name_file: item.playcount}) # se comprueba que si todos los episodios de una temporada están marcados, se marque tb la temporada if item.contentType != "movie": it = check_season_playcount(it, item.contentSeason) # Guardamos los cambios en item.nfo if filetools.write(item.nfo, url_scraper + it.tojson()): item.infoLabels["playcount"] = item.playcount if item.contentType == "tvshow": # Actualizar toda la serie new_item = item.clone(contentSeason=-1) mark_season_as_watched(new_item) if config.is_xbmc(): library.mark_content_as_watched_on_kodi(item, item.playcount) platformtools.itemlist_refresh()
def mark_content_as_watched(item): logger.info() # logger.debug("item:\n" + item.tostring('\n')) if filetools.exists(item.nfo): head_nfo = filetools.read(item.nfo, 0, 1) it = Item().fromjson(filetools.read(item.nfo, 1)) if item.contentType == 'movie': name_file = os.path.splitext(os.path.basename(item.nfo))[0] elif item.contentType == 'episode': name_file = "%sx%s" % (item.contentSeason, str(item.contentEpisodeNumber).zfill(2)) else: name_file = item.contentTitle if not hasattr(it, 'library_playcounts'): it.library_playcounts = {} it.library_playcounts.update({name_file: item.playcount}) # se comprueba que si todos los episodios de una temporada están marcados, se marque tb la temporada if item.contentType != 'movie': it = check_season_playcount(it, item.contentSeason) # Guardamos los cambios en item.nfo if filetools.write(item.nfo, head_nfo + it.tojson()): item.infoLabels['playcount'] = item.playcount if item.contentType == 'tvshow': # Actualizar toda la serie new_item = item.clone(contentSeason=-1) mark_season_as_watched(new_item) if config.is_xbmc(): library.mark_content_as_watched_on_kodi(item, item.playcount) platformtools.itemlist_refresh()
def remove_from_favorites(item): from channels import favoritos # En "extra" está el nombre del fichero en favoritos favoritos.delFavourite(item.extra) platformtools.dialog_ok("Pelisalacarta", config.get_localized_string(30102) +"\n"+ item.title +"\n"+ config.get_localized_string(30105)) platformtools.itemlist_refresh() return
def menu(item): logger.info() # Opciones disponibles para el menu op = ["Descargar", "Eliminar de la lista", "Reiniciar descarga", "Descargar desde...", "Reproducir"] opciones = [] # Opciones para el menu if item.downloadStatus == 0: # Sin descargar opciones.append(op[0]) # Descargar opciones.append(op[3]) # Descargar desde... opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 1: # descarga parcial opciones.append(op[0]) # Descargar opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 2: # descarga completada opciones.append(op[4]) # Reproducir opciones.append(op[1]) # Eliminar de la lista opciones.append(op[2]) # Reiniciar descarga if item.downloadStatus == 3: # descarga con error opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista # Mostramos el dialogo seleccion = platformtools.dialog_select("Scegliere un'opzione", opciones) # -1 es cancelar if seleccion == -1: return logger.info("opcion=%s" % (opciones[seleccion])) # Opcion Eliminar if opciones[seleccion] == op[1]: filetools.remove(item.path) # Opcion inicaiar descarga if opciones[seleccion] == op[0]: start_download(item) # Opcion inicaiar descarga desde... if opciones[seleccion] == op[3]: start_download(item, ask=True) # Reiniciar descarga if opciones[seleccion] == op[2]: if filetools.isfile(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)): filetools.remove(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)) update_json(item.path, {"downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0}) # Reproducir if opciones[seleccion] == op[4]: item.url = filetools.join(DOWNLOAD_PATH, item.downloadFilename) return platformtools.play_video(item) platformtools.itemlist_refresh()
def mark_tvshow_as_updatable(item): logger.info() head_nfo, it = library.read_nfo(item.nfo) it.active = item.active filetools.write(item.nfo, head_nfo + it.tojson()) platformtools.itemlist_refresh()
def eliminar(item): def eliminar_todo(item): filetools.rmdirtree(item.path) if config.is_xbmc(): import xbmc # esperamos 3 segundos para dar tiempo a borrar los ficheros xbmc.sleep(3000) # TODO mirar por qué no funciona al limpiar en la biblioteca de Kodi al añadirle un path # limpiamos la biblioteca de Kodi library.clean() logger.info("Eliminados todos los enlaces") platformtools.itemlist_refresh() logger.info(item.contentTitle) #logger.debug(item.tostring('\n')) if item.contentType == 'movie': heading = "Eliminar película" else: heading = "Eliminar serie" if item.multicanal: # Obtener listado de canales opciones = ["Eliminar solo los enlaces de %s" % k.capitalize() for k in item.library_urls.keys() if k !="descargas"] opciones.insert(0, heading) index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index == 0: # Seleccionado Eliminar pelicula/serie eliminar_todo(item) elif index > 0: # Seleccionado Eliminar canal X canal = opciones[index].replace("Eliminar solo los enlaces de ", "").lower() num_enlaces= 0 for fd in filetools.listdir(item.path): if fd.endswith(canal + '].json'): if filetools.remove(filetools.join(item.path, fd)): num_enlaces += 1 if num_enlaces > 0: # Actualizar .nfo head_nfo, item_nfo = library.read_nfo(item.nfo) del item_nfo.library_urls[canal] filetools.write(item.nfo, head_nfo + item_nfo.tojson()) msg_txt = "Eliminados %s enlaces del canal %s" % (num_enlaces, canal) logger.info(msg_txt) platformtools.dialog_notification(heading, msg_txt) platformtools.itemlist_refresh() else: if platformtools.dialog_yesno(heading, "¿Realmente desea eliminar '%s' de su biblioteca?" % item.infoLabels['title']): eliminar_todo(item)
def remove_from_downloads(item): from core import descargas # La categoría es el nombre del fichero en la lista de descargas descargas.deletebookmark(item.extra) platformtools.dialog_ok("Pelisalacarta", config.get_localized_string(30101) +"\n"+ item.title +"\n"+ config.get_localized_string(30106)) platformtools.itemlist_refresh() return
def mark_tvshow_as_updatable(item): logger.info("pelisalacarta.channels.biblioteca mark_tvshow_as_updatable") url_scraper = filetools.read(item.nfo, 0, 1) it = Item().fromjson(filetools.read(item.nfo, 1)) it.active = item.active filetools.write(item.nfo, url_scraper + it.tojson()) platformtools.itemlist_refresh()
def clean_all(item): logger.info() for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero))) if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero)) platformtools.itemlist_refresh()
def clean_ready(item): logger.info("pelisalacarta.channels.descargas clean_ready") for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero))) if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): if download_item.downloadStatus == STATUS_CODES.completed: filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero)) platformtools.itemlist_refresh()
def clean_ready(item): logger.info("pelisalacarta.channels.descargas clean_ready") for fichero in sorted(filetools.listdir(item.url)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(item.url, fichero))) serie_name = "%s [%s]" % (download_item.contentSerieName, download_item.contentChannel) if not item.serie_name or item.serie_name == serie_name: if download_item.downloadStatus == 2: filetools.remove(os.path.join(item.url, fichero)) platformtools.itemlist_refresh()
def menu(item): logger.info("pelisalacarta.channels.descargas menu") # Opciones disponibles para el menu op = ["Descargar", "Eliminar de la lista", "Reiniciar descarga"] opciones = [] # Opciones para el menu if item.downloadStatus == 0: # Sin descargar opciones.append(op[0]) # Descargar opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 1: # descarga parcial opciones.append(op[0]) # Descargar opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 2: # descarga completada opciones.append(op[1]) # Eliminar de la lista opciones.append(op[2]) # Reiniciar descarga if item.downloadStatus == 3: # descarga con error opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista # Mostramos el dialogo seleccion = platformtools.dialog_select("Elige una opción", opciones) # -1 es cancelar if seleccion == -1: return logger.info("pelisalacarta.channels.descargas menu opcion=%s" % (opciones[seleccion])) # Opcion Eliminar if opciones[seleccion] == op[1]: filetools.remove(item.path) # Opcion inicaiar descarga if opciones[seleccion] == op[0]: start_download(item) # Reiniciar descarga if opciones[seleccion] == op[2]: if filetools.isfile(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)): filetools.remove(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)) JSONItem = Item().fromjson(filetools.read(item.path)) JSONItem.downloadStatus = 0 JSONItem.downloadComplete = 0 JSONItem.downloadProgress = 0 JSONItem.downloadUrl = "" filetools.write(item.path, JSONItem.tojson()) platformtools.itemlist_refresh()
def download_all(item): time.sleep(0.5) for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): if fichero.endswith(".json"): download_item = Item(path = os.path.join(DOWNLOAD_LIST_PATH, fichero)).fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero))) if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): if download_item.downloadStatus in [STATUS_CODES.stoped, STATUS_CODES.canceled]: res = start_download(download_item) platformtools.itemlist_refresh() # Si se ha cancelado paramos if res == STATUS_CODES.canceled: break
def eliminar_todo(item): filetools.rmdirtree(item.path) if config.is_xbmc(): import xbmc # esperamos 3 segundos para dar tiempo a borrar los ficheros xbmc.sleep(3000) # TODO mirar por qué no funciona al limpiar en la biblioteca de Kodi al añadirle un path # limpiamos la biblioteca de Kodi library.clean() logger.info("Eliminados todos los enlaces") platformtools.itemlist_refresh()
def mark_season_as_watched(item): logger.info("pelisalacarta.channels.biblioteca mark_season_as_watched") # logger.debug("item:\n" + item.tostring('\n')) # Obtener el diccionario de episodios marcados f = filetools.join(item.path, "tvshow.nfo") url_scraper = filetools.read(f, 0, 1) it = Item().fromjson(filetools.read(f, 1)) if not hasattr(it, "library_playcounts"): it.library_playcounts = {} # Obtenemos los archivos de los episodios raiz, carpetas_series, ficheros = filetools.walk(item.path).next() # Marcamos cada uno de los episodios encontrados de esta temporada episodios_marcados = 0 for i in ficheros: if i.endswith(".strm"): season_episode = scrapertools.get_season_and_episode(i) if not season_episode: # El fichero no incluye el numero de temporada y episodio continue season, episode = season_episode.split("x") if int(item.contentSeason) == -1 or int(season) == int(item.contentSeason): name_file = os.path.splitext(os.path.basename(i))[0] it.library_playcounts[name_file] = item.playcount episodios_marcados += 1 if episodios_marcados: if int(item.contentSeason) == -1: # Añadimos todas las temporadas al diccionario item.library_playcounts for k in it.library_playcounts.keys(): if k.startswith("season"): it.library_playcounts[k] = item.playcount else: # Añadimos la temporada al diccionario item.library_playcounts it.library_playcounts["season %s" % item.contentSeason] = item.playcount # se comprueba que si todas las temporadas están vistas, se marque la serie como vista it = check_tvshow_playcount(it, item.contentSeason) # Guardamos los cambios en tvshow.nfo filetools.write(f, url_scraper + it.tojson()) item.infoLabels["playcount"] = item.playcount if config.is_xbmc(): # Actualizamos la BBDD de Kodi library.mark_season_as_watched_on_kodi(item, item.playcount) platformtools.itemlist_refresh()
def download_all(item): time.sleep(0.5) for fichero in sorted(filetools.listdir(item.url)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(item.url, fichero))) serie_name = "%s [%s]" % (download_item.contentSerieName, download_item.contentChannel) if not item.serie_name or item.serie_name == serie_name: download_item.path = os.path.join(item.url, fichero) if download_item.downloadStatus in [0, 1]: res = start_download(download_item) platformtools.itemlist_refresh() # Si se ha cancelado paramos if res == 1: break
def restart_error(item): logger.info("pelisalacarta.channels.descargas restart_error") for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero))) if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel): if download_item.downloadStatus == STATUS_CODES.error: if filetools.isfile(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)): filetools.remove(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)) update_json(item.path, {"downloadStatus" : STATUS_CODES.stoped, "downloadComplete" : 0 , "downloadProgress" : 0}) platformtools.itemlist_refresh()
def renameFavourite(item): logger.info("pelisalacarta.core.favoritos renameFavourite") #logger.debug(item.tostring('\n')) #Buscar el item q queremos renombrar en favourites.xml favourites_list = read_favourites() for i,fav in enumerate(favourites_list): if fav[0] == item.from_title: # abrir el teclado new_title = platformtools.dialog_input(item.from_title, item.title) if new_title: favourites_list[i] = (new_title, fav[1], fav[2]) if save_favourites(favourites_list): platformtools.dialog_ok(config.get_localized_string(30102), item.from_title, "se ha renombrado como:",new_title) # 'Se ha quitado de favoritos' platformtools.itemlist_refresh()
def restart_error(item): logger.info("pelisalacarta.channels.descargas restart_error") for fichero in sorted(filetools.listdir(item.url)): if fichero.endswith(".json"): download_item = Item().fromjson(filetools.read(os.path.join(item.url, fichero))) serie_name = "%s [%s]" % (download_item.contentSerieName, download_item.contentChannel) if not item.serie_name or item.serie_name == serie_name: if download_item.downloadStatus == 3: if filetools.isfile(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)): filetools.remove(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)) download_item.downloadStatus = 0 download_item.downloadComplete = 0 download_item.downloadProgress = 0 download_item.downloadUrl = "" filetools.write(os.path.join(item.url, fichero), download_item.tojson()) platformtools.itemlist_refresh()
def delFavourite(item): logger.info("pelisalacarta.core.favoritos delFavourite") #logger.debug(item.tostring('\n')) if item.from_title: item.title = item.from_title favourites_list = read_favourites() for fav in favourites_list[:]: if fav[0] == item.title: favourites_list.remove(fav) if save_favourites(favourites_list): platformtools.dialog_ok(config.get_localized_string(30102), item.title, config.get_localized_string(30105).lower()) # 'Se ha quitado de favoritos' platformtools.itemlist_refresh() break
def guardar_valores(item, dict_data_saved): """ Guarda los valores configurados en la ventana :param item: item :type item: Item :param dict_data_saved: diccionario con los datos salvados :type dict_data_saved: dict """ logger.info() # Aqui tienes q gestionar los datos obtenidos del cuadro de dialogo if item and dict_data_saved: logger.debug('item: {0}\ndatos: {1}'.format(item.tostring(), dict_data_saved)) # OBTENEMOS LOS DATOS DEL JSON if item.from_channel == "biblioteca": item.from_channel = item.contentChannel dict_series = get_tvshows(item.from_channel) tvshow = item.show.strip().lower() logger.info("Se actualiza los datos") list_quality = [] for _id, value in dict_data_saved.items(): if _id in item.list_calidad and value: list_quality.append(_id.lower()) lang_selected = item.list_idiomas[dict_data_saved[TAG_LANGUAGE]] dict_filter = {TAG_NAME: item.show, TAG_ACTIVE: dict_data_saved.get(TAG_ACTIVE, True), TAG_LANGUAGE: lang_selected, TAG_QUALITY_NOT_ALLOWED: list_quality} dict_series[tvshow] = dict_filter fname, json_data = update_json_data(dict_series, item.from_channel) result = filetools.write(fname, json_data) if result: message = "FILTRO GUARDADO" else: message = "Error al guardar en disco" heading = "{0} [{1}]".format(item.show.strip(), lang_selected) platformtools.dialog_notification(heading, message) if config.get_platform() == "mediaserver": platformtools.itemlist_refresh()
def settings(item): ret = platformtools.show_channel_settings( caption=config.get_localized_string(70224)) platformtools.itemlist_refresh() return ret
def descargar_lista(item, url): logger.info() from core import httptools, scrapertools if 'tinyupload.com/' in url: try: from urlparse import urlparse data = httptools.downloadpage(url).data logger.debug(data) down_url, url_name = scrapertools.find_single_match( data, ' href="(download\.php[^"]*)"><b>([^<]*)') url_json = '{uri.scheme}://{uri.netloc}/'.format( uri=urlparse(url)) + down_url except: platformtools.dialog_ok('Alfa', config.get_localized_string(70655), url) return False elif 'zippyshare.com/' in url: from core import servertools video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing( 'zippyshare', url) if not puedes: platformtools.dialog_ok('Alfa', config.get_localized_string(70655), motivo) return False url_json = video_urls[0][ 1] # https://www58.zippyshare.com/d/qPzzQ0UM/25460/alfavorites-testeanding.json url_name = url_json[url_json.rfind('/') + 1:] elif 'friendpaste.com/' in url: url_json = url if url.endswith('/raw') else url + '/raw' url_name = 'friendpaste' else: url_json = url url_name = url[url.rfind('/') + 1:] # Download json data = httptools.downloadpage(url_json).data # Verificar formato json de alfavorites y añadir info de la descarga jsondata = jsontools.load(data) if 'user_favorites' not in jsondata or 'info_lista' not in jsondata: logger.debug(data) platformtools.dialog_ok('Alfa', config.get_localized_string(70656)) return False jsondata['info_lista']['downloaded_date'] = fechahora_actual() jsondata['info_lista']['downloaded_from'] = url data = jsontools.dump(jsondata) # Pedir nombre para la lista descargada nombre = get_name_from_filename(url_name) titulo = platformtools.dialog_input( default=nombre, heading=config.get_localized_string(70657)) if titulo is None or titulo == '': return False titulo = text_clean(titulo, blank_char='_') filename = get_filename_from_name(titulo) fullfilename = os.path.join(config.get_data_path(), filename) # Si el nuevo nombre ya existe pedir confirmación para sobrescribir if os.path.exists(fullfilename): if not platformtools.dialog_yesno( 'Alfa', config.get_localized_string(70613), config.get_localized_string(70658), filename): return False if not filetools.write(fullfilename, data): platformtools.dialog_ok('Alfa', config.get_localized_string(70659), filename) platformtools.dialog_ok('Alfa', config.get_localized_string(70660), filename) platformtools.itemlist_refresh() return True
def editar_enlace_thumbnail(item): logger.info() alfav = AlfavoritesData() if not alfav.user_favorites[item.i_perfil]: return False if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False it = Item().fromurl( alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]) # A partir de Kodi 17 se puede usar xbmcgui.Dialog().select con thumbnails (ListItem & useDetails=True) is_kodi17 = (config.get_platform(True)['num_version'] >= 17.0) if is_kodi17: import xbmcgui # Diálogo para escoger thumbnail (el del canal o iconos predefinidos) opciones = [] ids = [] try: from core import channeltools channel_parameters = channeltools.get_channel_parameters(it.channel) if channel_parameters['thumbnail'] != '': nombre = 'Canal %s' % it.channel if is_kodi17: it_thumb = xbmcgui.ListItem(nombre) it_thumb.setArt({'thumb': channel_parameters['thumbnail']}) opciones.append(it_thumb) else: opciones.append(nombre) ids.append(channel_parameters['thumbnail']) except: pass resource_path = os.path.join(config.get_runtime_path(), 'resources', 'media', 'themes', 'default') for f in sorted(os.listdir(resource_path)): if f.startswith('thumb_') and not f.startswith( 'thumb_intervenido') and f != 'thumb_back.png': nombre = f.replace('thumb_', '').replace('_', ' ').replace('.png', '') if is_kodi17: it_thumb = xbmcgui.ListItem(nombre) it_thumb.setArt({'thumb': os.path.join(resource_path, f)}) opciones.append(it_thumb) else: opciones.append(nombre) ids.append(os.path.join(resource_path, f)) if is_kodi17: ret = xbmcgui.Dialog().select('Seleccionar thumbnail:', opciones, useDetails=True) else: ret = platformtools.dialog_select('Seleccionar thumbnail:', opciones) if ret == -1: return False # pedido cancel it.thumbnail = ids[ret] alfav.user_favorites[item.i_perfil]['items'][item.i_enlace] = it.tourl() alfav.save() platformtools.itemlist_refresh() return True
def configuracion(item): ret = platformtools.show_channel_settings() platformtools.itemlist_refresh() return ret
def settingCanal(item): platformtools.show_channel_settings() platformtools.itemlist_refresh() return
def settingCanal(item): from platformcode import platformtools platformtools.show_channel_settings() platformtools.itemlist_refresh() return
def delete(item): def delete_all(_item): for file in filetools.listdir(_item.path): if file.endswith(".strm") or file.endswith( ".nfo") or file.endswith(".json") or file.endswith( ".torrent"): filetools.remove(filetools.join(_item.path, file)) raiz, carpeta_serie, ficheros = next(filetools.walk(_item.path)) if ficheros == []: filetools.rmdir(_item.path) if config.is_xbmc(): import xbmc # esperamos 3 segundos para dar tiempo a borrar los ficheros xbmc.sleep(3000) # TODO mirar por qué no funciona al limpiar en la videoteca de Kodi al añadirle un path # limpiamos la videoteca de Kodi from platformcode import xbmc_videolibrary xbmc_videolibrary.clean() logger.info("Eliminados todos los enlaces") platformtools.itemlist_refresh() # logger.info(item.contentTitle) # logger.debug(item.tostring('\n')) if item.contentType == 'movie': heading = config.get_localized_string(70084) else: heading = config.get_localized_string(70085) if item.multicanal: # Obtener listado de canales if item.dead == '': opciones = [ config.get_localized_string(70086) % k.capitalize() for k in list(item.library_urls.keys()) if k != "downloads" ] opciones.insert(0, heading) index = platformtools.dialog_select( config.get_localized_string(30163), opciones) if index == 0: # Seleccionado Eliminar pelicula/serie delete_all(item) elif index > 0: # Seleccionado Eliminar canal X canal = opciones[index].replace( config.get_localized_string(70079), "").lower() else: return else: canal = item.dead num_enlaces = 0 for fd in filetools.listdir(item.path): if fd.endswith(canal + '].json') or scrapertools.find_single_match( fd, '%s]_\d+.torrent' % canal): if filetools.remove(filetools.join(item.path, fd)): num_enlaces += 1 if num_enlaces > 0: # Actualizar .nfo head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo) del item_nfo.library_urls[canal] if item_nfo.emergency_urls and item_nfo.emergency_urls.get( canal, False): del item_nfo.emergency_urls[canal] filetools.write(item.nfo, head_nfo + item_nfo.tojson()) msg_txt = config.get_localized_string(70087) % (num_enlaces, canal) logger.info(msg_txt) platformtools.dialog_notification(heading, msg_txt) platformtools.itemlist_refresh() else: if platformtools.dialog_yesno( heading, config.get_localized_string(70088) % item.infoLabels['title']): delete_all(item)
def configuracion(item): from platformcode import platformtools ret = platformtools.show_channel_settings() platformtools.itemlist_refresh() return ret
def setting_channel(item): ret = platformtools.show_channel_settings() platformtools.itemlist_refresh() return ret
def force_creation_advancedsettings(item): # advancedsettings path advancedsettings = xbmc.translatePath( "special://userdata/advancedsettings.xml") itemlist = [] try: risp = platformtools.dialog_select('Scegli settaggio cache', [ram[0], ram[1], ram[2], ram[3]]) #logger.info(str(risp)) if risp == 0: valore = opt[0] testo = "\n[COLOR orange]Cache Impostata per 512 Mega di RAM[/COLOR]" if risp == 1: valore = opt[1] testo = "\n[COLOR orange]Cache Impostata per 1 Gb di RAM[/COLOR]" if risp == 2: valore = opt[2] testo = "\n[COLOR orange]Cache Impostata per 2 Gb di RAM[/COLOR]" if risp == 3: valore = opt[3] testo = "\n[COLOR orange]Cache Impostata a superiore di 2 Gb di RAM[/COLOR]" if risp < 0: return itemlist file = '''<advancedsettings> <network> <buffermode>1</buffermode> <cachemembuffersize>''' + valore + '''</cachemembuffersize> <readbufferfactor>10</readbufferfactor> <autodetectpingtime>30</autodetectpingtime> <curlclienttimeout>60</curlclienttimeout> <curllowspeedtime>60</curllowspeedtime> <curlretries>2</curlretries> <disableipv6>true</disableipv6> </network> <gui> <algorithmdirtyregions>0</algorithmdirtyregions> <nofliptimeout>0</nofliptimeout> </gui> <playlistasfolders1>false</playlistasfolders1> <audio> <defaultplayer>dvdplayer</defaultplayer> </audio> <imageres>540</imageres> <fanartres>720</fanartres> <splash>false</splash> <handlemounting>0</handlemounting> <samba> <clienttimeout>30</clienttimeout> </samba> </advancedsettings>''' logger.info(file) salva = open(advancedsettings, "w") salva.write(file) salva.close() except: pass platformtools.dialog_ok("plugin", "E' stato creato un file advancedsettings.xml", "con la configurazione ideale per lo streaming.", testo) return platformtools.itemlist_refresh()
def delete(item): def delete_all(_item): filetools.rmdirtree(_item.path) if config.is_xbmc(): import xbmc # esperamos 3 segundos para dar tiempo a borrar los ficheros xbmc.sleep(3000) # TODO mirar por qué no funciona al limpiar en la videoteca de Kodi al añadirle un path # limpiamos la videoteca de Kodi from platformcode import xbmc_videolibrary xbmc_videolibrary.clean() logger.info("Eliminados todos los enlaces") platformtools.itemlist_refresh() # logger.info(item.contentTitle) # logger.debug(item.tostring('\n')) if item.contentType == 'movie': heading = "Eliminar película" else: heading = "Eliminar serie" if item.multicanal: # Obtener listado de canales opciones = [ "Eliminar solo los enlaces de %s" % k.capitalize() for k in item.library_urls.keys() if k != "downloads" ] opciones.insert(0, heading) index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index == 0: # Seleccionado Eliminar pelicula/serie delete_all(item) elif index > 0: # Seleccionado Eliminar canal X canal = opciones[index].replace("Eliminar solo los enlaces de ", "").lower() num_enlaces = 0 for fd in filetools.listdir(item.path): if fd.endswith(canal + '].json'): if filetools.remove(filetools.join(item.path, fd)): num_enlaces += 1 if num_enlaces > 0: # Actualizar .nfo head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo) del item_nfo.library_urls[canal] filetools.write(item.nfo, head_nfo + item_nfo.tojson()) msg_txt = "Eliminados %s enlaces del canal %s" % (num_enlaces, canal) logger.info(msg_txt) platformtools.dialog_notification(heading, msg_txt) platformtools.itemlist_refresh() else: if platformtools.dialog_yesno( heading, "¿Realmente desea eliminar '%s' de su videoteca?" % item.infoLabels['title']): delete_all(item)
def delete_file(item): os.remove(item.url) platformtools.itemlist_refresh() return
def seasons(item): logger.info() id = "0" itemlist = [] infoLabels = item.infoLabels ## Carga estados status = check_status() url_targets = item.url if "###" in item.url: id = item.url.split("###")[1].split(";")[0] type = item.url.split("###")[1].split(";")[1] item.url = item.url.split("###")[0] data = agrupa_datos(item.url) if account: str = get_status(status, "shows", id) #TODO desenredar todo el lio este if str != "" and item.category != "Series" and "XBMC" not in item.title: platformtools.itemlist_refresh() title = str.replace('steelblue', 'darkgrey').replace('Siguiendo', 'Abandonar') itemlist.append( Item(channel=item.channel, action="set_status", title=title, url=url_targets, thumbnail=item.thumbnail, contentSerieName=item.contentSerieName, folder=True)) elif item.category != "Series" and "XBMC" not in item.title: title = " [COLOR steelblue][B]( Seguir )[/B][/COLOR]" itemlist.append( Item(channel=item.channel, action="set_status", title=title, url=url_targets, thumbnail=item.thumbnail, contentSerieName=item.contentSerieName, folder=True)) sid = scrapertools.find_single_match(data, "<script>var sid = '(\d+)'") patron = 'itemprop="season".*?<a href=\'.*?/temporada-(\d+).*?' patron += 'alt="([^"]+)" src="([^"]+)"' matches = re.compile(patron, re.DOTALL).findall(data) for ssid, scrapedtitle, scrapedthumbnail in matches: if ssid == '0': scrapedtitle = "Especiales" infoLabels['season'] = ssid thumbnail = scrapedthumbnail.replace('tthumb/130x190', 'thumbs') thumbnail += '|User-Agent=%s' % httptools.get_user_agent() itemlist.append( Item(channel=item.channel, action="episodesxseason", title=scrapedtitle, url=item.url, thumbnail=thumbnail, sid=sid, text_bold=True, contentSerieName=item.contentSerieName, contentSeasonNumber=ssid, infoLabels=infoLabels)) if config.get_videolibrary_support() and len(itemlist) > 0: itemlist.append( Item( channel=item.channel, title= "[COLOR greenyellow]Añadir esta serie a la videoteca[/COLOR]", action="add_serie_to_library", url=item.url, text_bold=True, extra="episodios", contentSerieName=item.contentSerieName, )) return itemlist
def clear_saved_searches(item): config.set_setting("saved_searches_list", list(), "search") platformtools.dialog_ok(config.get_localized_string(60423), config.get_localized_string(60424)) platformtools.itemlist_refresh()
def settings(item): ret = platformtools.show_channel_settings( caption="configuración -- Descargas") platformtools.itemlist_refresh() return ret
def menu(item): logger.info() if item.downloadServer: servidor = item.downloadServer.get("server", "Auto") else: servidor = "Auto" # Opciones disponibles para el menu op = [ "Descargar", "Eliminar de la lista", "Reiniciar descarga y eliminar datos", "Modificar servidor: %s" % (servidor.capitalize()) ] opciones = [] # Opciones para el menu if item.downloadStatus == 0: # Sin descargar opciones.append(op[0]) # Descargar if not item.server: opciones.append(op[3]) # Elegir Servidor opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 1: # descarga parcial opciones.append(op[0]) # Descargar if not item.server: opciones.append(op[3]) # Elegir Servidor opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 2: # descarga completada opciones.append(op[1]) # Eliminar de la lista opciones.append(op[2]) # Reiniciar descarga if item.downloadStatus == 3: # descarga con error opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista # Mostramos el dialogo seleccion = platformtools.dialog_select("Elige una opción", opciones) # -1 es cancelar if seleccion == -1: return logger.info("opcion=%s" % (opciones[seleccion])) # Opcion Eliminar if opciones[seleccion] == op[1]: filetools.remove(item.path) # Opcion inicaiar descarga if opciones[seleccion] == op[0]: start_download(item) # Elegir Servidor if opciones[seleccion] == op[3]: select_server(item) # Reiniciar descarga if opciones[seleccion] == op[2]: if filetools.isfile( os.path.join(config.get_setting("downloadpath"), item.downloadFilename)): filetools.remove( os.path.join(config.get_setting("downloadpath"), item.downloadFilename)) update_json( item.path, { "downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0, "downloadServer": {} }) platformtools.itemlist_refresh()
def findvideos(item): from core import autoplay from platformcode import platformtools logger.debug() # logger.debug("item:\n" + item.tostring('\n')) videolibrarytools.check_renumber_options(item) itemlist = [] list_canales = {} item_local = None # Disable autoplay # autoplay.set_status(False) if not item.contentTitle or not item.strm_path: logger.debug("Unable to search for videos due to lack of parameters") return [] if item.contentEpisodeNumber: content_title = str(item.contentSeason) + 'x' + (str(item.contentEpisodeNumber) if item.contentEpisodeNumber > 9 else '0' + str(item.contentEpisodeNumber)) else: content_title = item.contentTitle.strip().lower() if item.contentType == 'movie': item.strm_path = filetools.join(videolibrarytools.MOVIES_PATH, item.strm_path) path_dir = filetools.dirname(item.strm_path) item.nfo = filetools.join(path_dir, filetools.basename(path_dir) + ".nfo") else: item.strm_path = filetools.join(videolibrarytools.TVSHOWS_PATH, item.strm_path) path_dir = filetools.dirname(item.strm_path) item.nfo = filetools.join(path_dir, 'tvshow.nfo') for fd in filetools.listdir(path_dir): if fd.endswith('.json'): contenido, nom_canal = fd[:-6].split('[') if (contenido.startswith(content_title) or item.contentType == 'movie') and nom_canal not in list(list_canales.keys()): list_canales[nom_canal] = filetools.join(path_dir, fd) num_canales = len(list_canales) if 'downloads' in list_canales: json_path = list_canales['downloads'] item_json = Item().fromjson(filetools.read(json_path)) item_json.contentChannel = "local" # Support for relative paths in downloads if filetools.is_relative(item_json.url): item_json.url = filetools.join(videolibrarytools.VIDEOLIBRARY_PATH, item_json.url) del list_canales['downloads'] # Check that the video has not been deleted if filetools.exists(item_json.url): item_local = item_json.clone(action='play') itemlist.append(item_local) else: num_canales -= 1 filtro_canal = '' if num_canales > 1 and config.get_setting("ask_channel", "videolibrary"): opciones = [config.get_localized_string(70089) % k.capitalize() for k in list(list_canales.keys())] opciones.insert(0, config.get_localized_string(70083)) if item_local: opciones.append(item_local.title) index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index < 0: return [] elif item_local and index == len(opciones) - 1: filtro_canal = 'downloads' platformtools.play_video(item_local) elif index > 0: filtro_canal = opciones[index].replace(config.get_localized_string(70078), "").strip() itemlist = [] all_videolibrary = [] for nom_canal, json_path in list(list_canales.items()): if filtro_canal and filtro_canal != nom_canal.capitalize(): continue item_canal = Item() # We import the channel of the selected part try: if nom_canal == 'community': channel = __import__('specials.%s' % nom_canal, fromlist=["channels.%s" % nom_canal]) else: channel = __import__('channels.%s' % nom_canal, fromlist=["channels.%s" % nom_canal]) except ImportError: exec("import channels." + nom_canal + " as channel") except: dead_list = [] zombie_list = [] if nom_canal not in dead_list and nom_canal not in zombie_list: confirm = platformtools.dialog_yesno(config.get_localized_string(30131), config.get_localized_string(30132) % nom_canal.upper() + '\n' + config.get_localized_string(30133)) elif nom_canal in zombie_list: confirm = False else: confirm = True if confirm: # delete the channel from all movie and tvshow from past.utils import old_div num_enlaces = 0 dialog = platformtools.dialog_progress(config.get_localized_string(30131), config.get_localized_string(60005) % nom_canal) if not all_videolibrary: all_videolibrary = list_movies(Item()) + list_tvshows(Item()) for n, it in enumerate(all_videolibrary): if nom_canal in it.library_urls: dead_item = Item(multichannel=len(it.library_urls) > 1, contentType=it.contentType, dead=nom_canal, path=filetools.split(it.nfo)[0], nfo=it.nfo, library_urls=it.library_urls, infoLabels={'title': it.contentTitle}) num_enlaces += delete(dead_item) dialog.update(old_div(100*n, len(all_videolibrary))) dialog.close() msg_txt = config.get_localized_string(70087) % (num_enlaces, nom_canal) logger.info(msg_txt) platformtools.dialog_notification(config.get_localized_string(30131), msg_txt) platformtools.itemlist_refresh() if nom_canal not in dead_list: dead_list.append(nom_canal) continue else: if nom_canal not in zombie_list: zombie_list.append(nom_canal) if len(dead_list) > 0: for nom_canal in dead_list: if nom_canal in item.library_urls: del item.library_urls[nom_canal] item_json = Item().fromjson(filetools.read(json_path)) list_servers = [] try: # FILTERTOOLS # if the channel has a filter, the name it has saved is passed to it so that it filters correctly. if "list_language" in item_json: # if it comes from the addon video library if "library_filter_show" in item: item_json.show = item.library_filter_show.get(nom_canal, "") # We run find_videos, from the channel or common item_json.contentChannel = 'videolibrary' item_json.play_from = item.play_from item_json.nfo = item.nfo item_json.strm_path = item.strm_path if hasattr(channel, 'findvideos'): from core import servertools if item_json.videolibray_emergency_urls: del item_json.videolibray_emergency_urls list_servers = getattr(channel, 'findvideos')(item_json) elif item_json.action == 'play': from platformcode import platformtools # autoplay.set_status(True) item_json.contentChannel = item_json.channel item_json.channel = "videolibrary" platformtools.play_video(item_json) return '' else: from core import servertools list_servers = servertools.find_video_items(item_json) except Exception as ex: logger.error("The findvideos function for the channel %s failed" % nom_canal) template = "An exception of type %s occured. Arguments:\n%r" message = template % (type(ex).__name__, ex.args) logger.error(message) logger.error(traceback.format_exc()) # Change the title to the servers adding the name of the channel in front and the infoLabels and the images of the item if the server does not have for server in list_servers: server.contentChannel = server.channel server.channel = "videolibrary" server.nfo = item.nfo server.strm_path = item.strm_path server.play_from = item.play_from # Kodi 18 Compatibility - Prevents wheel from spinning around in Direct Links if server.action == 'play': server.folder = False # Channel name is added if desired if config.get_setting("quit_channel_name", "videolibrary") == 0: server.title = "%s: %s" % (nom_canal.capitalize(), server.title) if not server.thumbnail: server.thumbnail = item.thumbnail # logger.debug("server:\n%s" % server.tostring('\n')) itemlist.append(server) if autoplay.play_multi_channel(item, itemlist): # hideserver return [] add_download_items(item, itemlist) return itemlist
def menu(item): logger.info() # Opciones disponibles para el menu op = [ "Download", "Elimina dalla lista", "Reiniziallizza download", "Scarica da..." ] opciones = [] # Opciones para el menu if item.downloadStatus == 0: # Sin descargar opciones.append(op[0]) # Descargar opciones.append(op[3]) # Descargar desde... opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 1: # descarga parcial opciones.append(op[0]) # Descargar opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista if item.downloadStatus == 2: # descarga completada opciones.append(op[1]) # Eliminar de la lista opciones.append(op[2]) # Reiniciar descarga if item.downloadStatus == 3: # descarga con error opciones.append(op[2]) # Reiniciar descarga opciones.append(op[1]) # Eliminar de la lista # Mostramos el dialogo seleccion = platformtools.dialog_select("Scegli un'opzione", opciones) # -1 es cancelar if seleccion == -1: return logger.info("opcion=%s" % (opciones[seleccion])) # Opcion Eliminar if opciones[seleccion] == op[1]: filetools.remove(item.path) # Opcion inicaiar descarga if opciones[seleccion] == op[0]: start_download(item) # Opcion inicaiar descarga desde... if opciones[seleccion] == op[3]: start_download(item, ask=True) # Reiniciar descarga if opciones[seleccion] == op[2]: if filetools.isfile( os.path.join(config.get_setting("downloadpath"), item.downloadFilename)): filetools.remove( os.path.join(config.get_setting("downloadpath"), item.downloadFilename)) update_json( item.path, { "downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0 }) platformtools.itemlist_refresh()
def acciones_cuenta(item): logger.info() itemlist = [] if "Tus fichas" in item.title: itemlist.append( item.clone(title="Capítulos", url="tf_block_c a", contentType="tvshow")) itemlist.append( item.clone(title="Series", url="tf_block_s", contentType="tvshow")) itemlist.append(item.clone(title="Películas", url="tf_block_p")) itemlist.append(item.clone(title="Documentales", url="tf_block_d")) return itemlist elif "Añadir a una lista" in item.title: data = httptools.downloadpage(host + "/c_listas.php?apikey=%s&sid=%s" % (apikey, sid)).data data = json.Xml2Json(data).result itemlist.append(item.clone(title="Crear nueva lista", folder=False)) if data["Data"]["TusListas"] != "\t": import random data = data["Data"]["TusListas"]["Item"] if type(data) is not list: data = [data] for child in data: image = "" title = "%s (%s fichas)" % (child["Title"], child["FichasInList"]) images = [] for i in range(1, 5): if "sinimagen.png" not in child["Poster%s" % i]: images.append(child["Poster%s" % i].replace( "/100/", "/400/")) if images: image = images[random.randint(0, len(images) - 1)] url = host + "/data.php?mode=add_listas&apikey=%s&sid=%s&ficha_id=%s" % ( apikey, sid, item.ficha) post = "lista_id[]=%s" % child["Id"] itemlist.append( item.clone(title=title, url=url, post=post, thumbnail=image, folder=False)) return itemlist elif "Crear nueva lista" in item.title: from platformcode import platformtools nombre = platformtools.dialog_input( "", "Introduce un nombre para la lista") if nombre: dict_priv = {0: 'Pública', 1: 'Privada'} priv = platformtools.dialog_select("Privacidad de la lista", ['Pública', 'Privada']) if priv != -1: url = host + "/data.php?mode=create_list&apikey=%s&sid=%s" % ( apikey, sid) post = "name=%s&private=%s" % (nombre, priv) data = httptools.downloadpage(url, post) platformtools.dialog_notification( "Lista creada correctamente", "Nombre: %s - %s" % (nombre, dict_priv[priv])) platformtools.itemlist_refresh() return elif re.search(r"(?i)Seguir Lista", item.title): from platformcode import platformtools data = httptools.downloadpage(item.url) platformtools.dialog_notification("Operación realizada con éxito", "Lista: %s" % item.lista) return elif item.post: from platformcode import platformtools data = httptools.downloadpage(item.url, item.post).data platformtools.dialog_notification("Ficha añadida a la lista", "Lista: %s" % item.title) platformtools.itemlist_refresh() return data = httptools.downloadpage("https://playmax.mx/tusfichas.php").data data = re.sub(r"\n|\r|\t|\s{2}| |<br>", "", data) bloque = scrapertools.find_single_match( data, item.url + '">(.*?)(?:<div class="tf_blocks|<div class="tf_o_move">)') matches = scrapertools.find_multiple_matches( bloque, '<div class="tf_menu_mini">([^<]+)<(.*?)<cb></cb></div>') for category, contenido in matches: itemlist.append( item.clone(action="", title=category, text_color=color3)) patron = '<div class="c_fichas_image">.*?href="\.([^"]+)".*?src="\.([^"]+)".*?serie="([^"]*)".*?' \ '<div class="c_fichas_title">(?:<div class="c_fichas_episode">([^<]+)</div>|)([^<]+)</div>' entradas = scrapertools.find_multiple_matches(contenido, patron) for scrapedurl, scrapedthumbnail, serie, episodio, scrapedtitle in entradas: tipo = "movie" scrapedurl = host + scrapedurl scrapedthumbnail = host + scrapedthumbnail action = "findvideos" if __menu_info__: action = "menu_info" if serie: tipo = "tvshow" if episodio: title = " %s - %s" % (episodio.replace("X", "x"), scrapedtitle) else: title = " " + scrapedtitle new_item = Item(channel=item.channel, action=action, title=title, url=scrapedurl, thumbnail=scrapedthumbnail, contentTitle=scrapedtitle, contentType=tipo, text_color=color2) if new_item.contentType == "tvshow": new_item.show = scrapedtitle if not __menu_info__: new_item.action = "episodios" itemlist.append(new_item) return itemlist
def acciones_enlace(item): logger.info() item.__dict__['channel'] = item.__dict__.pop('from_channel') item.__dict__['action'] = item.__dict__.pop('from_action') if item.downloadStatus == STATUS_CODES.completed: acciones = [ 'Reproducir vídeo', 'Eliminar descarga', 'Guardar una copia' ] elif item.downloadStatus == STATUS_CODES.canceled: acciones = ['Continuar descarga', 'Eliminar descarga'] # ~ elif item.downloadStatus == STATUS_CODES.error: else: acciones = ['Eliminar descarga'] ret = platformtools.dialog_select('¿Qué hacer con esta descarga?', acciones) if ret == -1: return False # pedido cancel elif acciones[ret] == 'Eliminar descarga': if not platformtools.dialog_yesno( 'Eliminar descarga', '¿ Confirmas el borrado de la descarga %s ?' % item.title, 'Se eliminará el fichero %s y su json con la información.' % item.downloadFilename): return False path_video = filetools.join(download_path, item.downloadFilename) if item.downloadFilename and filetools.exists(path_video): filetools.remove(path_video) if item.jsonfile and filetools.exists(item.jsonfile): filetools.remove(item.jsonfile) platformtools.itemlist_refresh() return True elif acciones[ret] == 'Continuar descarga': item.__dict__.pop('jsonfile') server_item = Item().fromjson(item.__dict__.pop('server_item')) return download_video(server_item, item) elif acciones[ret] == 'Reproducir vídeo': import xbmcgui, xbmc mediaurl = filetools.join(download_path, item.downloadFilename) xlistitem = xbmcgui.ListItem(path=mediaurl) platformtools.set_infolabels(xlistitem, item, True) # se lanza el reproductor (no funciona si el play es desde el diálogo info !?) playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(mediaurl, xlistitem) xbmc.Player().play(playlist, xlistitem) return True elif acciones[ret] == 'Guardar una copia': import xbmcgui destino_path = xbmcgui.Dialog().browseSingle( 3, 'Seleccionar carpeta dónde copiar', 'files', '', False, False, '') if not destino_path: return False origen = filetools.join(download_path, item.downloadFilename) destino = filetools.join(destino_path, item.downloadFilename) if not filetools.copy(origen, destino, silent=False): platformtools.dialog_ok( config.__addon_name, 'Error, no se ha podido copiar el fichero!', origen, destino) return False platformtools.dialog_notification('Fichero copiado', destino_path) return True
def add_channel(item): logger.debug() channel_to_add = {} json_file = '' result = platformtools.dialog_select(config.get_localized_string(70676), [ config.get_localized_string(70678), config.get_localized_string(70679) ]) if result == -1: return if result == 0: file_path = xbmcgui.Dialog().browseSingle( 1, config.get_localized_string(70680), 'files') try: channel_to_add['path'] = file_path channel_to_add['url'] = file_path json_file = jsontools.load(open(file_path, "r").read()) channel_to_add['channel_name'] = json_file['channel_name'] except: pass elif result == 1: url = platformtools.dialog_input("", config.get_localized_string(70681), False) try: if url[:4] != 'http': url = 'http://' + url channel_to_add['path'] = url json_file = jsontools.load(httptools.downloadpage(url).data) except: pass if len(json_file) == 0: return if "episodes_list" in json_file: platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(70682)) return channel_to_add['channel_name'] = json_file['channel_name'] if 'thumbnail' in json_file: channel_to_add['thumbnail'] = json_file['thumbnail'] if 'fanart' in json_file: channel_to_add['fanart'] = json_file['fanart'] path = filetools.join(config.get_data_path(), 'community_channels.json') community_json = open(path, "r") community_json = jsontools.load(community_json.read()) id = 1 while str(id) in community_json['channels']: id += 1 community_json['channels'][str(id)] = (channel_to_add) with open(path, "w") as file: file.write(jsontools.dump(community_json)) file.close() platformtools.dialog_notification( config.get_localized_string(20000), config.get_localized_string(70683) % json_file['channel_name']) import xbmc xbmc.sleep(1000) platformtools.itemlist_refresh() return
def eliminar(item): def eliminar_todo(_item): path = (_item.path).decode("utf8") ficheros = os.listdir(path) for file in ficheros: if file.endswith(".strm") or file.endswith(".sod") or file.endswith(".json"): os.remove(filetools.join(path, file)) if not os.listdir(path): filetools.rmdirtree(path) if config.is_xbmc(): import xbmc # esperamos 3 segundos para dar tiempo a borrar los ficheros xbmc.sleep(3000) # TODO mirar por qué no funciona al limpiar en la biblioteca de Kodi al añadirle un path # limpiamos la biblioteca de Kodi from platformcode import xbmc_library xbmc_library.clean() logger.info("Eliminados todos los enlaces") platformtools.itemlist_refresh() # logger.info(item.contentTitle) # logger.debug(item.tostring('\n')) if item.contentType == 'movie': heading = "Rimuovere film" else: heading = "Rimuovere serie" if item.multicanal: # Obtener listado de canales opciones = ["Rimuovere solo i link dei %s" % k.capitalize() for k in item.library_urls.keys() if k !="descargas"] opciones.insert(0, heading) index = platformtools.dialog_select(config.get_localized_string(30163), opciones) if index == 0: # Seleccionado Eliminar pelicula/serie eliminar_todo(item) elif index > 0: # Seleccionado Eliminar canal X canal = opciones[index].replace("Rimuovere solo i link dei ", "").lower() num_enlaces = 0 for fd in filetools.listdir(item.path): if fd.endswith(canal + '].json'): if filetools.remove(filetools.join(item.path, fd)): num_enlaces += 1 if num_enlaces > 0: # Actualizar .nfo head_nfo, item_nfo = library.read_nfo(item.nfo) del item_nfo.library_urls[canal] filetools.write(item.nfo, head_nfo + item_nfo.tojson()) msg_txt = "Cancellati %s collegamenti del canale %s" % (num_enlaces, canal) logger.info(msg_txt) platformtools.dialog_notification(heading, msg_txt) platformtools.itemlist_refresh() else: if platformtools.dialog_yesno(heading, "Vuoi davvero eliminare '%s' dalla tua libreria?" % item.infoLabels['title']): eliminar_todo(item)