def newest(categoria): logger.info() itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://www.cinefox.tv/catalogue?type=peliculas" item.action = "peliculas" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() if categoria == "series": item.url = "http://www.cinefox.tv/ultimos-capitulos" item.action = "ultimos" itemlist = ultimos(item) if itemlist[-1].action == "ultimos": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("streamondemand.altadefinizione01 newest" + categoria) itemlist = [] item = Item() try: if categoria == "series": item.url = "https://www.dreamsub.it" item.action = "ultimiep" item.extra = "serie" itemlist = ultimiep(item) if itemlist[-1].action == "ultimiep": itemlist.pop() if categoria == "anime": item.url = "https://www.dreamsub.it" item.action = "ultimiep" item.extra = "anime" itemlist = ultimiep(item) if itemlist[-1].action == "ultimiep": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def get_episodios(item): logger.info("pelisalacarta.channels.biblioteca get_episodios") itemlist = [] # Obtenemos los archivos de los episodios raiz, carpetas_series, ficheros = filetools.walk(item.path).next() # Crear un item en la lista para cada strm encontrado for i in ficheros: # strm if i.endswith(".strm"): season, episode = scrapertools.get_season_and_episode(i).split("x") # Si hay q filtrar por temporada, ignoramos los capitulos de otras temporadas if item.filtrar_season and int(season) != int(item.contentSeason): continue epi = Item().fromurl(filetools.read(filetools.join(raiz, i))) epi.contentChannel = item.contentChannel epi.path = filetools.join(raiz, i) epi.title = i epi.channel = "biblioteca" epi.action = "findvideos" epi.contentEpisodeNumber = episode epi.contentSeason = season # fix sobreescribe el color del texto si viene pasado en el strm epi.text_color = "" # fix para que no se ejecute el método de play para la biblioteca de Kodi epi.strm = False itemlist.append(epi) # videos elif not i.endswith(".nfo") and not i.endswith(".json") and not i.endswith(".srt"): season, episode = scrapertools.get_season_and_episode(i).split("x") # Si hay q filtrar por temporada, ignoramos los capitulos de otras temporadas if item.filtrar_season and int(season) != int(item.contentSeason): continue epi = Item() epi.contentChannel = "local" epi.path = filetools.join(raiz, i) epi.title = i epi.channel = "biblioteca" epi.action = "play" epi.contentEpisodeNumber = episode epi.contentSeason = season itemlist.append(epi) library.set_infolabels_from_library(itemlist, tipo="Episodes") return sorted(itemlist, key=get_sort_temp_epi)
def newest(categoria): itemlist = [] item = Item() try: if categoria == 'peliculas': item.url = urlparse.urljoin(__url_base__,"plugins/ultimas-peliculas-updated.php") item.extra = "movie" elif categoria == 'infantiles': item.url = urlparse.urljoin(__url_base__, "plugins/ultimas-peliculas-updated.php") item.filtro=("genero","animación") item.extra = "movie" elif categoria == 'series': item.url = urlparse.urljoin(__url_base__,"plugins/ultimos-capitulos-updated.php") item.extra="series_novedades" else: return [] item.action = "listado" itemlist = listado(item) if itemlist[-1].action == "listado": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def actionexecute(sender, itemtext): Log("[__init__.py] actionexecute") item = Item() item.deserialize(itemtext) Log("[__init__.py] " + item.tostring()) dir = MediaContainer(viewGroup="InfoList") if item.action == "": item.action = "mainlist" Log("[__init__.py] action=" + item.action) exec "from tvalacarta.channels import " + item.channel if item.action == "findvideos": try: exec "itemlist = " + item.channel + "." + item.action + "(item)" except: itemlist = findvideos(item) else: exec "itemlist = " + item.channel + "." + item.action + "(item)" for item in itemlist: item.title = encodingsafe(item.title) item.plot = encodingsafe(item.plot) Log("item=" + item.tostring()) if item.folder: if item.action == "search": dir.Append( Function( InputDirectoryItem(do_search, item.title, "subtitle", "txt", thumb=item.thumbnail), itemtext=item.serialize(), ) ) else: dir.Append( Function( DirectoryItem(actionexecute, title=item.title, subtitle="subtitle", thumb=item.thumbnail), itemtext=item.serialize(), ) ) else: dir.Append( Function( DirectoryItem(playvideo, title=item.title, subtitle="", summary=item.plot, thumb=item.thumbnail), itemtext=item.serialize(), ) ) Log("[__init__.py] 5") return dir
def newest(categoria): logger.info() itemlist = [] item = Item() try: if categoria == 'peliculas': item.url = CHANNEL_HOST item.action = "peliculas" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() elif categoria == 'documentales': item.url = urlparse.urljoin(CHANNEL_HOST, "genero/documental/") item.action = "peliculas" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() elif categoria == 'infantiles': item.url = urlparse.urljoin(CHANNEL_HOST, "genero/infantil/") item.action = "peliculas" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def busqueda(item): logger.info("pelisalacarta.channels.vixto busqueda") itemlist = list() # Descarga la página data = scrapertools.downloadpage(item.url) data = re.sub(r"\n|\r|\t| |\s{2}", "", data) # Extrae las entradas (carpetas) bloque = scrapertools.find_single_match(data, '<h2>Peliculas</h2>(.*?)</div>') bloque += scrapertools.find_single_match(data, '<h2>Series</h2>(.*?)</div>') patron = '<figure class="col-lg-2.*?href="([^"]+)".*?src="([^"]+)".*?<figcaption title="([^"]+)"' matches = scrapertools.find_multiple_matches(bloque, patron) peliculas = False series = False for scrapedurl, scrapedthumbnail, scrapedtitle in matches: new_item = Item(channel=item.channel, contentType="movie", url=scrapedurl, title=" "+scrapedtitle, text_color=color1, context="buscar_trailer", fulltitle=scrapedtitle, contentTitle=scrapedtitle, thumbnail=scrapedthumbnail, action="findvideos") if "/peliculas/" in scrapedurl and not peliculas: itemlist.append(Item(channel=item.channel, action="", title="Películas", text_color=color2)) peliculas = True if "/series/" in scrapedurl and not series: itemlist.append(Item(channel=item.channel, action="", title="Series", text_color=color2)) series = True if "/series/" in scrapedurl: new_item.contentType = "tvshow" new_item.show = scrapedtitle new_item.action = "episodios" filtro_thumb = scrapedthumbnail.replace("http://image.tmdb.org/t/p/w342", "") filtro_list = {"poster_path": filtro_thumb} new_item.infoLabels["filtro"] = filtro_list.items() itemlist.append(new_item) try: tmdb.set_infoLabels_itemlist(itemlist, __modo_grafico__) except: pass return itemlist
def newest(categoria): log("newest", "newest" + categoria) itemlist = [] item = Item() try: if categoria == "anime": item.url = "http://animeforce.org" item.action = "ultimiep" itemlist = ultimiep(item) if itemlist[-1].action == "ultimiep": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("streamondemand.ilgeniodellostreaming newest" + categoria) itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://ilgeniodellostreaming.cc/film/" item.action = "peliculas" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info() itemlist = [] item = Item() try: if categoria == 'peliculas': item.url = "http://www.clasicofilm.com/feeds/posts/summary?start-index=1&max-results=20&alt=json-in-script&callback=finddatepost" item.action = "peliculas" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("[itastreaming.py] newest" + categoria) itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://itastreaming.gratis/nuove-uscite/" item.action = "fichas" itemlist = fichas(item) if itemlist[-1].action == "fichas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("[cinemalibero.py] newest" + categoria) itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://www.cinemalibero.tv/category/film/" item.action = "peliculas" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("[SerieTVU.py]==> newest" + categoria) itemlist = [] item = Item() try: if categoria == "series": item.url = "http://www.serietvu.com/ultimi-episodi" item.action = "latestep" itemlist = latestep(item) if itemlist[-1].action == "latestep": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("[GuardaSerieOnline.py]==> newest" + categoria) itemlist = [] item = Item() try: if categoria == "series": item.url = "http://www.guardaserie.online/lista-serie-tv" item.action = "serietvaggiornate" itemlist = serietvaggiornate(item) if itemlist[-1].action == "serietvaggiornate": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info() itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://allpeliculas.co/Movies/fullView/1/0/&ajax=1" item.action = "lista" itemlist = lista(item) if itemlist[-1].action == "lista": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("[AltadefinizioneHD.py]==> newest " + categoria) itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://altadefinizionehd.com" item.action = "ultimifilm" itemlist = ultimifilm(item) if itemlist[-1].action == "ultimifilm": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("streamondemand.documentaristreamingdb newest" + categoria) itemlist = [] item = Item() try: if categoria == "documentales": item.url = "http://www.documentari-streaming-db.com/?searchtype=movie&post_type=movie&sl=lasts&s=" item.action = "peliculas" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("filmhdstreaming newest" + categoria) itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://filmhdstreaming.org/page/1.html" item.action = "elenco" itemlist = elenco(item) if itemlist[-1].action == "elenco": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info() itemlist = [] item = Item() try: if categoria == "documentales": item.url = "http://www.area-documental.com/resultados-reciente.php?buscar=&genero=" item.action = "entradas" itemlist = entradas(item) if itemlist[-1].action == "entradas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info() itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://www.inkapelis.com/" item.action = "entradas" item.extra = "Novedades" itemlist = entradas(item) if itemlist[-1].action == "entradas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info("[italiafilm.py] newest" + categoria) itemlist = [] item = Item() try: if categoria == "peliculas": item.url = "http://www.italia-film.gratis/category/film-streaming-%s/" % date.today().year item.action = "peliculas" item.extra = "movie" itemlist = peliculas(item) if itemlist[-1].action == "peliculas": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
def newest(categoria): logger.info() itemlist = [] item = Item() try: if categoria == 'series': item.channel = "verseriesynovelas" item.extra = "newest" item.url = "http://www.verseriesynovelas.tv/archivos/nuevo" item.action = "novedades" itemlist = novedades(item) if itemlist[-1].action == "novedades": itemlist.pop() # Se captura la excepción, para no interrumpir al canal novedades si un canal falla except: import sys for line in sys.exc_info(): logger.error("{0}".format(line)) return [] return itemlist
if not filetools.exists(tvshow_path): # Creamos tvshow.nfo, si no existe, con la head_nfo, info de la serie y marcas de episodios vistos logger.info("Creando tvshow.nfo: " + tvshow_path) head_nfo = scraper.get_nfo(item) item_tvshow = Item(title=item.contentTitle, channel="biblioteca", action="get_temporadas", fanart=item.infoLabels['fanart'], thumbnail=item.infoLabels['thumbnail'], infoLabels=item.infoLabels, path=path.replace(TVSHOWS_PATH, "")) item_tvshow.library_playcounts = {} item_tvshow.library_urls = {item.channel: item.url} else: # Si existe tvshow.nfo, pero estamos añadiendo un nuevo canal actualizamos el listado de urls head_nfo, item_tvshow = read_nfo(tvshow_path) item_tvshow.channel = "biblioteca" item_tvshow.action = "get_temporadas" item_tvshow.library_urls[item.channel] = item.url # FILTERTOOLS # si el canal tiene filtro de idiomas, añadimos el canal y el show if episodelist and "list_language" in episodelist[0]: # si ya hemos añadido un canal previamente con filtro, añadimos o actualizamos el canal y show if "library_filter_show" in item_tvshow: item_tvshow.library_filter_show[item.channel] = item.show # no habia ningún canal con filtro y lo generamos por primera vez else: item_tvshow.library_filter_show = {item.channel: item.show} if item.channel != "descargas": item_tvshow.active = 1 # para que se actualice a diario cuando se llame a library_service
item.infoLabels['title'] = item.contentSerieName item_tvshow = Item(title=item.contentSerieName, channel="videolibrary", action="get_seasons", fanart=item.infoLabels['fanart'], thumbnail=item.infoLabels['thumbnail'], infoLabels=item.infoLabels, path=path.replace(TVSHOWS_PATH, "")) item_tvshow.library_playcounts = {} item_tvshow.library_urls = {item.channel: item.url} else: # Si existe tvshow.nfo, pero estamos añadiendo un nuevo canal actualizamos el listado de urls head_nfo, item_tvshow = read_nfo(tvshow_path) item_tvshow.channel = "videolibrary" item_tvshow.action = "get_seasons" item_tvshow.library_urls[item.channel] = item.url # FILTERTOOLS # si el canal tiene filtro de idiomas, añadimos el canal y el show if episodelist and "list_language" in episodelist[0]: # si ya hemos añadido un canal previamente con filtro, añadimos o actualizamos el canal y show if "library_filter_show" in item_tvshow: if item.title_from_channel: item_tvshow.library_filter_show[ item.channel] = item.title_from_channel else: item_tvshow.library_filter_show[item.channel] = item.show # no habia ningún canal con filtro y lo generamos por primera vez else: if item.title_from_channel:
def mainlist(item): logger.info("pelisalacarta.channels.descargas mainlist") itemlist = [] status_color = {0: "orange", 1: "orange", 2: "green", 3: "red"} item.url = config.get_setting("downloadlistpath") series = {} for file in sorted(filetools.listdir(item.url)): file = os.path.join(item.url, file) # Saltamos los archivos que no sean .json if not file.endswith(".json"): continue i = Item().fromjson(filetools.read(file)) i.path = file i.thumbnail = i.contentThumbnail #item.serie_name significa que estamos desntro de una serie if not item.serie_name: # Series if i.contentType == "episode": serie_name = "%s [%s]" % (i.contentSerieName, i.contentChannel) if not serie_name in series: title = serie_name series = {serie_name: {"downloadProgress": [i.downloadProgress], "downloadStatus": [i.downloadStatus]}} i.title=title i.contentSeason = "" i.contntEpisodeNumber = "" i.action = "mainlist" i.serie_name = serie_name itemlist.append(i) else: series[serie_name]["downloadProgress"].append(i.downloadProgress) series[serie_name]["downloadStatus"].append(i.downloadStatus) # Peliculas elif i.contentType == "movie": i.title = "[COLOR %s][%i%%][/COLOR] %s" % (status_color[i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) else: if i.contentType == "episode": serie_name = "%s [%s]" % (i.contentSerieName, i.contentChannel) if serie_name == item.serie_name: i.title = "[COLOR %s][%i%%][/COLOR] %s" % (status_color[i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) for i in itemlist: if i.title in series: if any(series[i.title]["downloadStatus"]) == 3: downloadStatus = 3 elif all(series[i.title]["downloadStatus"]) == 2: downloadStatus = 2 else: downloadStatus = 1 downloadProgress = sum(series[i.title]["downloadProgress"]) / len(series[i.title]["downloadProgress"]) i.title = "[COLOR %s][%i%%][/COLOR] %s [%s]" % (status_color[downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel) i.downloadStatus = downloadStatus estados = [i.downloadStatus for i in itemlist] # Si hay alguno completado if 2 in estados: itemlist.insert(0, Item(channel=item.channel, action="clean_ready", title="Eliminar descargas completadas", url=config.get_setting("downloadlistpath"), serie_name = item.serie_name)) # Si hay alguno con error if 3 in estados: itemlist.insert(0, Item(channel=item.channel, action="restart_error", title="Reiniciar descargas con error", url=config.get_setting("downloadlistpath"), serie_name = item.serie_name)) # Si hay alguno pendiente if 1 in estados or 0 in estados: itemlist.insert(0, Item(channel=item.channel, action="download_all", title="Descargar todo", url=config.get_setting("downloadlistpath"), serie_name = item.serie_name)) if len(itemlist): itemlist.insert(0, Item(channel=item.channel, action="clean_all", title="Eliminar todo", url=config.get_setting("downloadlistpath"), serie_name = item.serie_name)) return itemlist
def run(): logger.info("pelisalacarta.platformcode.launcher run") # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info("pelisalacarta.platformcode.launcher "+item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("pelisalacarta.platformcode.launcher Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() # Check for updates only on first screen if config.get_setting("updatecheck2") == "true": logger.info("pelisalacarta.platformcode.launcher Check for plugin updates enabled") from core import updater try: version = updater.checkforupdates() if version: platformtools.dialog_ok("Versión "+version+" disponible", "Ya puedes descargar la nueva versión del plugin\n" "desde el listado principal") itemlist.insert(0, Item(title="Descargar version "+version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumbnail_path() + "Crystal_Clear_action_info.png")) except: platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar", "si hay actualizaciones") logger.info("cpelisalacarta.platformcode.launcher Fallo al verificar la actualización") else: logger.info("pelisalacarta.platformcode.launcher Check for plugin updates disabled") platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "update": from core import updater updater.update(item) if config.get_system_platform() != "xbox": import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_pin") != "": tecleado = platformtools.dialog_input("", "PIN para canales de adultos", True) if tecleado is not None: if tecleado == config.get_setting("adult_pin"): can_open_channel = True # All the other cases can open the channel else: can_open_channel = True if not can_open_channel: return # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel+".py") logger.info("pelisalacarta.platformcode.launcher channel_file=%s" % channel_file) channel = None if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels."+item.channel+" as channel" logger.info("pelisalacarta.platformcode.launcher running channel "+channel.__name__+" "+channel.__file__) # Special play action if item.action == "play": logger.info("pelisalacarta.platformcode.launcher play") # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("pelisalacarta.platformcode.launcher executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0: item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("plugin", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("pelisalacarta.platformcode.launcher executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info("pelisalacarta.platformcode.launcher no channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import descargas item.action = item.extra del item.extra descargas.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("pelisalacarta.platformcode.launcher search") tecleado = platformtools.dialog_input("") if tecleado is not None: tecleado = tecleado.replace(" ", "+") # TODO revisar 'personal.py' porque no tiene función search y daría problemas itemlist = channel.search(item, tecleado) else: itemlist = [] platformtools.render_items(itemlist, item) # For all other actions else: logger.info("pelisalacarta.platformcode.launcher executing channel '"+item.action+"' method") itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error("pelisalacarta.platformcode.launcher "+traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("pelisalacarta.platformcode.launcher Razon del error, codigo: "+str(e.reason[0])+", Razon: " + str(e.reason[1])) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("plugin", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info("pelisalacarta.platformcode.launcher codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
def run(item=None): logger.info() if not item: # Extract item from sys.argv if sys.argv[2]: sp = sys.argv[2].split('&') url = sp[0] item = Item().fromurl(url) if len(sp) > 1: for e in sp[1:]: key, val = e.split('=') item.__setattr__(key, val) # If no item, this is mainlist else: if config.get_setting("start_page"): if not config.get_setting("custom_start"): category = config.get_setting("category").lower() item = Item(channel="news", action="novedades", extra=category, mode = 'silent') else: from channels import side_menu item= Item() item = side_menu.check_user_home(item) item.start = True; else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): from platformcode import configurator configurator.show_window() logger.info(item.tostring()) try: if not config.get_setting('tmdb_active'): config.set_setting('tmdb_active', True) # Cleans infoLabels["playcount"] if set by generictools if item.video_path: item.infoLabels["playcount"] = 1 del item.infoLabels["playcount"] # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() elif item.action == "script": from core import tmdb if tmdb.drop_bd(): platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) elif item.action == "function": """ { "action": "function", "folder": "lib", "function": "alfa_assistant", "method": "install_alfa_assistant", "options": "auto" } """ # Checks if function file exists function_file = os.path.join(config.get_runtime_path(), item.folder, item.function + ".py") logger.info("function_file=%s" % function_file) function = None if os.path.exists(function_file): try: function = __import__('%s.%s' % (item.folder, item.function), None, None, ["%s.%s" % (item.folder, item.function)]) except ImportError: exec("import %s." + item.function + " as function") logger.info("Running function %s(%s) | %s" % (function.__name__, item.options, function.__file__)) getattr(function, item.method)(item.options) else: logger.error("ERROR Running function %s(%s) | %s" % (function.__name__, item.options, function.__file__)) # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_request_password"): tecleado = platformtools.dialog_input("", config.get_localized_string(60334), True) if tecleado is None or tecleado != config.get_setting("adult_password"): return # # Actualiza el canal individual # if (item.action == "mainlist" and item.channel != "channelselector" and # config.get_setting("check_for_channel_updates") == True): # from core import updater # updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info("channel_file=%s" % channel_file) channel = None if os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec("import channels." + item.channel + " as channel") logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Calls redirection if Alfavorites findvideos, episodios, seasons if item.context and 'alfavorites' in str(item.context) \ and item.action in ['findvideos', 'episodios', 'seasons', 'play']: try: from lib import generictools item, it, overwrite = generictools.redirect_clone_newpct1(item) except: import traceback logger.error(traceback.format_exc()) # Special play action if item.action == "play": #define la info para trakt try: trakt_tools.set_trakt_info(item) except: pass logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(60339)) # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) itemlist = servertools.filter_servers(itemlist) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) # last_search = "" # last_search_active = config.get_setting("last_search", "search") # if last_search_active: # try: # current_saved_searches_list = list(config.get_setting("saved_searches_list", "search")) # last_search = current_saved_searches_list[0] # except: # pass last_search = channeltools.get_channel_setting('Last_searched', 'search', '') tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if "http" not in tecleado: channeltools.set_channel_setting('Last_searched', tecleado, 'search') itemlist = channel.search(item, tecleado) else: return platformtools.render_items(itemlist, item) # For all other actions else: logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) if config.get_setting('trakt_sync'): token_auth = config.get_setting("token_trakt", "trakt") if not token_auth: trakt_tools.auth_trakt() else: import xbmc if not xbmc.getCondVisibility('System.HasAddon(script.trakt)') and config.get_setting( 'install_trakt'): trakt_tools.ask_install_script() itemlist = trakt_tools.trakt_check(itemlist) else: config.set_setting('install_trakt', True) platformtools.render_items(itemlist, item) except urllib2.URLError as e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.error("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("alfa", texto) # Grab server response errors elif hasattr(e, 'code'): logger.error("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("alfa", config.get_localized_string(30051) % e.code) except WebErrorException as e: import traceback logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + '([^.]+)\.py"' canal = scrapertools.find_single_match(traceback.format_exc(), patron) platformtools.dialog_ok( config.get_localized_string(59985) + canal, config.get_localized_string(60013) %(e)) except: import traceback logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + '([^.]+)\.py"' canal = scrapertools.find_single_match(traceback.format_exc(), patron) try: if config.get_platform(True)['num_version'] < 14: log_name = "xbmc.log" else: log_name = "kodi.log" log_message = config.get_localized_string(50004) + config.translatePath("special://logpath") + log_name except: log_message = "" if canal: platformtools.dialog_ok( config.get_localized_string(60087) %canal, config.get_localized_string(60014), log_message) else: platformtools.dialog_ok( config.get_localized_string(60038), config.get_localized_string(60015), log_message)
def list_all(item): logger.info() itemlist = [] data = get_source(item.url) patron = '<article class="Cards.*?href="([^"]+)"(.*?)<img.*?' patron += 'data-echo="([^"]+)" alt="([^"]+)"' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedurl, scrapedinfo, scrapedthumbnail, scrapedtitle in matches: title = scrapedtitle scrapedtitle = re.sub(r' \((.*?)\)$', '', scrapedtitle) thumbnail = scrapedthumbnail.strip() url = scrapedurl tmdb_id = scrapertools.find_single_match(url, r'/\w(\d+)-') thumbnail = re.sub(r'p/w\d+', 'p/original', thumbnail) if item.type == 'search': s_title = scrapertools.find_single_match(url, host + '(\w+)') if not unify: title += ' [COLOR grey][I](%s)[/I][/COLOR]' % s_title.capitalize( )[:-1] new_item = Item(channel=item.channel, title=title, url=url, thumbnail=thumbnail, infoLabels={'tmdb_id': tmdb_id}) if item.type == 'peliculas' or 'peliculas' in url: new_item.action = 'findvideos' new_item.contentTitle = scrapedtitle new_item.type = 1 calidad_baja = scrapertools.find_single_match( scrapedinfo, r'>(\w+\s\w+)</div>$') if calidad_baja: new_item.title += '[COLOR tomato] (Calidad Baja)[/COLOR]' else: new_item.action = 'seasons' new_item.contentSerieName = scrapedtitle new_item.type = 0 sesxep = scrapertools.find_single_match(url, r'/(\d+x\d+)$') if sesxep: new_item.title += ' ' + sesxep new_item.action = 'findvideos' itemlist.append(new_item) tmdb.set_infoLabels(itemlist, seekTmdb=True) if item.type == 'search': itemlist.sort(key=lambda i: (i.type, i.title)) # Paginación url_next_page = scrapertools.find_single_match( data, '<a href="([^"]+)" up-target="body">Pagina s') if url_next_page: itemlist.append( item.clone(title="Siguiente >>", url=url_next_page, action='list_all', text_color='gold')) return itemlist
def list_all(item): logger.info itemlist = list() data = httptools.downloadpage(item.url).data soup = BeautifulSoup(data, "html5lib", from_encoding="utf-8") for elem in soup.find_all("li", class_="TPostMv"): url = elem.a["href"] thumb = elem.img["src"] title = elem.h2.text cleantitle = title year = '' tvshow = elem.find("span", class_="TpTv BgA") if not tvshow: year = elem.find("span", class_="Date AAIco-date_range").text extra_info = elem.find("span", class_="calidad").text.split("|") try: language = extra_info[1].strip().encode('utf-8') except: language = '' if not config.get_setting("unify"): title += ' [%s]' % IDIOMAS.get(language.lower(), language) new_item = Item(channel=item.channel, title='%s' % title, url=url, thumbnail=thumb, infoLabels={'year': year}) if tvshow: new_item.action = 'seasons' new_item.contentSerieName = cleantitle if item.mode != 'search': new_item.mode = 'tvshows' else: new_item.action = 'findvideos' new_item.contentTitle = cleantitle if item.mode != 'search': new_item.mode = 'movies' if item.mode == new_item.mode or item.mode == 'search': itemlist.append(new_item) tmdb.set_infoLabels_itemlist(itemlist, True) # Pagination try: next_page = soup.find("a", class_="next page-numbers")["href"] itemlist.append( Item(channel=item.channel, title='Siguiente >>', url=next_page, action='list_all')) except: pass return itemlist
if not filetools.exists(tvshow_path): # Creamos tvshow.nfo, si no existe, con la head_nfo, info de la serie y marcas de episodios vistos logger.info("Creando tvshow.nfo: " + tvshow_path) head_nfo = scraper.get_nfo(item) item_tvshow = Item(title=item.contentTitle, channel="biblioteca", action="get_temporadas", fanart=item.infoLabels['fanart'], thumbnail=item.infoLabels['thumbnail'], infoLabels=item.infoLabels, path=path.replace(TVSHOWS_PATH, "")) item_tvshow.library_playcounts = {} item_tvshow.library_urls = {item.channel: item.url} else: # Si existe tvshow.nfo, pero estamos añadiendo un nuevo canal actualizamos el listado de urls head_nfo, item_tvshow = read_nfo(tvshow_path) item_tvshow.channel = "biblioteca" item_tvshow.action = "get_temporadas" item_tvshow.library_urls[item.channel] = item.url # FILTERTOOLS # si el canal tiene filtro de idiomas, añadimos el canal y el show if episodelist and "list_idiomas" in episodelist[0]: # si ya hemos añadido un canal previamente con filtro, añadimos o actualizamos el canal y show if "library_filter_show" in item_tvshow: item_tvshow.library_filter_show[item.channel] = item.show # no habia ningún canal con filtro y lo generamos por primera vez else: item_tvshow.library_filter_show = {item.channel: item.show} if item.channel != "descargas": item_tvshow.active = 1 # para que se actualice a diario cuando se llame a library_service
def run(item=None): logger.debug() if not item: # Extract item from sys.argv if sys.argv[2]: sp = sys.argv[2].split('&') url = sp[0] item = Item().fromurl(url) if len(sp) > 1: for e in sp[1:]: key, val = e.split('=') item.__setattr__(key, val) # If no item, this is mainlist else: if config.get_setting("start_page"): if not config.get_setting("custom_start"): dictCategory = { config.get_localized_string(70137): 'peliculas', config.get_localized_string(30123): 'series', config.get_localized_string(30124): 'anime', config.get_localized_string(60513): 'documentales', config.get_localized_string(70171): 'torrent', } if not config.get_setting( "category") in dictCategory.keys(): config.set_setting('category', config.get_localized_string(70137)) category = dictCategory[config.get_setting("category")] item = Item(channel="news", action="novedades", extra=category, mode='silent') else: from platformcode import side_menu item = Item() item = side_menu.check_user_home(item) item.start = True else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): if not config.get_all_settings_addon(): logger.error('corrupted settings.xml!!') settings_xml = os.path.join(config.get_data_path(), "settings.xml") settings_bak = os.path.join(config.get_data_path(), "settings.bak") if filetools.exists(settings_bak): filetools.copy(settings_bak, settings_xml, True) logger.info('restored settings.xml from backup') else: filetools.write(settings_xml, '<settings version="2">\n</settings>' ) # resetted settings else: from platformcode import xbmc_videolibrary xbmc_videolibrary.ask_set_content(silent=False) config.set_setting('show_once', True) logger.info(item.tostring()) try: if not config.get_setting('tmdb_active'): config.set_setting('tmdb_active', True) # If item has no action, stops here if item.action == "": logger.debug("Item without action") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() elif item.channel == "infoplus": from platformcode import infoplus return infoplus.Main(item) elif config.get_setting( 'new_search' ) and item.channel == "search" and item.action == 'new_search': from platformcode.globalsearch import Search item.contextual = True Search(item) return elif item.channel == "backup": from platformcode import backup return getattr(backup, item.action)(item) elif item.channel == "elementum_download": from platformcode import elementum_download return getattr(elementum_download, item.action)(item) elif item.channel == "shortcuts": from platformcode import shortcuts return getattr(shortcuts, item.action)(item) elif item.channel == "autorenumber": from platformcode import autorenumber return getattr(autorenumber, item.action)(item) elif item.action == "delete_key": from platformcode import keymaptools return keymaptools.delete_key() elif item.action == "script": from core import tmdb if tmdb.drop_bd(): platformtools.dialog_notification( config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) elif item.action == "itemInfo": platformtools.dialog_textviewer('Item info', item.parent) elif item.action == "open_browser": import webbrowser if not webbrowser.open(item.url): import xbmc if xbmc.getCondVisibility( 'system.platform.linux') and xbmc.getCondVisibility( 'system.platform.android'): # android xbmc.executebuiltin( 'StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")' % (item.url)) else: try: import urllib.request as urllib except ImportError: import urllib short = urllib.urlopen( 'https://u.nu/api.php?action=shorturl&format=simple&url=' + item.url).read().decode('utf-8') platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(70740) % short) # Action in certain channel specified in "action" and "channel" parameters elif item.action == "check_channels": from platformcode import checkhost checkhost.check_channels() else: # Checks if channel exists if os.path.isfile( os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py")): CHANNELS = 'channels' else: CHANNELS = 'specials' channel_file = os.path.join(config.get_runtime_path(), CHANNELS, item.channel + ".py") logger.debug("channel_file= " + channel_file + ' - ' + CHANNELS + ' - ' + item.channel) channel = None if os.path.exists(channel_file): try: channel = __import__('%s.%s' % (CHANNELS, item.channel), None, None, ['%s.%s' % (CHANNELS, item.channel)]) except ImportError: exec("import " + CHANNELS + "." + item.channel + " as channel") logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": # define la info para trakt try: from core import trakt_tools trakt_tools.set_trakt_info(item) except: pass logger.debug("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.debug("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el Channel elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(60339)) # If player don't have a "play" function, not uses the standard play from platformtools else: logger.debug("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": from core import servertools # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.debug("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": from core import videolibrarytools videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": from core import videolibrarytools videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from specials import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": # from core.support import dbg;dbg() if filetools.isfile(temp_search_file) and config.get_setting( 'videolibrary_kodi'): itemlist = [] f = filetools.read(temp_search_file) strList = f.split(',') if strList[0] == '[V]' and strList[1] == item.channel: for it in strList: if it and it not in ['[V]', item.channel]: itemlist.append(Item().fromurl(it)) filetools.write(temp_search_file, f[4:]) return platformtools.render_items(itemlist, item) else: filetools.remove(temp_search_file) logger.debug("item.action=%s" % item.action.upper()) from core import channeltools if config.get_setting('last_search'): last_search = channeltools.get_channel_setting( 'Last_searched', 'search', '') else: last_search = '' search_text = platformtools.dialog_input(last_search) if search_text is not None: channeltools.set_channel_setting('Last_searched', search_text, 'search') itemlist = new_search(item.clone(text=search_text), channel) else: return platformtools.render_items(itemlist, item) # For all other actions else: # import web_pdb; web_pdb.set_trace() logger.debug("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) if config.get_setting('trakt_sync'): from core import trakt_tools token_auth = config.get_setting("token_trakt", "trakt") if not token_auth: trakt_tools.auth_trakt() else: import xbmc if not xbmc.getCondVisibility( 'System.HasAddon(script.trakt)' ) and config.get_setting('install_trakt'): trakt_tools.ask_install_script() itemlist = trakt_tools.trakt_check(itemlist) else: config.set_setting('install_trakt', True) platformtools.render_items(itemlist, item) except WebErrorException as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) platformtools.dialog_ok( config.get_localized_string(59985) % e.channel, config.get_localized_string(60013) % e.url) except Exception as e: import traceback from core import scrapertools logger.error(traceback.format_exc()) patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + r'([^.]+)\.py"' Channel = scrapertools.find_single_match(traceback.format_exc(), patron) if Channel or e.__class__ == logger.ChannelScraperException: if item.url: if platformtools.dialog_yesno( config.get_localized_string(60087) % Channel, config.get_localized_string(60014), nolabel='ok', yeslabel=config.get_localized_string(70739)): run(Item(action="open_browser", url=item.url)) else: platformtools.dialog_ok( config.get_localized_string(60087) % Channel, config.get_localized_string(60014)) else: if platformtools.dialog_yesno(config.get_localized_string(60038), config.get_localized_string(60015)): run(Item(channel="setting", action="report_menu"))
def list_all(item): logger.info() itemlist = [] next = False media_type = item.media_type if not item.results: json_data = load_json(item) else: json_data = item.results first = item.first last = first + 19 if last > len(json_data[media_type]): last = len(json_data[media_type]) else: next = True for media in json_data[media_type][first:last]: quality, language, plot, poster = set_extra_values(media) title = media['title'] title = set_title(title, language, quality) new_item = Item(channel=item.channel, title=title, quality=quality, language=language, plot=plot, thumbnail=poster) if 'movies_list' in json_data: new_item.url = media new_item.contentTitle = media['title'] new_item.action = 'findvideos' if 'year' in media: new_item.infoLabels['year'] = media['year'] else: new_item.url = media['seasons_list'] new_item.contentSerieName = media['title'] new_item.action = 'seasons' itemlist.append(new_item) tmdb.set_infoLabels(itemlist, seekTmdb=True) # Pagination if next: first = last itemlist.append( Item(channel=item.channel, title="Siguiente >>", url=item.url, action='list_all', media_type=item.media_type, results=item.results, first=first)) return itemlist
def lista(item): logger.info() next = True itemlist = [] data = httptools.downloadpage(item.url).data data = re.sub(r"\n|\r|\t|\s{2}| ", "", data) data = scrapertools.find_single_match( data, "itemprop='headline'>.*?</h2>.*?</ul>") patron = '<span class="([^"]+)">.*?<figure class="poster-bg"><header><span>(\d{4})</span></header><img src="([^"]+)" />' patron += '<footer>(.*?)</footer></figure><h6>([^<]+)</h6><a href="([^"]+)"></a>' matches = scrapertools.find_multiple_matches(data, patron) first = int(item.first) last = first + 19 if last > len(matches): last = len(matches) next = False for scrapedtype, scrapedyear, scrapedthumbnail, scrapedquality, scrapedtitle, scrapedurl in matches[ first:last]: patron_quality = "<span>(.+?)</span>" quality = scrapertools.find_multiple_matches(scrapedquality, patron_quality) qual = "" for calidad in quality: qual = qual + "[" + calidad + "] " title = "%s [%s] %s" % (scrapedtitle, scrapedyear, qual) new_item = Item(channel=item.channel, title=title, url=host + scrapedurl, thumbnail=scrapedthumbnail, type=scrapedtype, infoLabels={'year': scrapedyear}) if scrapedtype.strip() == 'sr': new_item.contentSerieName = scrapedtitle new_item.action = 'episodios' else: new_item.contentTitle = scrapedtitle new_item.action = 'findvideos' if scrapedtype == item.type or item.type == 'cat': itemlist.append(new_item) tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True) #pagination url_next_page = item.url first = last if next: itemlist.append( item.clone(title="Siguiente >>", url=url_next_page, action='lista', first=first)) return itemlist
def run(): logger.info() # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info(item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector # Check for updates only on first screen if config.get_setting("check_for_plugin_updates") == "true": logger.info("Check for plugin updates enabled") from core import updater try: config.set_setting("plugin_updates_available","0") version = updater.checkforupdates() itemlist = channelselector.getmainlist() if version: config.set_setting("plugin_updates_available","1") platformtools.dialog_ok("Versión "+version+" disponible", "Ya puedes descargar la nueva versión del plugin\n" "desde el listado principal") itemlist = channelselector.getmainlist() itemlist.insert(0, Item(title="Descargar version "+version, version=version, channel="updater", action="update", thumbnail=channelselector.get_thumb("squares","thumb_actualizar.png"))) except: import traceback logger.info(traceback.format_exc()) platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar", "si hay actualizaciones") logger.info("Fallo al verificar la actualización") config.set_setting("plugin_updates_available","0") itemlist = channelselector.getmainlist() else: logger.info("Check for plugin updates disabled") config.set_setting("plugin_updates_available","0") itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "update": from core import updater updater.update(item) config.set_setting("plugin_updates_available","0") if config.get_system_platform() != "xbox": import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_pin") != "": tecleado = platformtools.dialog_input("", "PIN para canales de adultos", True) if tecleado is not None: if tecleado == config.get_setting("adult_pin"): can_open_channel = True # All the other cases can open the channel else: can_open_channel = True if not can_open_channel: return # Actualiza el canal individual if (item.action == "mainlist" and item.channel != "channelselector" and config.get_setting("check_for_channel_updates") == "true"): from core import updater updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info("channel_file=%s" % channel_file) channel = None if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels." + item.channel + " as channel" logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("pelisalacarta", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist) if config.get_setting("max_links", "biblioteca") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import descargas item.action = item.extra del item.extra descargas.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) last_search = "" last_search_active = config.get_setting("last_search", "buscador") if last_search_active: try: current_saved_searches_list = list(config.get_setting("saved_searches_list", "buscador")) last_search = current_saved_searches_list[0] except: pass tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if last_search_active: from channels import buscador buscador.save_search(tecleado) # TODO revisar 'personal.py' porque no tiene función search y daría problemas itemlist = channel.search(item, tecleado) else: itemlist = [] platformtools.render_items(itemlist, item) # For all other actions else: logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("pelisalacarta", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("pelisalacarta", config.get_localized_string(30051) % e.code)
def busqueda(item): logger.info() itemlist = list() # Descarga la página data = httptools.downloadpage(item.url).data data = re.sub(r"\n|\r|\t| |\s{2}", "", data) # Extrae las entradas (carpetas) bloque = scrapertools.find_single_match(data, '<h2>Peliculas</h2>(.*?)</div>') bloque += scrapertools.find_single_match(data, '<h2>Series</h2>(.*?)</div>') patron = '<figure class="col-lg-2.*?href="([^"]+)".*?src="([^"]+)".*?<figcaption title="([^"]+)"' matches = scrapertools.find_multiple_matches(bloque, patron) peliculas = False series = False for scrapedurl, scrapedthumbnail, scrapedtitle in matches: new_item = Item(channel=item.channel, contentType="movie", url=scrapedurl, title=" " + scrapedtitle, text_color=color1, context="buscar_trailer", fulltitle=scrapedtitle, contentTitle=scrapedtitle, thumbnail=scrapedthumbnail, action="findvideos") if "/peliculas/" in scrapedurl and not peliculas: itemlist.append( Item(channel=item.channel, action="", title="Películas", text_color=color2)) peliculas = True if "/series/" in scrapedurl and not series: itemlist.append( Item(channel=item.channel, action="", title="Series", text_color=color2)) series = True if "/series/" in scrapedurl: new_item.contentType = "tvshow" new_item.show = scrapedtitle new_item.action = "episodios" filtro_thumb = scrapedthumbnail.replace( "http://image.tmdb.org/t/p/w342", "") filtro_list = {"poster_path": filtro_thumb} new_item.infoLabels["filtro"] = filtro_list.items() itemlist.append(new_item) try: tmdb.set_infoLabels_itemlist(itemlist, __modo_grafico__) except: pass return itemlist
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 = xml2dict(data) 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 fichas(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data # data = re.sub(r"\n|\r|\t|\s{2}|-\s", "", data) fichas_marca = { '1': 'Siguiendo', '2': 'Pendiente', '3': 'Favorita', '4': 'Vista', '5': 'Abandonada' } patron = '<div class="c_fichas_image"[^>]*>[^<]*<[^>]+href="\.([^"]+)".*?src-data="([^"]+)".*?' \ '<div class="c_fichas_data".*?marked="([^"]*)".*?serie="([^"]*)".*?' \ '<div class="c_fichas_title">(?:<div class="c_fichas_episode">([^<]+)</div>|)([^<]+)</div>' matches = scrapertools.find_multiple_matches(data, patron) for scrapedurl, scrapedthumbnail, marca, serie, episodio, scrapedtitle in matches: tipo = "movie" scrapedurl = host + scrapedurl.rsplit("-dc=")[0] if not "-dc=" in scrapedurl: scrapedurl += "-dc=" 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 if marca: title += " [COLOR %s][%s][/COLOR]" % (color4, fichas_marca[marca]) 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) if itemlist and (item.extra == "listas_plus" or item.extra == "sigo"): follow = scrapertools.find_single_match( data, '<div onclick="seguir_lista.*?>(.*?)<') title = "Seguir Lista" if follow == "Siguiendo": title = "Dejar de seguir lista" item.extra = "" url = host + "/data.php?mode=seguir_lista&apikey=%s&sid=%s&lista=%s" % ( apikey, sid, item.url.rsplit("/l", 1)[1]) itemlist.insert( 0, item.clone(action="acciones_cuenta", title=title, url=url, text_color=color4, lista=item.title, folder=False)) next_page = scrapertools.find_single_match(data, 'href="([^"]+)" class="next"') if next_page: next_page = host + next_page.replace("&", "&") itemlist.append( Item(channel=item.channel, action="fichas", title=">> Página Siguiente", url=next_page)) try: total = int( scrapertools.find_single_match( data, '<span class="page-dots">.*href.*?>(\d+)')) except: total = 0 if not config.get_setting("last_page", item.channel) and config.is_xbmc() and total > 2 \ and item.extra != "newest": itemlist.append( item.clone(action="select_page", title="Ir a página... (Total:%s)" % total, url=next_page, text_color=color5)) return itemlist
def list_all(item): logger.info() itemlist = [] data = get_source(item.url) full_data = data if item.section != '': data = scrapertools.find_single_match( data, 'class="MovieList NoLmtxt(.*?)</ul>') else: data = scrapertools.find_single_match( data, '<!--<%s>.*?class="MovieList NoLmtxt(.*?)</ul>' % item.type) if item.section == 'alpha': patron = '<span class="Num">\d+.*?<a href="([^"]+)" class.*?<img src="([^"]+)" alt=.*?' patron += '<strong>([^"]+)</strong>.*?<td>(\d{4})</td>' matches = re.compile(patron, re.DOTALL).findall(full_data) else: patron = '<article.*?<a href="(.*?)">.*?<img src="(.*?)" alt=.*?' patron += '<h3 class="Title">(.*?)<\/h3>.*?date_range">(\d+)<' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedurl, scrapedthumbnail, scrapedtitle, year in matches: url = scrapedurl if year == '': year = '-' if "|" in scrapedtitle: scrapedtitle = scrapedtitle.split("|") cleantitle = scrapedtitle[0].strip() else: cleantitle = scrapedtitle cleantitle = re.sub('\(.*?\)', '', cleantitle) if not config.get_setting('unify'): title = '%s [%s]' % (cleantitle, year) else: title = cleantitle thumbnail = 'http:' + scrapedthumbnail new_item = Item(channel=item.channel, title=title, url=url, thumbnail=thumbnail, infoLabels={'year': year}) if 'series' not in url: new_item.contentTitle = cleantitle new_item.action = 'findvideos' else: new_item.contentSerieName = cleantitle new_item.action = 'seasons' itemlist.append(new_item) tmdb.set_infoLabels_itemlist(itemlist, True) # Paginación url_next_page = scrapertools.find_single_match( full_data, '<a class="next.*?href="([^"]+)">') if url_next_page: itemlist.append( Item(channel=item.channel, title="Siguiente >>", url=url_next_page, action='list_all', type=item.type)) return itemlist
def save_tvshow(item, episodelist): """ guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist @type item: item @param item: item que representa la serie a guardar @type episodelist: list @param episodelist: listado de items que representan los episodios que se van a guardar. @rtype insertados: int @return: el número de episodios insertados @rtype sobreescritos: int @return: el número de episodios sobreescritos @rtype fallidos: int @return: el número de episodios fallidos o -1 si ha fallado toda la serie @rtype path: str @return: directorio serie """ logger.info() # logger.debug(item.tostring('\n')) path = "" # Si llegados a este punto no tenemos titulo o code, salimos if not (item.contentSerieName or item.infoLabels['code']) or not item.channel: logger.error("NO ENCONTRADO contentSerieName NI code: " + item.url) return 0, 0, -1, path # Salimos sin guardar scraper_return = scraper.find_and_set_infoLabels(item) # Llegados a este punto podemos tener: # scraper_return = True: Un item con infoLabels con la información actualizada de la serie # scraper_return = False: Un item sin información de la peli (se ha dado a cancelar en la ventana) # item.infoLabels['code'] == "" : No se ha encontrado el identificador de IMDB necesario para continuar, salimos if not scraper_return or not item.infoLabels['code']: # TODO de momento si no hay resultado no añadimos nada, # aunq podriamos abrir un cuadro para introducir el identificador/nombre a mano logger.error("NO ENCONTRADO EN SCRAPER O NO TIENE code: " + item.url) return 0, 0, -1, path _id = item.infoLabels['code'][0] if not item.infoLabels['code'][0] or item.infoLabels['code'][0] == 'None': if item.infoLabels['code'][1] and item.infoLabels['code'][1] != 'None': _id = item.infoLabels['code'][1] elif item.infoLabels['code'][2] and item.infoLabels['code'][2] != 'None': _id = item.infoLabels['code'][2] else: logger.error("NO ENCONTRADO EN SCRAPER O NO TIENE code: " + item.url + ' / ' + item.infoLabels['code']) return 0, 0, -1, path if config.get_setting("original_title_folder", "videolibrary") == 1 and item.infoLabels['originaltitle']: base_name = item.infoLabels['originaltitle'] elif item.infoLabels['tvshowtitle']: base_name = item.infoLabels['tvshowtitle'] elif item.infoLabels['title']: base_name = item.infoLabels['title'] else: base_name = item.contentSerieName if not PY3: base_name = unicode(filetools.validate_path(base_name.replace('/', '-')), "utf8").encode("utf8") else: base_name = filetools.validate_path(base_name.replace('/', '-')) if config.get_setting("lowerize_title", "videolibrary") == 0: base_name = base_name.lower() for raiz, subcarpetas, ficheros in filetools.walk(TVSHOWS_PATH): for c in subcarpetas: code = scrapertools.find_single_match(c, '\[(.*?)\]') if code and code != 'None' and code in item.infoLabels['code']: path = filetools.join(raiz, c) _id = code break if not path: path = filetools.join(TVSHOWS_PATH, ("%s [%s]" % (base_name, _id)).strip()) logger.info("Creando directorio serie: " + path) try: filetools.mkdir(path) except OSError as exception: if exception.errno != errno.EEXIST: raise tvshow_path = filetools.join(path, "tvshow.nfo") if not filetools.exists(tvshow_path): # Creamos tvshow.nfo, si no existe, con la head_nfo, info de la serie y marcas de episodios vistos logger.info("Creando tvshow.nfo: " + tvshow_path) head_nfo = scraper.get_nfo(item) item.infoLabels['mediatype'] = "tvshow" item.infoLabels['title'] = item.contentSerieName item_tvshow = Item(title=item.contentSerieName, channel="videolibrary", action="get_seasons", fanart=item.infoLabels['fanart'], thumbnail=item.infoLabels['thumbnail'], infoLabels=item.infoLabels, path=path.replace(TVSHOWS_PATH, "")) item_tvshow.library_playcounts = {} item_tvshow.library_urls = {item.channel: item.url} else: # Si existe tvshow.nfo, pero estamos añadiendo un nuevo canal actualizamos el listado de urls head_nfo, item_tvshow = read_nfo(tvshow_path) item_tvshow.channel = "videolibrary" item_tvshow.action = "get_seasons" item_tvshow.library_urls[item.channel] = item.url # FILTERTOOLS # si el canal tiene filtro de idiomas, añadimos el canal y el show if episodelist and "list_language" in episodelist[0]: # si ya hemos añadido un canal previamente con filtro, añadimos o actualizamos el canal y show if "library_filter_show" in item_tvshow: if item.title_from_channel: item_tvshow.library_filter_show[item.channel] = item.title_from_channel else: item_tvshow.library_filter_show[item.channel] = item.show # no habia ningún canal con filtro y lo generamos por primera vez else: if item.title_from_channel: item_tvshow.library_filter_show = {item.channel: item.title_from_channel} else: item_tvshow.library_filter_show = {item.channel: item.show} if item.channel != "downloads": item_tvshow.active = 1 # para que se actualice a diario cuando se llame a videolibrary_service filetools.write(tvshow_path, head_nfo + item_tvshow.tojson()) if not episodelist: # La lista de episodios esta vacia return 0, 0, 0, path # Guardar los episodios '''import time start_time = time.time()''' insertados, sobreescritos, fallidos = save_episodes(path, episodelist, item) '''msg = "Insertados: %d | Sobreescritos: %d | Fallidos: %d | Tiempo: %2.2f segundos" % \ (insertados, sobreescritos, fallidos, time.time() - start_time) logger.debug(msg)''' return insertados, sobreescritos, fallidos, path
def peliculas(item): logger.info("pelisalacarta.channels.biblioteca peliculas") strm_path = library.MOVIES_PATH download_path = filetools.join(config.get_library_path(), "Descargas", "Cine") itemlist = [] for raiz, subcarpetas, ficheros in filetools.walk(strm_path): for f in ficheros: if f.endswith(".strm"): i = filetools.join(raiz, f) movie = Item().fromurl(filetools.read(i)) movie.contentChannel = movie.channel movie.path = i movie.title = os.path.splitext(os.path.basename(i))[0].capitalize() movie.channel = "biblioteca" movie.action = "findvideos" movie.text_color = "blue" # fix para que no se ejecute el método de play para la biblioteca de Kodi movie.strm = False itemlist.append(movie) # Obtenemos todos los videos de la biblioteca de CINE recursivamente for raiz, subcarpetas, ficheros in filetools.walk(download_path): for f in ficheros: if not f.endswith(".json") and not f.endswith(".nfo") and not f.endswith(".srt"): i = filetools.join(raiz, f) movie = Item() movie.contentChannel = "local" movie.path = i movie.title = os.path.splitext(os.path.basename(i))[0].capitalize() movie.channel = "biblioteca" movie.action = "play" movie.text_color = "green" itemlist.append(movie) library.set_infolabels_from_library(itemlist, tipo="Movies") # Agrupamos las peliculas por canales join_itemlist = [] for i in range(len(itemlist)): encontrado = False for j in range(i + 1, len(itemlist)): if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[j].infoLabels: if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels["tmdb_id"]: encontrado = True if "list_channels" not in itemlist[i]: list_channels = [] dict_first_channel = {"path": itemlist[i].path, "channel": itemlist[i].contentChannel} list_channels.append(dict_first_channel.copy()) itemlist[j].list_channels = list_channels dict_other_channel = {"path": itemlist[j].path, "channel": itemlist[j].contentChannel} itemlist[j].list_channels.append(dict_other_channel.copy()) itemlist[j].action = "get_canales_movies" itemlist[j].text_color = "orange" # TODO pendiente de probar if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "": itemlist[i].title = itemlist[i].contentTitle if not encontrado: join_itemlist.append(itemlist[i]) return sorted(join_itemlist, key=lambda it: it.title.lower())
def list_news(item): logger.info() itemlist = [] listed = [] next = False data = get_source(item.url, referer=referer) patron = '<td><a href=([^ ]+) target="_parent"><img src=([^ ]+) class="s8" alt="([^"]+)"' matches = re.compile(patron, re.DOTALL).findall(data) first = item.first last = first + 19 if last > len(matches): last = len(matches) next = True for url, thumb, title in matches[first:last]: infoLabels = dict() id = scrapertools.find_single_match(url, 'titles/([^/]+)') if item.news_type == 'movies': filter_thumb = thumb.replace( "https://image.tmdb.org/t/p/w185_and_h278_bestv2", "") filter_list = {"poster_path": filter_thumb.strip()} filter_list = list(filter_list.items()) infoLabels['filtro'] = filter_list url = '%ssecure/titles/%s?titleId=%s' % (host, id, id) else: se_ep = scrapertools.get_season_and_episode(title) contentSerieName = title.replace(se_ep.replace('x0', 'x'), '').strip() if not config.get_setting('unify'): title = '%s - %s' % (se_ep, contentSerieName) se_ep = se_ep.split('x') url = '%ssecure/titles/%s?titleId=%s&seasonNumber=%s' % ( host, id, id, se_ep[0]) thumb = re.sub("p/(.*?)/", "p/original/", thumb) if url not in listed: new_item = Item(channel=item.channel, action="findvideos", title=title, url=url, thumbnail=thumb, infoLabels=infoLabels) if item.news_type == 'movies': new_item.contentTitle = title new_item.action = 'findvideos' else: ep = int(se_ep[1]) new_item.contentSerieName = contentSerieName new_item.url += '&episodeNumber=%s' % ep new_item.ep_info = ep new_item.infoLabels['season'] = se_ep[0] new_item.infoLabels['episode'] = ep listed.append(url) itemlist.append(new_item) tmdb.set_infoLabels(itemlist, True) if not next: url_next_page = item.url first = last if url_next_page: itemlist.append( item.clone(title="Siguiente >>", url=url_next_page, action='list_news', first=first)) return itemlist
def list_all(item): logger.info() itemlist = [] logger.error(item.url) if item.ar_post and not item.not_post: data = get_source(item.url, post=item.ar_post) else: data = get_source(item.url) patron = '<div class="col-6.*?href="([^"]+)".*?>(.*?)<img.*?'#url, info patron += 'src="([^"]+)".*?<p.*?>([^<]+)</p>'#thumb,title matches = re.compile(patron, re.DOTALL).findall(data) for scrapedurl, info, scrapedthumbnail, scrapedtitle in matches: _type = scrapertools.find_single_match(info,'>([^<]+)</').lower() year = '-' year = scrapertools.find_single_match(scrapedtitle,'\(\d{4}\)') url = scrapedurl if not url.startswith('http'): url = urlparse.urljoin(host, url) thumbnail = scrapedthumbnail thumb = scrapertools.find_single_match(thumbnail,'portadas/(.*)') lang = 'VOSE' title = scrapedtitle scrapedtitle = re.sub('\(.*?\)$', '', scrapedtitle).strip() if _type: title += '[COLOR darkgrey] (%s)[/COLOR]' % _type.capitalize() context = renumbertools.context(item) context2 = autoplay.context context.extend(context2) new_item= Item(channel=item.channel, title=title, thumbnail=thumbnail, language=lang, thumb=thumb, infoLabels={'year':year} ) if 'pel' in _type: new_item.contentTitle=scrapedtitle new_item.action = 'findvideos' new_item.url = url.replace(host, '%s1/' % host) else: new_item.plot=_type.capitalize() new_item.contentSerieName=scrapedtitle new_item.context = context new_item.action = 'episodios' new_item.url = url itemlist.append(new_item) # Paginacion next_page = scrapertools.find_single_match(data, ' data-id="(\d+)" aria-label="Next">') if next_page != "": ar_post = re.sub('pinput=(\d+)&', 'pinput=%s&' % next_page, item.ar_post) itemlist.append(Item(channel=item.channel, action="list_all", title=">> Página siguiente", url=item.url, ar_post= ar_post, thumbnail='https://s16.postimg.cc/9okdu7hhx/siguiente.png' )) tmdb.set_infoLabels(itemlist, seekTmdb=True) return itemlist
def peliculas(item): logger.info("streamondemand.channels.biblioteca peliculas") strm_path = library.MOVIES_PATH download_path = filetools.join(config.get_library_path(), "Descargas", "Cine") itemlist = [] for raiz, subcarpetas, ficheros in filetools.walk(strm_path): for f in ficheros: if f.endswith(".strm"): i = filetools.join(raiz, f) movie = Item().fromurl(filetools.read(i)) movie.contentChannel = movie.channel movie.path = i movie.title = os.path.splitext( os.path.basename(i))[0].capitalize() movie.channel = "biblioteca" movie.action = "findvideos" movie.text_color = "blue" # fix para que no se ejecute el método de play para la biblioteca de Kodi movie.strm = False itemlist.append(movie) # Obtenemos todos los videos de la biblioteca de CINE recursivamente for raiz, subcarpetas, ficheros in filetools.walk(download_path): for f in ficheros: if not f.endswith(".json") and not f.endswith( ".nfo") and not f.endswith(".srt"): i = filetools.join(raiz, f) movie = Item() movie.contentChannel = "local" movie.path = i movie.title = os.path.splitext( os.path.basename(i))[0].capitalize() movie.channel = "biblioteca" movie.action = "play" movie.text_color = "green" itemlist.append(movie) library.set_infolabels_from_library(itemlist, tipo='Movies') # Agrupamos las peliculas por canales join_itemlist = [] for i in range(len(itemlist)): encontrado = False for j in range(i + 1, len(itemlist)): if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[ j].infoLabels: if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels[ "tmdb_id"]: encontrado = True if "list_channels" not in itemlist[i]: list_channels = [] dict_first_channel = { "path": itemlist[i].path, "channel": itemlist[i].contentChannel } list_channels.append(dict_first_channel.copy()) itemlist[j].list_channels = list_channels dict_other_channel = { "path": itemlist[j].path, "channel": itemlist[j].contentChannel } itemlist[j].list_channels.append(dict_other_channel.copy()) itemlist[j].action = "get_canales_movies" itemlist[j].text_color = "orange" # TODO pendiente de probar if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "": itemlist[i].title = itemlist[i].contentTitle if not encontrado: join_itemlist.append(itemlist[i]) return sorted(join_itemlist, key=lambda it: it.title.lower())
def listado(item): logger.info(item) itemlist = [] data = downloadpage(item.url) patron = '<a class="extended" href=".([^"]+).*?' patron += '<img class="centeredPicFalse"([^>]+).*?' patron += '<span class="year">(\d{4})</span>.*?' patron += '<span class="title">(.*?)</span>' for url, pic, year, title in scrapertools.find_multiple_matches( data, patron): thumbnail = scrapertools.find_single_match(pic, 'src="([^"]+)') if not thumbnail: thumbnail = HOST + "/images/cover-notfound.png" new_item = Item(channel=__channel__, thumbnail=thumbnail, text_color=color2, infoLabels={"year": year}) if "galep.php" in item.url: # movie new_item.contentTitle = title new_item.action = "findvideos" new_item.url = HOST + url.replace('peli.php?id=', 'venlaces.php?npl=') elif "gales.php" in item.url: # tvshow title = title.replace(' - 0x0', '') new_item.contentSerieName = title new_item.action = "temporadas" new_item.url = HOST + url if "ord=reci" in item.url: # episode season_episode = scrapertools.get_season_and_episode(title) if season_episode: new_item.contentSeason, new_item.contentEpisodeNumber = season_episode.split( 'x') new_item.action = "get_episodio" new_item.contentSerieName = title.split('-', 1)[1].strip() elif "gener=" in item.url and scrapertools.get_season_and_episode( title): # Las series filtrada por genero devuelven capitulos y series completas title = title.split('-', 1)[1].strip() new_item.contentSerieName = title else: return [] new_item.title = "%s (%s)" % (title, year) itemlist.append(new_item) if itemlist: # Obtenemos los datos basicos mediante multihilos tmdb.set_infoLabels(itemlist) # Si es necesario añadir paginacion if len(itemlist) == 35: empen = scrapertools.find_single_match(item.url, 'empen=(\d+)') url_next_page = item.url.replace('empen=%s' % empen, 'empen=%s' % (int(empen) + 35)) itemlist.append( Item(channel=item.channel, action="listado", title=">> Página siguiente", thumbnail=thumbnail_host, url=url_next_page, folder=True, text_color=color3, text_bold=True)) return itemlist
def run(): logger.info() # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info(item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Action for main menu in channelselector if item.action == "getmainlist": import channelselector # Check for updates only on first screen if config.get_setting("check_for_plugin_updates") == "true": logger.info("Check for plugin updates enabled") from core import updater try: config.set_setting("plugin_updates_available","0") version = updater.checkforupdates() itemlist = channelselector.getmainlist() if version: config.set_setting("plugin_updates_available","1") platformtools.dialog_ok("Versione "+version+" disponible", "E' possibile fare il download della nuova versione\n" "selezionare la relativa voce nel menu principale") itemlist = channelselector.getmainlist() itemlist.insert(0, Item(title="Download versione "+version, version=version, channel="updater", action="update", thumbnail=os.path.join(config.get_runtime_path() , "resources" , "images", "service_update.png"))) except: import traceback logger.info(traceback.format_exc()) platformtools.dialog_ok("Impossibile connettersi", "Non è stato possibile verificare", "aggiornamenti") logger.info("Fallo al verificar la actualización") config.set_setting("plugin_updates_available","0") itemlist = channelselector.getmainlist() else: logger.info("Check for plugin updates disabled") config.set_setting("plugin_updates_available","0") itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for updating plugin elif item.action == "update": from core import updater updater.update(item) config.set_setting("plugin_updates_available","0") if config.get_system_platform() != "xbox": import xbmc xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control can_open_channel = False # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting("adult_pin") != "": tecleado = platformtools.dialog_input("", "PIN per canali per adulti", True) if tecleado is not None: if tecleado == config.get_setting("adult_pin"): can_open_channel = True # All the other cases can open the channel else: can_open_channel = True if not can_open_channel: return # Actualiza el canal individual if (item.action == "mainlist" and item.channel != "channelselector" and config.get_setting("check_for_channel_updates") == "true"): from core import updater updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info("channel_file=%s" % channel_file) channel = None if item.channel in ["personal", "personal2", "personal3", "personal4", "personal5"]: import channels.personal as channel elif os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels." + item.channel + " as channel" logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("plugin", "Niente da riprodurre") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") from core import servertools itemlist = servertools.find_video_items(item) if config.get_setting('filter_servers') == 'true': itemlist = filtered_servers(itemlist) if config.get_setting("max_links", "biblioteca") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": library.add_pelicula_to_library(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": library.add_serie_to_library(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import descargas item.action = item.extra del item.extra descargas.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) tecleado = platformtools.dialog_input('') if tecleado is not None: # TODO revisar 'personal.py' porque no tiene función search y daría problemas # DrZ3r0 itemlist = channel.search(item, tecleado.replace(" ", "+")) else: return platformtools.render_items(itemlist, item) # For all other actions else: logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.info("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("plugin", texto) # Grab server response errors elif hasattr(e, 'code'): logger.info("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok("plugin", config.get_localized_string(30051) % e.code)
def series(item): logger.info("pelisalacarta.channels.biblioteca series") strm_path = library.TVSHOWS_PATH download_path = filetools.join(config.get_library_path(), "Descargas", "Series") itemlist = [] # Obtenemos todos los strm de la biblioteca de SERIES recursivamente for raiz, subcarpetas, ficheros in filetools.walk(strm_path): for f in ficheros: if f == "tvshow.json": i = filetools.join(raiz, f) tvshow = Item().fromjson(filetools.read(i)) logger.debug(tvshow.tostring()) tvshow.contentChannel = tvshow.channel tvshow.path = os.path.dirname(i) tvshow.title = os.path.basename(os.path.dirname(i)) tvshow.channel = "biblioteca" tvshow.action = "get_temporadas" tvshow.text_color = "blue" itemlist.append(tvshow) # Obtenemos todos los videos de la biblioteca de SERIES recursivamente for raiz, subcarpetas, ficheros in filetools.walk(download_path): for f in ficheros: if f == "tvshow.json": i = filetools.join(raiz, f) tvshow = Item().fromjson(filetools.read(i)) tvshow.contentChannel = "local" tvshow.path = os.path.dirname(i) tvshow.title = os.path.basename(os.path.dirname(i)) tvshow.channel = "biblioteca" tvshow.action = "get_temporadas" tvshow.text_color = "green" itemlist.append(tvshow) library.set_infolabels_from_library(itemlist, tipo="TVShows") # Agrupamos las series por canales join_itemlist = [] for i in range(len(itemlist)): encontrado = False for j in range(i + 1, len(itemlist)): if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[j].infoLabels: if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels["tmdb_id"]: encontrado = True if "list_channels" not in itemlist[i]: list_channels = [] dict_first_channel = {"path": itemlist[i].path, "channel": itemlist[i].contentChannel} list_channels.append(dict_first_channel.copy()) itemlist[j].list_channels = list_channels dict_other_channel = {"path": itemlist[j].path, "channel": itemlist[j].contentChannel} itemlist[j].list_channels.append(dict_other_channel.copy()) itemlist[j].action = "get_canales_tvshow" itemlist[j].text_color = "orange" if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "": itemlist[i].title = itemlist[i].contentTitle if not encontrado: join_itemlist.append(itemlist[i]) return sorted(join_itemlist, key=lambda it: it.title.lower())
def lista(item): logger.info() next = True itemlist = [] data = httptools.downloadpage(item.url).data data = re.sub(r"\n|\r|\t|\s{2}| ", "", data) css_data = scrapertools.find_single_match( data, "<style id='page-skin-1' type='text/css'>(.*?)</style>") data = scrapertools.find_single_match( data, "itemprop='headline'>.*?</h2>.*?</ul>") patron = '<span class="([^"]+)">.*?<figure class="poster-bg">(.*?)<img src="([^"]+)" />' patron += '(.*?)</figure><h6>([^<]+)</h6><a href="([^"]+)"></a>' matches = scrapertools.find_multiple_matches(data, patron) first = int(item.first) last = first + 19 if last > len(matches): last = len(matches) next = False for scrapedtype, scrapedyear, scrapedthumbnail, scrapedquality, scrapedtitle, scrapedurl in matches[ first:last]: year = scrapertools.find_single_match(scrapedyear, '<span>(\d{4})</span>') if not year: class_year = scrapertools.find_single_match( scrapedyear, 'class="([^\"]+)"') year = scrapertools.find_single_match( css_data, "\." + class_year + ":after {content:'(\d{4})';}") if not year: year = scrapertools.find_single_match( data, "headline'>(\d{4})</h2>") qual = "" if scrapedquality: patron_qualities = '<i class="([^"]+)"></i>' qualities = scrapertools.find_multiple_matches( scrapedquality, patron_qualities) for quality in qualities: patron_desc = "\." + quality + ":after {content:'([^\']+)';}" quality_desc = scrapertools.find_single_match( css_data, patron_desc) qual = qual + "[" + quality_desc + "] " title = "%s [%s] %s" % (scrapedtitle, year, qual) new_item = Item(channel=item.channel, title=title, url=host + scrapedurl, thumbnail=scrapedthumbnail, type=scrapedtype, infoLabels={'year': year}) if scrapedtype.strip() == 'sr': new_item.contentSerieName = scrapedtitle new_item.action = 'episodios' else: new_item.contentTitle = scrapedtitle new_item.action = 'findvideos' if scrapedtype == item.type or item.type == 'cat': itemlist.append(new_item) tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True) #pagination url_next_page = item.url first = last if next: itemlist.append( item.clone(title="Siguiente >>", url=url_next_page, action='lista', first=first)) return itemlist
def list_all(item): logger.info() itemlist = list() next = True if not item.url.startswith(host): item.url = host + item.url if item.post: soup = BeautifulSoup(get_source(item.url, post=item.post), "html5lib", from_encoding="utf-8") else: soup = create_soup(item.url, referer=host) matches = soup.find_all("div", class_="span-6 inner-6 tt view") first = item.first last = first + 20 if last > len(matches): last = len(matches) next = False for elem in matches[first:last]: lang = list() url = elem.a["href"] title = elem.find("a", class_="link")["title"] title = re.sub(r"\..*", "", title) thumb = elem.img["src"] new_item = Item(channel=item.channel, title=title, url=host + url, thumbnail=thumb, infoLabels={}) if '/show/' in url: new_item.contentSerieName = title new_item.action = 'seasons' else: lang_data = elem.find("div", class_="left").find_all("img") for l in lang_data: if l["src"]: lang.append( IDIOMAS.get( lang_from_flag(l["src"], "/static/style/images/", "png"), '')) new_item.language = lang new_item.contentTitle = title new_item.infoLabels["year"] = "-" new_item.action = 'findvideos' itemlist.append(new_item) tmdb.set_infoLabels_itemlist(itemlist, True) if next: url_next_page = item.url first = last else: try: url_next_page = host + soup.find("ul", id="filter").find( "a", class_="current").next_sibling["href"] except: url_next_page = False pass first = 0 if url_next_page and len(matches) > 20: itemlist.append( Item(channel=item.channel, title="Siguiente >>", url=url_next_page, action='list_all', first=first)) return itemlist
def series(item): logger.info("streamondemand.channels.biblioteca series") strm_path = library.TVSHOWS_PATH download_path = filetools.join(config.get_library_path(), "Descargas", "Series") itemlist = [] # Obtenemos todos los strm de la biblioteca de SERIES recursivamente for raiz, subcarpetas, ficheros in filetools.walk(strm_path): for f in ficheros: if f == "tvshow.json": i = filetools.join(raiz, f) tvshow = Item().fromjson(filetools.read(i)) logger.debug(tvshow.tostring()) tvshow.contentChannel = tvshow.channel tvshow.path = os.path.dirname(i) tvshow.title = os.path.basename(os.path.dirname(i)) tvshow.channel = "biblioteca" tvshow.action = "get_temporadas" tvshow.text_color = "blue" itemlist.append(tvshow) # Obtenemos todos los videos de la biblioteca de SERIES recursivamente for raiz, subcarpetas, ficheros in filetools.walk(download_path): for f in ficheros: if f == "tvshow.json": i = filetools.join(raiz, f) tvshow = Item().fromjson(filetools.read(i)) tvshow.contentChannel = "local" tvshow.path = os.path.dirname(i) tvshow.title = os.path.basename(os.path.dirname(i)) tvshow.channel = "biblioteca" tvshow.action = "get_temporadas" tvshow.text_color = "green" itemlist.append(tvshow) library.set_infolabels_from_library(itemlist, tipo='TVShows') # Agrupamos las series por canales join_itemlist = [] for i in range(len(itemlist)): encontrado = False for j in range(i + 1, len(itemlist)): if "tmdb_id" in itemlist[i].infoLabels and "tmdb_id" in itemlist[ j].infoLabels: if itemlist[i].infoLabels["tmdb_id"] == itemlist[j].infoLabels[ "tmdb_id"]: encontrado = True if "list_channels" not in itemlist[i]: list_channels = [] dict_first_channel = { "path": itemlist[i].path, "channel": itemlist[i].contentChannel } list_channels.append(dict_first_channel.copy()) itemlist[j].list_channels = list_channels dict_other_channel = { "path": itemlist[j].path, "channel": itemlist[j].contentChannel } itemlist[j].list_channels.append(dict_other_channel.copy()) itemlist[j].action = "get_canales_tvshow" itemlist[j].text_color = "orange" if "contentTitle" in itemlist[i] and itemlist[i].contentTitle != "": itemlist[i].title = itemlist[i].contentTitle if not encontrado: join_itemlist.append(itemlist[i]) return sorted(join_itemlist, key=lambda it: it.title.lower())
def run(item=None): logger.info() if not item: # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: if config.get_setting("start_page"): if not config.get_setting("custom_start"): dictCategory = { config.get_localized_string(70137): 'peliculas', config.get_localized_string(30123): 'series', config.get_localized_string(30124): 'anime', config.get_localized_string(70018): 'infantiles', config.get_localized_string(60513): 'documentales', config.get_localized_string(70013): 'terror', config.get_localized_string(30124): 'castellano', config.get_localized_string(59976): 'latino', config.get_localized_string(70171): 'torrent', } category = dictCategory[config.get_setting("category")] item = Item(channel="news", action="novedades", extra=category, mode='silent') else: from specials import side_menu item = Item() item = side_menu.check_user_home(item) item.start = True else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") if not config.get_setting('show_once'): from platformcode import xbmc_videolibrary xbmc_videolibrary.ask_set_content( 1, config.get_setting('videolibrary_kodi_force')) config.set_setting('show_once', True) logger.info(item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return if item.action == "update": updater.update() # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() elif item.action == "delete_key": from platformcode import keymaptools return keymaptools.delete_key() elif item.action == "script": from core import tmdb if tmdb.drop_bd(): platformtools.dialog_notification( config.get_localized_string(20000), config.get_localized_string(60011), time=2000, sound=False) # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": #updater.checkforupdates() beta version checking for update, still disabled # Parental control # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting( "adult_request_password"): tecleado = platformtools.dialog_input( "", config.get_localized_string(60334), True) if tecleado is None or tecleado != config.get_setting( "adult_password"): return # # Actualiza el canal individual # if (item.action == "mainlist" and item.channel != "channelselector" and # config.get_setting("check_for_channel_updates") == True): # from core import updater # updater.update_channel(item.channel) # Checks if channel exists if os.path.isfile( os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py")): CHANNELS = 'channels' else: CHANNELS = 'specials' channel_file = os.path.join(config.get_runtime_path(), CHANNELS, item.channel + ".py") logger.info("channel_file= " + channel_file) channel = None if os.path.exists(channel_file): try: channel = __import__(CHANNELS + item.channel, None, None, [CHANNELS + item.channel]) except ImportError: importer = "import " + CHANNELS + "." + item.channel + " as channel" exec(importer) logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": #define la info para trakt try: trakt_tools.set_trakt_info(item) except: pass logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok( config.get_localized_string(20000), config.get_localized_string(60339)) # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) itemlist = servertools.filter_servers(itemlist) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from specials import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) last_search = "" last_search_active = config.get_setting( "last_search", "search") if last_search_active: try: current_saved_searches_list = list( config.get_setting("saved_searches_list", "search")) last_search = current_saved_searches_list[0] except: pass tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if last_search_active and not tecleado.startswith("http"): from specials import search search.save_search(tecleado) itemlist = channel.search(item, tecleado) else: return platformtools.render_items(itemlist, item) # For all other actions else: # import web_pdb; web_pdb.set_trace() logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) if config.get_setting('trakt_sync'): token_auth = config.get_setting("token_trakt", "trakt") if not token_auth: trakt_tools.auth_trakt() else: import xbmc if not xbmc.getCondVisibility( 'System.HasAddon(script.trakt)' ) and config.get_setting('install_trakt'): trakt_tools.ask_install_script() itemlist = trakt_tools.trakt_check(itemlist) else: config.set_setting('install_trakt', True) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.error("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string( 30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("alfa", texto) # Grab server response errors elif hasattr(e, 'code'): logger.error("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok( "alfa", config.get_localized_string(30051) % e.code)
def run(item=None): logger.info() if not item: # Extract item from sys.argv if sys.argv[2]: item = Item().fromurl(sys.argv[2]) # If no item, this is mainlist else: item = Item(channel="channelselector", action="getmainlist", viewmode="movie") logger.info(item.tostring()) try: # If item has no action, stops here if item.action == "": logger.info("Item sin accion") return # Action for main menu in channelselector elif item.action == "getmainlist": import channelselector # # Check for updates only on first screen # if config.get_setting("check_for_plugin_updates") == True: # logger.info("Check for plugin updates enabled") # from core import updater # # try: # config.set_setting("plugin_updates_available", 0) # new_published_version_tag, number_of_updates = updater.get_available_updates() # # config.set_setting("plugin_updates_available", number_of_updates) # itemlist = channelselector.getmainlist() # # if new_published_version_tag != "": # platformtools.dialog_notification(new_published_version_tag + " disponible", # "Ya puedes descargar la nueva versión del plugin\n" # "desde el listado principal") # # itemlist = channelselector.getmainlist() # itemlist.insert(0, Item(title="Descargar version " + new_published_version_tag, # version=new_published_version_tag, channel="updater", # action="update", # thumbnail=channelselector.get_thumb("update.png"))) # except: # import traceback # logger.error(traceback.format_exc()) # platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar", # "si hay actualizaciones") # logger.error("Fallo al verificar la actualización") # config.set_setting("plugin_updates_available", 0) # itemlist = channelselector.getmainlist() # # else: # logger.info("Check for plugin updates disabled") # config.set_setting("plugin_updates_available", 0) # itemlist = channelselector.getmainlist() itemlist = channelselector.getmainlist() platformtools.render_items(itemlist, item) # # Action for updating plugin # elif item.action == "update": # # from core import updater # updater.update(item) # config.set_setting("plugin_updates_available", 0) # # import xbmc # xbmc.executebuiltin("Container.Refresh") # Action for channel types on channelselector: movies, series, etc. elif item.action == "getchanneltypes": import channelselector itemlist = channelselector.getchanneltypes() platformtools.render_items(itemlist, item) # Action for channel listing on channelselector elif item.action == "filterchannels": import channelselector itemlist = channelselector.filterchannels(item.channel_type) platformtools.render_items(itemlist, item) # Special action for playing a video from the library elif item.action == "play_from_library": play_from_library(item) return elif item.action == "keymap": from platformcode import keymaptools if item.open: return keymaptools.open_shortcut_menu() else: return keymaptools.set_key() # Action in certain channel specified in "action" and "channel" parameters else: # Entry point for a channel is the "mainlist" action, so here we check parental control if item.action == "mainlist": # Parental control # If it is an adult channel, and user has configured pin, asks for it if channeltools.is_adult(item.channel) and config.get_setting( "adult_request_password"): tecleado = platformtools.dialog_input( "", "Contraseña para canales de adultos", True) if tecleado is None or tecleado != config.get_setting( "adult_password"): return # # Actualiza el canal individual # if (item.action == "mainlist" and item.channel != "channelselector" and # config.get_setting("check_for_channel_updates") == True): # from core import updater # updater.update_channel(item.channel) # Checks if channel exists channel_file = os.path.join(config.get_runtime_path(), 'channels', item.channel + ".py") logger.info("channel_file=%s" % channel_file) channel = None if os.path.exists(channel_file): try: channel = __import__('channels.%s' % item.channel, None, None, ["channels.%s" % item.channel]) except ImportError: exec "import channels." + item.channel + " as channel" logger.info("Running channel %s | %s" % (channel.__name__, channel.__file__)) # Special play action if item.action == "play": logger.info("item.action=%s" % item.action.upper()) # logger.debug("item_toPlay: " + "\n" + item.tostring('\n')) # First checks if channel has a "play" function if hasattr(channel, 'play'): logger.info("Executing channel 'play' method") itemlist = channel.play(item) b_favourite = item.isFavourite # Play should return a list of playable URLS if len(itemlist) > 0 and isinstance(itemlist[0], Item): item = itemlist[0] if b_favourite: item.isFavourite = True platformtools.play_video(item) # Permitir varias calidades desde play en el canal elif len(itemlist) > 0 and isinstance(itemlist[0], list): item.video_urls = itemlist platformtools.play_video(item) # If not, shows user an error message else: platformtools.dialog_ok("alfa", "No hay nada para reproducir") # If player don't have a "play" function, not uses the standard play from platformtools else: logger.info("Executing core 'play' method") platformtools.play_video(item) # Special action for findvideos, where the plugin looks for known urls elif item.action == "findvideos": # First checks if channel has a "findvideos" function if hasattr(channel, 'findvideos'): itemlist = getattr(channel, item.action)(item) itemlist = servertools.filter_servers(itemlist) # If not, uses the generic findvideos function else: logger.info("No channel 'findvideos' method, " "executing core method") itemlist = servertools.find_video_items(item) if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) from platformcode import subtitletools subtitletools.saveSubtitleName(item) platformtools.render_items(itemlist, item) # Special action for adding a movie to the library elif item.action == "add_pelicula_to_library": videolibrarytools.add_movie(item) # Special action for adding a serie to the library elif item.action == "add_serie_to_library": videolibrarytools.add_tvshow(item, channel) # Special action for downloading all episodes from a serie elif item.action == "download_all_episodes": from channels import downloads item.action = item.extra del item.extra downloads.save_download(item) # Special action for searching, first asks for the words then call the "search" function elif item.action == "search": logger.info("item.action=%s" % item.action.upper()) last_search = "" last_search_active = config.get_setting( "last_search", "search") if last_search_active: try: current_saved_searches_list = list( config.get_setting("saved_searches_list", "search")) last_search = current_saved_searches_list[0] except: pass tecleado = platformtools.dialog_input(last_search) if tecleado is not None: if last_search_active and not tecleado.startswith("http"): from channels import search search.save_search(tecleado) itemlist = channel.search(item, tecleado) else: return platformtools.render_items(itemlist, item) # For all other actions else: logger.info("Executing channel '%s' method" % item.action) itemlist = getattr(channel, item.action)(item) platformtools.render_items(itemlist, item) except urllib2.URLError, e: import traceback logger.error(traceback.format_exc()) # Grab inner and third party errors if hasattr(e, 'reason'): logger.error("Razon del error, codigo: %s | Razon: %s" % (str(e.reason[0]), str(e.reason[1]))) texto = config.get_localized_string( 30050) # "No se puede conectar con el sitio web" platformtools.dialog_ok("alfa", texto) # Grab server response errors elif hasattr(e, 'code'): logger.error("Codigo de error HTTP : %d" % e.code) # "El sitio web no funciona correctamente (error http %d)" platformtools.dialog_ok( "alfa", config.get_localized_string(30051) % e.code)
def list_all(item): logger.info() itemlist = [] soup = get_source(item.url, soup=True) if not soup: return [] if not soup: platformtools.dialog_notification( "Cambio de estructura", "Reporta el error desde el menú principal", sound=False) return itemlist items = soup.find('div', id='archive-content').find_all('article') for article in items: data = article.find('div', class_='data') infoLabels = { 'year': data.find('p').text, 'genres': data.find('span').text } thumbnail = article.find('img')['src'] title = data.find('h3').text if 'tmdb.org' in thumbnail: infoLabels['filtro'] = scrapertools.find_single_match( thumbnail, "/(\w+)\.\w+$") it = Item(action='findvideos', channel=item.channel, fanart=item.fanart, infoLabels=infoLabels, thumbnail=thumbnail, title=title, url=article.find('a')['href']) if item.list_type and item.list_type in ['movies', 'tvshows']: list_type = item.list_type elif item.viewType and item.list_type in ['movies', 'tvshows']: list_type = item.list_type else: if 'serie' in it.url: list_type = 'tvshows' elif 'pelicula' in it.url: list_type = 'movies' if list_type == 'tvshows': it.action = 'seasons' it.contentSerieName = title it.contentType = 'tvshow' it.viewType = 'episodes' elif list_type == 'movies': it.contentTitle = title it.contentType = 'movie' it.viewType = 'movies' itemlist.append(it) if not isinstance(item.tmdb, bool) or item.tmdb != False: tmdb.set_infoLabels(itemlist, True) return itemlist
def list_all(item): logger.info() itemlist = list() next = False soup = create_soup(item.url) matches = soup.find("div", class_="content").find_all("article", id=re.compile(r"^post-\d+")) first = item.first last = first + 15 if last >= len(matches): last = len(matches) next = True for elem in matches[first:last]: info_1 = elem.find("div", class_="poster") info_2 = elem.find("div", class_="data") thumb = info_1.img["src"] title = info_1.img["alt"] url = info_1.a["href"] try: year = info_2.find( "span", text=re.compile(r"\d{4}")).text.split(",")[-1].strip() except: year = "-" new_item = Item(channel=item.channel, title=title, url=url, thumbnail=thumb, infoLabels={"year": year}) if "tvshows" in url: new_item.contentSerieName = title new_item.action = "seasons" else: new_item.contentTitle = title new_item.action = "findvideos" itemlist.append(new_item) tmdb.set_infoLabels_itemlist(itemlist, True) if not next: url_next_page = item.url first = last else: try: url_next_page = soup.find_all("a", class_="arrow_pag")[-1]["href"] except: return itemlist url_next_page = '%s' % url_next_page first = 0 if url_next_page and len(matches) > 16: itemlist.append( Item(channel=item.channel, title="Siguiente >>", url=url_next_page, action='list_all', first=first)) return itemlist
def findvideos(item): logger.info() itemlist = [] url_list = item.urls_q try: test = httptools.downloadpage(url_list[0], only_headers=True).url except: try: domain = urlparse.urlparse(url_list[0])[1] url_t = 'https://' + domain get_source(url_t) test = httptools.downloadpage(url_list[0], only_headers=True).url except: test = 'error' if 'error.' in test: url_list = item.url for url in url_list: if not url: continue server = 'torrent' action = 'play' title = server.capitalize() quality = scrapertools.find_single_match(url, '(\d+)p%') new_item = Item(channel=item.channel, title=title, url=url, action=action, language=item.language, plot=item.plot, server=server, thumbnail=item.thumbnail) if not url.endswith('.torrent') and not url.startswith('mag'): if not url.endswith('.mkv'): new_item.server = '' new_item.action = 'folder_list' new_item.title = 'Directo [Folder]' new_item.nom_serie = item.contentSerieName #return folder_list(item) else: new_item.server = 'directo' new_item.title = new_item.server.capitalize() new_item.infoLabels = item.infoLabels else: new_item.infoLabels = item.infoLabels if quality: quality += 'p' new_item.quality = quality new_item.title += ' [%s]' % quality itemlist.append(new_item) itemlist.sort(key=lambda x: x.server) return itemlist