def episodesxseason(item, get_episodes=False, get_movie=False): logger.info() itemlist = [] soup = create_soup(item.url) if soup.find(id=re.compile('menu\d+')): # Initial variables to set content type airing = False batch = False finale = False moviespecial = False menu = soup.find(id=re.compile('menu\d+')) type = soup.find(class_='alphabet-title').text # Detect what kind of content we're dealing with if 'airing' in type.lower(): pass airing = True elif 'batch' in type.lower(): pass batch = True elif 'movie' in type.lower(): pass moviespecial = True elif 'finale' in type.lower(): pass finale = True else: type = '' episodes = menu.find_all('table') details = soup.find(id=re.compile('post-\d+')) image = details.find( class_='entry-content-poster').find('img')['data-src'] contentTitle = details.find(class_='entry-title').text for episode in episodes: infoLabels = item.infoLabels urls = {} ep = episode.find('a', class_='aa_ss_ops_new') if ep: airing = True if airing: infoLabels['episode'] = int( scrapertools.find_single_match(ep.text, '.+? - (\d+)')) title = "1x{}. {}".format(infoLabels['episode'], (config.get_localized_string(60036) % infoLabels['episode'])) elif batch: infoLabels['episode'] = (scrapertools.find_multiple_matches( ep.text, '.+? - (\d+).+?(\d+)')) infoLabels['episode'] = (scrapertools.find_multiple_matches( ep.text, '.+? - (\d+).+?(\d+)')) title = "1x{}. {}".format(infoLabels['episode'], (config.get_localized_string(60036) % infoLabels['episode'])) elif finale: pass elif moviespecial: pass else: title = scrapertools.find_single_match( episode.find(class_='aa_ss_ops_new').text, '') for link in episode.find_all(class_='release-links'): qa = link.find('span').text.split('|')[0].strip() for linktype in link.find_all(class_='link_uppercase'): name = '{} [{}]'.format(linktype.text.title(), qa) urls[name] = linktype['href'] title = "{}{}".format(type, title) new_item = item.clone( action='findvideos', contentTitle=contentTitle, fanart=image, infoLabels=infoLabels, plot=details.find(class_='entry-content-story').text, thumbnail=image, title=title, urls=urls) itemlist.append(new_item) itemlist.reverse() return itemlist else: return [ Item(folder=False, title='Cambio de estructura. Reportar en el foro') ]
def sub_menu(item): logger.info() item.channel = "search" itemlist = list() context = [{ "title": config.get_localized_string(70273), "action": "setting_channel", "channel": item.channel }] itemlist.append( Item(channel=item.channel, action="search", title=config.get_localized_string(30980), context=context, thumbnail=get_thumb("search.png"))) thumbnail = get_thumb("search_star.png") itemlist.append( Item(channel='tvmoviedb', title=config.get_localized_string(70036), action="search_", search={ 'url': 'search/person', 'language': 'es', 'page': 1 }, star=True, thumbnail=thumbnail)) itemlist.append( Item(channel=item.channel, action="search", title=config.get_localized_string(59998), extra="categorias", context=context, thumbnail=get_thumb("search.png"))) itemlist.append( Item(channel=item.channel, action="opciones", title=config.get_localized_string(59997), thumbnail=get_thumb("search.png"))) itemlist.append( Item(channel="tvmoviedb", action="mainlist", title=config.get_localized_string(70274), thumbnail=get_thumb("search.png"))) saved_searches_list = get_saved_searches() context2 = context[:] context2.append({ "title": config.get_localized_string(59996), "action": "clear_saved_searches", "channel": item.channel }) logger.info("saved_searches_list=%s" % saved_searches_list) if saved_searches_list: itemlist.append( Item(channel=item.channel, action="", title=config.get_localized_string(59995), context=context2, thumbnail=get_thumb("search.png"))) for saved_search_text in saved_searches_list: itemlist.append( Item(channel=item.channel, action="do_search", title=' "' + saved_search_text + '"', extra=saved_search_text, context=context2, category=saved_search_text, thumbnail=get_thumb("search.png"))) return itemlist
def settings(item): return platformtools.show_channel_settings( caption=config.get_localized_string(59993))
def downloadfileGzipped(url, pathfichero): logger.info("url=" + url) nombrefichero = pathfichero logger.info("nombrefichero=" + nombrefichero) import xbmc nombrefichero = xbmc.makeLegalFilename(nombrefichero) logger.info("nombrefichero=" + nombrefichero) patron = "(http://[^/]+)/.+" matches = re.compile(patron, re.DOTALL).findall(url) if len(matches): logger.info("URL principal :" + matches[0]) url1 = matches[0] else: url1 = url txheaders = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; ' 'Media Center PC 5.0; .NET CLR 3.0.04506)', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'es-es,es;q=0.8,en-us;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip,deflate', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Keep-Alive': '115', 'Connection': 'keep-alive', 'Referer': url1, } txdata = "" # Crea el diálogo de progreso from platformcode import platformtools progreso = platformtools.dialog_progress( "addon", config.get_localized_string(60200), url.split("|")[0], nombrefichero) # Timeout del socket a 60 segundos socket.setdefaulttimeout(10) h = urllib2.HTTPHandler(debuglevel=0) request = urllib2.Request(url, txdata, txheaders) # if existSize > 0: # request.add_header('Range', 'bytes=%d-' % (existSize, )) opener = urllib2.build_opener(h) urllib2.install_opener(opener) try: connexion = opener.open(request) except urllib2.HTTPError, e: logger.error("error %d (%s) al abrir la url %s" % (e.code, e.msg, url)) progreso.close() # El error 416 es que el rango pedido es mayor que el fichero => es que ya está completo if e.code == 416: return 0 else: return -2
def faq(item): if item.extra == "onoff_canales": respuesta = platformtools.dialog_yesno( config.get_localized_string(60457), config.get_localized_string(60458)) if respuesta == 1: from specials import setting setting.conf_tools(Item(extra='channels_onoff')) elif item.extra == "trakt_sync": respuesta = platformtools.dialog_yesno( config.get_localized_string(60457), config.get_localized_string(60459)) if respuesta == 1: from specials import videolibrary videolibrary.channel_config(Item(channel='videolibrary')) elif item.extra == "tiempo_enlaces": respuesta = platformtools.dialog_yesno( config.get_localized_string(60457), config.get_localized_string(60460)) if respuesta == 1: from specials import videolibrary videolibrary.channel_config(Item(channel='videolibrary')) elif item.extra == "prob_busquedacont": title = config.get_localized_string(60461) % item.title[6:] text = config.get_localized_string(60462) return TextBox("DialogTextViewer.xml", os.getcwd(), "Default", title=title, text=text) elif item.extra == "canal_fallo": title = config.get_localized_string(60461) % item.title[6:] text = config.get_localized_string(60463) return TextBox("DialogTextViewer.xml", os.getcwd(), "Default", title=title, text=text) elif item.extra == "prob_bib": platformtools.dialog_ok( config.get_localized_string(60457), # To check config.get_localized_string(60464)) respuesta = platformtools.dialog_yesno( config.get_localized_string(60457), config.get_localized_string(60465)) if respuesta == 1: itemlist = [] from specials import setting new_item = Item(channel="setting", action="submenu_tools", folder=True) itemlist.extend(setting.submenu_tools(new_item)) return itemlist elif item.extra == "prob_torrent": title = config.get_localized_string(60461) % item.title[6:] text = config.get_localized_string(70279) return TextBox("DialogTextViewer.xml", os.getcwd(), "Default", title=title, text=text) elif item.extra == "buscador_juntos": respuesta = platformtools.dialog_yesno( config.get_localized_string(60457), config.get_localized_string(60466)) if respuesta == 1: from specials import search search.settings("") elif item.extra == "report_error": import xbmc if config.get_platform(True)['num_version'] < 14: log_name = "xbmc.log" else: log_name = "kodi.log" ruta = xbmc.translatePath("special://logpath") + log_name title = config.get_localized_string(60461) % item.title[6:] text = config.get_localized_string(60467) % ruta return TextBox("DialogTextViewer.xml", os.getcwd(), "Default", title=title, text=text) else: platformtools.dialog_ok( config.get_localized_string(60457), # To check "Tag telegram" config.get_localized_string(60468))
def mainlist(item): logger.info() itemlist = [] # Lista de archivos for file in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): # Saltamos todos los que no sean JSON if not file.endswith(".json"): continue # cargamos el item file = os.path.join(DOWNLOAD_LIST_PATH, file) i = Item(path=file).fromjson(filetools.read(file)) i.thumbnail = i.contentThumbnail # Listado principal if not item.contentType == "tvshow": # Series if i.contentType == "episode": # Comprobamos que la serie no este ya en el itemlist if not filter( lambda x: x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel, itemlist): title = TITLE_TVSHOW % ( STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel) itemlist.append(Item(title=title, channel="descargas", action="mainlist", contentType="tvshow", contentSerieName=i.contentSerieName, contentChannel=i.contentChannel, downloadStatus=i.downloadStatus, downloadProgress=[i.downloadProgress], fanart=i.fanart, thumbnail=i.thumbnail)) else: s = \ filter( lambda x: x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel, itemlist)[0] s.downloadProgress.append(i.downloadProgress) downloadProgress = sum(s.downloadProgress) / len(s.downloadProgress) if not s.downloadStatus in [STATUS_CODES.error, STATUS_CODES.canceled] and not i.downloadStatus in [ STATUS_CODES.completed, STATUS_CODES.stoped]: s.downloadStatus = i.downloadStatus s.title = TITLE_TVSHOW % ( STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel) # Peliculas elif i.contentType == "movie" or i.contentType == "video": i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentTitle) itemlist.append(i) # Listado dentro de una serie else: if i.contentType == "episode" and i.contentSerieName == item.contentSerieName and i.contentChannel == item.contentChannel: i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle)) itemlist.append(i) 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=config.get_localized_string(70218), contentType=item.contentType, contentChannel=item.contentChannel, contentSerieName=item.contentSerieName, text_color="sandybrown")) # Si hay alguno con error if 3 in estados: itemlist.insert(0, Item(channel=item.channel, action="restart_error", title=config.get_localized_string(70219), contentType=item.contentType, contentChannel=item.contentChannel, contentSerieName=item.contentSerieName, text_color="orange")) # Si hay alguno pendiente if 1 in estados or 0 in estados: itemlist.insert(0, Item(channel=item.channel, action="download_all", title=config.get_localized_string(70220), contentType=item.contentType, contentChannel=item.contentChannel, contentSerieName=item.contentSerieName, text_color="green")) if len(itemlist): itemlist.insert(0, Item(channel=item.channel, action="clean_all", title=config.get_localized_string(70221), contentType=item.contentType, contentChannel=item.contentChannel, contentSerieName=item.contentSerieName, text_color="red")) if not item.contentType == "tvshow" and config.get_setting("browser", "downloads") == True: itemlist.insert(0, Item(channel=item.channel, action="browser", title=config.get_localized_string(70222), url=DOWNLOAD_PATH, text_color="yellow")) if not item.contentType == "tvshow": itemlist.insert(0, Item(channel=item.channel, action="settings", title=config.get_localized_string(70223), text_color="blue")) return itemlist
def seasons(item): logger.info() itemlist = [] seasons = [] # Obtenemos el HTML y cargamos el JSON soup = create_soup(item.url) json = jsontools.load(soup.find('script', id='__NEXT_DATA__').text) # Buscamos el "content_id", requerido para búsqueda en la API de la página content_id = json['props']['pageProps'].get('id') if not content_id: id_ = item.url.replace(host, '').split('/')[2].split('-', 1) content_id = '{}-{}'.format(id_[0], id_[1].replace('-', '%20')) # Obtenemos el JSON con los episodios desde la API para clasificar temporadas (vienen en lotes) episodios = httptools.downloadpage( 'https://fapi.comamosramen.com/api/byUniqId/{}'.format( content_id)).json # Recorremos la lista de episodios y obtenemos las temporadas según haya diferencias entre c/ep for episodio in episodios['temporadas']: if len(seasons) > 0 and seasons[-1]['temporada'] == int( episodio['temporada']): seasons[-1]['episodios'].append(episodio) else: seasons.append({ 'temporada': int(episodio['temporada']), 'episodios': [] }) seasons[-1]['episodios'].append(episodio) # Recorremos la lista de temporadas para procesamiento for season in seasons: title, language = set_lang(episodios.get('titulo')) infoLabels = {'year': episodios.get('año')} ogtitle = title # Determinación del idioma if item.language: language = item.language if episodios.get('categorias'): if 'Audio Latino' in episodios.get('categorias'): language = 'LAT' # Determinación dinámica del contentType if episodios.get('tipo'): if episodios.get('tipo') in ['pelicula']: contentType = 'movie' else: contentType = 'tvshow' else: contentType = '' it = Item(action='episodesxseason', channel=item.channel, contentType=contentType, infoLabels=infoLabels, json_episodios=season['episodios'], language=language, plot=episodios.get('descripcion'), thumbnail=item.thumbnail, title=unify.add_languages( (config.get_localized_string(60027) % str(season['temporada'])), language), url=item.url) # Asignamos valores al item según su contentType if contentType == 'movie': it.contentTitle = ogtitle else: it.contentSeason = season['temporada'] it.contentSerieName = ogtitle itemlist.append(it) # Asignamos las infoLabels (si aplica) if not item.videolibrary: tmdb.set_infoLabels(itemlist, True, force_no_year=True) # Si solo hay una temporada, retornamos directamente los episodios if len(itemlist) == 1: itemlist = episodesxseason(itemlist[0]) # Agregamos elemento "Agregar a videoteca" if len(itemlist) > 0 and config.get_videolibrary_support( ) and not itemlist[0].contentType == 'movie' and not item.videolibrary: itemlist.append( Item(action="add_serie_to_library", channel=item.channel, contentType='tvshow', contentSerieName=item.contentSerieName, extra="episodios", title='[COLOR yellow]{}[/COLOR]'.format( config.get_localized_string(60352)), url=item.url)) return itemlist
import urllib payload = urllib.urlencode({ 'action': 'doo_player_ajax', 'post': item.post, 'nume': item.nume, 'type': item.type }) data = httptools.downloadpage(item.url, post=payload).data patron = r"<iframe.*src='(([^']+))'\s" matches = re.compile(patron, re.IGNORECASE).findall(data) url = matches[0][0] url = url.strip() data = httptools.downloadpage(url, headers=headers).data itemlist = servertools.find_video_items(data=data) return itemlist NovitaThumbnail = "https://superrepo.org/static/images/icons/original/xplugin.video.moviereleases.png.pagespeed.ic.j4bhi0Vp3d.png" GenereThumbnail = "https://farm8.staticflickr.com/7562/15516589868_13689936d0_o.png" FilmFanart = "https://superrepo.org/static/images/fanart/original/script.artwork.downloader.jpg" CercaThumbnail = "http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search" CercaFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg" ListTxt = "[COLOR orange]Torna a video principale [/COLOR]" AvantiTxt = config.get_localized_string(30992) AvantiImg = "http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png" thumbnail = "http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"
def seasons(item, add_to_videolibrary=False): logger.info() itemlist = [] soup = create_soup(item.url) section = soup.find('div', id='seasons') for article in section.children: if not article.find('li', class_="none"): contentType = item.contentType infoLabels = item.infoLabels title = item.title seasontitle = str(article.find('span', class_='title').contents[0]) if not infoLabels['last_air_date'] and not infoLabels['premiered']: date = article.find('span', class_='title').i.text date = datetime.datetime.strptime(date, "%b. %d, %Y") infoLabels['last_air_date'] = date.strftime("%Y/%m/%d") infoLabels['premiered'] = infoLabels['last_air_date'] if not infoLabels['plot']: plot = soup.find('div', id='info').find('div', class_='wp-content') if plot: infoLabels['plot'] = "\n".join( [x.text for x in plot.find_all('p')]) # --- Si buscamos nº de temporada y es película, devolverá la cadena 'PELI' en vez de número --- # if 'PELI' in seasontitle: contentType = 'movie' else: if 'Especial' in item.title: seasonnum = '0' else: seasonnum = scrapertools.find_single_match( seasontitle, '(?is)\s(\d+)') if seasonnum: contentType = 'tvshow' infoLabels['season'] = int(seasonnum) if int(seasonnum) == 0: title = 'Especiales de ' + item.contentSerieName else: title = 'Temporada ' + str(seasonnum) else: contentType = 'movie' itemlist.append( item.clone(action='episodesxseason', contentType=contentType, episode_data=str(article), infoLabels=infoLabels, title=title)) tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True) itemlist.reverse( ) # Empieza por el último capítulo, así que se revierte la lista if len(itemlist) == 1 and not add_to_videolibrary: itemlist = episodesxseason(itemlist[0], add_to_videolibrary) if len(itemlist) > 0 and config.get_videolibrary_support( ) and not itemlist[0].contentType == 'movie' and not add_to_videolibrary: itemlist.append( Item(action="add_serie_to_library", channel=item.channel, contentSerieName=item.contentSerieName, extra="episodios", title='[COLOR yellow]{}[/COLOR]'.format( config.get_localized_string(70092)), url=item.url)) return itemlist
def getmainlist(view="thumb_"): logger.info() itemlist = list() # Añade los canales que forman el menú principal itemlist.append( Item(title=config.get_localized_string(30130), channel="news", action="mainlist", thumbnail=get_thumb("news.png", view), category=config.get_localized_string(30119), viewmode="thumbnails", context=[{ "title": config.get_localized_string(70285), "channel": "news", "action": "menu_opciones", "goto": True }])) itemlist.append( Item(title=config.get_localized_string(30118), channel="channelselector", action="getchanneltypes", thumbnail=get_thumb("channels.png", view), view=view, category=config.get_localized_string(30119), viewmode="thumbnails")) itemlist.append( Item(title=config.get_localized_string(70527), channel="alfavorites", action="mainlist", thumbnail=get_thumb("mylink.png", view), view=view, category=config.get_localized_string(70527), viewmode="thumbnails")) itemlist.append( Item(title=config.get_localized_string(30103), channel="search", action="mainlist", thumbnail=get_thumb("search.png", view), category=config.get_localized_string(30119), viewmode="list", context=[{ "title": config.get_localized_string(70286), "channel": "search", "action": "opciones", "goto": True }])) itemlist.append( Item(title=config.get_localized_string(30102), channel="favorites", action="mainlist", thumbnail=get_thumb("favorites.png", view), category=config.get_localized_string(30102), viewmode="thumbnails")) if config.get_videolibrary_support(): itemlist.append( Item(title=config.get_localized_string(30131), channel="videolibrary", action="mainlist", thumbnail=get_thumb("videolibrary.png", view), category=config.get_localized_string(30119), viewmode="thumbnails", context=[{ "title": config.get_localized_string(70287), "channel": "videolibrary", "action": "channel_config" }])) itemlist.append( Item(title=config.get_localized_string(30101), channel="downloads", action="mainlist", thumbnail=get_thumb("downloads.png", view), viewmode="list", context=[{ "title": config.get_localized_string(70288), "channel": "setting", "config": "downloads", "action": "channel_config" }])) thumb_setting = "setting_%s.png" % 0 # config.get_setting("plugin_updates_available") itemlist.append( Item(title=config.get_localized_string(30100), channel="setting", action="mainlist", thumbnail=get_thumb(thumb_setting, view), category=config.get_localized_string(30100), viewmode="list")) if config.is_xbmc(): itemlist.append( Item(title="Reportar un fallo", channel="setting", action="report_menu", thumbnail=get_thumb("error.png", view), category=config.get_localized_string(30104), viewmode="list")) itemlist.append( Item(title=config.get_localized_string(30104) + " (" + config.get_localized_string(20000) + " " + config.get_addon_version(with_fix=False) + ")", channel="help", action="mainlist", thumbnail=get_thumb("help.png", view), category=config.get_localized_string(30104), viewmode="list")) return itemlist
def filterchannels(category, view="thumb_"): logger.info() channelslist = [] frequent_list = [] freq = False if category == 'freq': freq = True category = 'all' # Si category = "allchannelstatus" es que estamos activando/desactivando canales # Si category = "all-channels" viene del canal test appenddisabledchannels = False if category == "allchannelstatus": category = "all" appenddisabledchannels = True # Lee la lista de canales channel_path = os.path.join(config.get_runtime_path(), "channels", '*.json') logger.info("channel_path=%s" % channel_path) channel_files = glob.glob(channel_path) logger.info("channel_files encontrados %s" % (len(channel_files))) channel_language = config.get_setting("channel_language", default="all") logger.info("channel_language=%s" % channel_language) for channel_path in channel_files: logger.info("channel=%s" % channel_path) channel = os.path.basename(channel_path).replace(".json", "") try: channel_parameters = channeltools.get_channel_parameters(channel) if channel_parameters["channel"] == 'community': continue # Si no es un canal lo saltamos if not channel_parameters["channel"]: continue logger.info("channel_parameters=%s" % repr(channel_parameters)) # Si prefiere el banner y el canal lo tiene, cambia ahora de idea if view == "banner_" and "banner" in channel_parameters: channel_parameters["thumbnail"] = channel_parameters["banner"] # si el canal está desactivado no se muestra el canal en la lista if not channel_parameters["active"]: continue # Se salta el canal si no está activo y no estamos activando/desactivando los canales channel_status = config.get_setting("enabled", channel_parameters["channel"]) if channel_status is None: # si channel_status no existe es que NO HAY valor en _data.json. # como hemos llegado hasta aquí (el canal está activo en channel.json), se devuelve True channel_status = True if not channel_status: # si obtenemos el listado de canales desde "activar/desactivar canales", y el canal está desactivado # lo mostramos, si estamos listando todos los canales desde el listado general y está desactivado, # no se muestra if not appenddisabledchannels: continue # Se salta el canal para adultos si el modo adultos está desactivado if channel_parameters["adult"] and config.get_setting( "adult_mode") == 0: if category != "all_channels": continue # Se salta el canal si está en un idioma filtrado # Se muestran todos los canales si se elige "all" en el filtrado de idioma # Se muestran sólo los idiomas filtrados, cast o lat # Los canales de adultos se mostrarán siempre que estén activos if channel_language != "all" and channel_language not in channel_parameters["language"] \ and "*" not in channel_parameters["language"]: if category != "all_channels": continue # Se salta el canal si está en una categoria filtrado if category != "all" and category not in channel_parameters[ "categories"]: if category != "all_channels": continue # Si tiene configuración añadimos un item en el contexto context = [] if channel_parameters["has_settings"]: context.append({ "title": config.get_localized_string(70525), "channel": "setting", "action": "channel_config", "config": channel_parameters["channel"] }) channel_info = set_channel_info(channel_parameters) # Si ha llegado hasta aquí, lo añade frequency = channeltools.get_channel_setting( "frequency", channel_parameters["channel"], 0) channelslist.append( Item(title=channel_parameters["title"], channel=channel_parameters["channel"], action="mainlist", thumbnail=channel_parameters["thumbnail"], fanart=channel_parameters["fanart"], plot=channel_info, category=channel_parameters["title"], language=channel_parameters["language"], viewmode="list", context=context, frequency=frequency)) except: logger.error( "Se ha producido un error al leer los datos del canal '%s'" % channel) import traceback logger.error(traceback.format_exc()) if config.get_setting('frequents'): for ch in channelslist: if int(ch.frequency) != 0: frequent_list.append(ch) frequent_list = sorted(frequent_list, key=lambda item: item.frequency, reverse=True) if freq: max_ff = config.get_setting("max_frequents_folder") if max_ff > 0: return frequent_list[0:max_ff] else: return frequent_list max_freq = config.get_setting("max_frequents") if frequent_list: if len(frequent_list) >= max_freq: max_freq = max_freq else: max_freq = len(frequent_list) frequent_list = frequent_list[0:max_freq] frequent_list.insert( 0, Item(title='- Canales frecuentes -', action='')) frequent_list.append(Item(title='- Todos los canales -', action='')) elif freq: for ch in channelslist: if int(ch.frequency) != 0: frequent_list.append(ch) frequent_list = sorted(frequent_list, key=lambda item: item.frequency, reverse=True) max_ff = config.get_setting("max_frequents_folder") if max_ff > 0: return frequent_list[0:max_ff] else: return frequent_list channelslist.sort(key=lambda item: item.title.lower().strip()) if category == "all": channel_parameters = channeltools.get_channel_parameters('url') # Si prefiere el banner y el canal lo tiene, cambia ahora de idea if view == "banner_" and "banner" in channel_parameters: channel_parameters["thumbnail"] = channel_parameters["banner"] channelslist.insert( 0, Item(title=config.get_localized_string(60088), action="mainlist", channel="url", thumbnail=channel_parameters["thumbnail"], type="generic", viewmode="list")) if frequent_list and config.get_setting('frequents'): channelslist = frequent_list + channelslist if category in ['movie', 'tvshow']: titles = [ config.get_localized_string(70028), config.get_localized_string(30985), config.get_localized_string(70559), config.get_localized_string(60264), config.get_localized_string(70560) ] ids = ['popular', 'top_rated', 'now_playing', 'on_the_air'] for x in range(0, 3): if x == 2 and category != 'movie': title = titles[x + 1] id = ids[x + 1] else: title = titles[x] id = ids[x] channelslist.insert( x, Item(channel='search', action='discover_list', title=title, search_type='list', list_type='%s/%s' % (category.replace('show', ''), id), thumbnail=get_thumb(id + ".png"), mode=category)) channelslist.insert( 3, Item(channel='search', action='years_menu', title='Por Años', type=category.replace('show', ''), thumbnail=get_thumb("years.png"), mode=category)) channelslist.insert( 4, Item(channel='search', action='genres_menu', title='Generos', type=category.replace('show', ''), thumbnail=get_thumb("genres.png"), mode=category)) return channelslist
def filterchannels(category, view="thumb_"): from core import channeltools logger.debug('Filter Channels ' + category) channelslist = [] # If category = "allchannelstatus" is that we are activating / deactivating channels appenddisabledchannels = False if category == "allchannelstatus": category = "all" appenddisabledchannels = True channel_path = os.path.join(config.get_runtime_path(), 'channels', '*.json') logger.debug("channel_path = %s" % channel_path) channel_files = glob.glob(channel_path) logger.debug("channel_files found %s" % (len(channel_files))) # Channel Language channel_language = auto_filter() logger.debug("channel_language=%s" % channel_language) for channel_path in channel_files: logger.debug("channel in for = %s" % channel_path) channel = os.path.basename(channel_path).replace(".json", "") try: channel_parameters = channeltools.get_channel_parameters(channel) if channel_parameters["channel"] == 'community': continue # If it's not a channel we skip it if not channel_parameters["channel"]: continue logger.debug("channel_parameters=%s" % repr(channel_parameters)) # If you prefer the banner and the channel has it, now change your mind if view == "banner_" and "banner" in channel_parameters: channel_parameters["thumbnail"] = channel_parameters["banner"] # if the channel is deactivated the channel is not shown in the list if not channel_parameters["active"]: continue # The channel is skipped if it is not active and we are not activating / deactivating the channels channel_status = config.get_setting("enabled", channel_parameters["channel"]) if channel_status is None: # if channel_status does not exist, there is NO value in _data.json. # as we got here (the channel is active in channel.json), True is returned channel_status = True if not channel_status: # if we get the list of channels from "activate / deactivate channels", and the channel is deactivated # we show it, if we are listing all the channels from the general list and it is deactivated, it is not shown if not appenddisabledchannels: continue if channel_language != "all" and "*" not in channel_parameters["language"] \ and channel_language not in str(channel_parameters["language"]): continue # The channel is skipped if it is in a filtered category if category != "all" and category not in channel_parameters[ "categories"]: continue # If you have configuration we add an item in the context context = [] if channel_parameters["has_settings"]: context.append({ "title": config.get_localized_string(70525), "channel": "setting", "action": "channel_config", "config": channel_parameters["channel"] }) channel_info = set_channel_info(channel_parameters) # If it has come this far, add it channelslist.append( Item(title=channel_parameters["title"], channel=channel_parameters["channel"], action="mainlist", thumbnail=channel_parameters["thumbnail"], fanart=channel_parameters["fanart"], plot=channel_info, category=channel_parameters["title"], language=channel_parameters["language"], viewmode="list", context=context)) except: logger.error( "An error occurred while reading the channel data '%s'" % channel) import traceback logger.error(traceback.format_exc()) channelslist.sort(key=lambda item: item.title.lower().strip()) if not config.get_setting("only_channel_icons"): if category == "all": channel_parameters = channeltools.get_channel_parameters('url') # If you prefer the banner and the channel has it, now change your mind if view == "banner_" and "banner" in channel_parameters: channel_parameters["thumbnail"] = channel_parameters["banner"] channelslist.insert( 0, Item(title=config.get_localized_string(60088), action="mainlist", channel="url", thumbnail=channel_parameters["thumbnail"], type="generic", viewmode="list")) # Special Category if category in ['movie', 'tvshow']: titles = [ config.get_localized_string(70028), config.get_localized_string(30985), config.get_localized_string(70559), config.get_localized_string(60264), config.get_localized_string(70560) ] ids = ['popular', 'top_rated', 'now_playing', 'on_the_air'] for x in range(0, 3): if x == 2 and category != 'movie': title = titles[x + 1] id = ids[x + 1] else: title = titles[x] id = ids[x] channelslist.insert( x, Item(channel='search', action='discover_list', title=title, search_type='list', list_type='%s/%s' % (category.replace('show', ''), id), mode=category, thumbnail=get_thumb(id + ".png"))) channelslist.insert( 3, Item(channel='search', action='genres_menu', title=config.get_localized_string(30987), type=category.replace('show', ''), mode=category, thumbnail=get_thumb("genres.png"))) return channelslist
def getmainlist(view="thumb_"): logger.debug() itemlist = list() if config.dev_mode(): itemlist.append( Item(title="Redirect", action="check_channels", thumbnail='', category=config.get_localized_string(30119), viewmode="thumbnails")) # Main Menu Channels if addon.getSetting('enable_news_menu') == "true": itemlist.append( Item(title=config.get_localized_string(30130), channel="news", action="mainlist", thumbnail=get_thumb("news.png", view), category=config.get_localized_string(30119), viewmode="thumbnails", context=[{ "title": config.get_localized_string(70285), "channel": "shortcuts", "action": "SettingOnPosition", "category": 7, "setting": 1 }])) if addon.getSetting('enable_channels_menu') == "true": itemlist.append( Item(title=config.get_localized_string(30118), channel="channelselector", action="getchanneltypes", thumbnail=get_thumb("channels.png", view), view=view, category=config.get_localized_string(30119), viewmode="thumbnails")) if addon.getSetting('enable_search_menu') == "true": itemlist.append( Item(title=config.get_localized_string(30103), channel="search", path='special', action="mainlist", thumbnail=get_thumb("search.png", view), category=config.get_localized_string(30119), viewmode="list", context=[{ "title": config.get_localized_string(60412), "action": "setting_channel_new", "channel": "search" }, { "title": config.get_localized_string(70286), "channel": "shortcuts", "action": "SettingOnPosition", "category": 5, "setting": 1 }])) if addon.getSetting('enable_onair_menu') == "true": itemlist.append( Item(channel="filmontv", action="mainlist", title=config.get_localized_string(50001), thumbnail=get_thumb("on_the_air.png"), viewmode="thumbnails")) if addon.getSetting('enable_link_menu') == "true": itemlist.append( Item(title=config.get_localized_string(70527), channel="kodfavorites", action="mainlist", thumbnail=get_thumb("mylink.png", view), view=view, category=config.get_localized_string(70527), viewmode="thumbnails")) if addon.getSetting('enable_fav_menu') == "true": itemlist.append( Item(title=config.get_localized_string(30102), channel="favorites", action="mainlist", thumbnail=get_thumb("favorites.png", view), category=config.get_localized_string(30102), viewmode="thumbnails")) if config.get_videolibrary_support() and addon.getSetting( 'enable_library_menu') == "true": itemlist.append( Item(title=config.get_localized_string(30131), channel="videolibrary", action="mainlist", thumbnail=get_thumb("videolibrary.png", view), category=config.get_localized_string(30119), viewmode="thumbnails", context=[{ "title": config.get_localized_string(70287), "channel": "shortcuts", "action": "SettingOnPosition", "category": 2, "setting": 1 }, { "title": config.get_localized_string(60568), "channel": "videolibrary", "action": "update_videolibrary" }])) if downloadenabled != "false": itemlist.append( Item(title=config.get_localized_string(30101), channel="downloads", action="mainlist", thumbnail=get_thumb("downloads.png", view), viewmode="list", context=[{ "title": config.get_localized_string(70288), "channel": "shortcuts", "action": "SettingOnPosition", "category": 6 }])) thumb_setting = "setting_%s.png" % 0 # config.get_setting("plugin_updates_available") itemlist.append( Item(title=config.get_localized_string(30100), channel="setting", action="settings", thumbnail=get_thumb(thumb_setting, view), category=config.get_localized_string(30100), viewmode="list", folder=False)) itemlist.append( Item(title=config.get_localized_string(30104) + " (v" + config.get_addon_version(with_fix=True) + ")", channel="help", action="mainlist", thumbnail=get_thumb("help.png", view), category=config.get_localized_string(30104), viewmode="list")) return itemlist
def test_video_exists(page_url): # El servidor no está soportado, lo informamos return False, config.get_localized_string(30065)
def test_video_exists(page_url): logger.info("(page_url='%s')" % page_url) data = httptools.downloadpage(page_url).data if "no longer exists" in data or "to copyright issues" in data: return False, config.get_localized_string(70449) % "tusfiles" return True, ""
def play_from_library(item): """ Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener más items, como mucho se puede colocar un dialogo de seleccion. Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante "Container.Update()" cargamos el strm como si un item desde dentro del addon se tratara, quitando todas las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para la videoteca. @type item: item @param item: elemento con información """ logger.info() #logger.debug("item: \n" + item.tostring('\n')) import xbmcgui import xbmcplugin import xbmc from time import sleep, time from channels import nextep # Intentamos reproducir una imagen (esto no hace nada y ademas no da error) xbmcplugin.setResolvedUrl( int(sys.argv[1]), True, xbmcgui.ListItem(path=os.path.join(config.get_runtime_path(), "resources", "subtitle.mp4"))) # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion sleep(0.5) ### Si no se pone esto se bloquea Kodi xbmc.Player().stop() # modificamos el action (actualmente la videoteca necesita "findvideos" ya que es donde se buscan las fuentes item.action = "findvideos" check_next_ep = nextep.check(item) window_type = config.get_setting("window_type", "videolibrary") # y volvemos a lanzar kodi if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1: # Ventana convencional xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")") else: # Ventana emergente from channels import videolibrary, autoplay p_dialog = platformtools.dialog_progress_bg( config.get_localized_string(20000), config.get_localized_string(70004)) p_dialog.update(0, '') itemlist = videolibrary.findvideos(item) if check_next_ep and autoplay.is_active(item.contentChannel): p_dialog.update(100, '') sleep(0.5) p_dialog.close() item = nextep.return_item(item) if item.next_ep: return play_from_library(item) else: while platformtools.is_playing(): # Ventana convencional sleep(5) p_dialog.update(50, '') it = item if not check_next_ep or not autoplay.is_active(item.contentChannel): '''# Se filtran los enlaces segun la lista negra if config.get_setting('filter_servers', "servers"): itemlist = servertools.filter_servers(itemlist)''' # Se limita la cantidad de enlaces a mostrar if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) # Se "limpia" ligeramente la lista de enlaces if config.get_setting("replace_VD", "videolibrary") == 1: itemlist = reorder_itemlist(itemlist) p_dialog.update(100, '') sleep(0.5) p_dialog.close() if len(itemlist) > 0: while not xbmc.Monitor().abortRequested(): # El usuario elige el mirror opciones = [] for item in itemlist: opciones.append(item.title) # Se abre la ventana de seleccion if (item.contentSerieName != "" and item.contentSeason != "" and item.contentEpisodeNumber != ""): cabecera = ("%s - %sx%s -- %s" % (item.contentSerieName, item.contentSeason, item.contentEpisodeNumber, config.get_localized_string(30163))) else: cabecera = config.get_localized_string(30163) seleccion = platformtools.dialog_select(cabecera, opciones) if seleccion == -1: return else: item = videolibrary.play(itemlist[seleccion])[0] if item.action == 'play': platformtools.play_video(item) else: channel = __import__( 'channels.%s' % item.contentChannel, None, None, ["channels.%s" % item.contentChannel]) if hasattr(channel, item.action): play_items = getattr(channel, item.action)( item.clone(action=item.action, channel=item.contentChannel)) return from channels import autoplay if (platformtools.is_playing() and item.action ) or item.server == 'torrent' or autoplay.is_active( item.contentChannel): break if it.show_server and check_next_ep: nextep.run(it) sleep(0.5) p_dialog.close()
def settings(item): ret = platformtools.show_channel_settings(caption=config.get_localized_string(70224)) platformtools.itemlist_refresh() return ret
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__)) # 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 download_from_server(item): logger.info(item.tostring()) unsupported_servers = ["torrent"] progreso = platformtools.dialog_progress(config.get_localized_string(30101), config.get_localized_string(70178) % item.server) channel = __import__('channels.%s' % item.contentChannel, None, None, ["channels.%s" % item.contentChannel]) if hasattr(channel, "play") and not item.play_menu: progreso.update(50, config.get_localized_string(70178) % item.server, config.get_localized_string(60003) % item.contentChannel) try: itemlist = getattr(channel, "play")(item.clone(channel=item.contentChannel, action=item.contentAction)) except: logger.error("Error en el canal %s" % item.contentChannel) else: if len(itemlist) and isinstance(itemlist[0], Item): download_item = item.clone(**itemlist[0].__dict__) download_item.contentAction = download_item.action download_item.infoLabels = item.infoLabels item = download_item elif len(itemlist) and isinstance(itemlist[0], list): item.video_urls = itemlist if not item.server: item.server = "directo" else: logger.info("No hay nada que reproducir") return {"downloadStatus": STATUS_CODES.error} progreso.close() logger.info("contentAction: %s | contentChannel: %s | server: %s | url: %s" % ( item.contentAction, item.contentChannel, item.server, item.url)) if not item.server or not item.url or not item.contentAction == "play" or item.server in unsupported_servers: logger.error("El Item no contiene los parametros necesarios.") return {"downloadStatus": STATUS_CODES.error} if not item.video_urls: video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(item.server, item.url, item.password, True) else: video_urls, puedes, motivo = item.video_urls, True, "" # Si no esta disponible, salimos if not puedes: logger.info("El vídeo **NO** está disponible") return {"downloadStatus": STATUS_CODES.error} else: logger.info("El vídeo **SI** está disponible") result = {} # Recorre todas las opciones hasta que consiga descargar una correctamente for video_url in reversed(video_urls): result = download_from_url(video_url[1], item) if result["downloadStatus"] in [STATUS_CODES.canceled, STATUS_CODES.completed]: break # Error en la descarga, continuamos con la siguiente opcion if result["downloadStatus"] == STATUS_CODES.error: continue # Devolvemos el estado return result
def novedades(item): logger.info() global list_newest threads = [] list_newest = [] start_time = time.time() mode = item.mode if mode == '': mode = 'normal' if mode == 'get_cached': if os.path.exists(menu_cache_path): return get_from_cache(item) multithread = config.get_setting("multithread", "news") logger.info("multithread= " + str(multithread)) if not multithread: if platformtools.dialog_yesno(config.get_localized_string(60515), config.get_localized_string(60516), config.get_localized_string(60517), config.get_localized_string(60518)): if config.set_setting("multithread", True, "news"): multithread = True if mode == 'normal': progreso = platformtools.dialog_progress( item.category, config.get_localized_string(60519)) list_canales, any_active = get_channels_list() if config.is_xbmc(): from specials import side_menu if mode == 'silent' and any_active and len( list_canales[item.extra]) > 0: side_menu.set_menu_settings(item) aux_list = [] for canal in list_canales[item.extra]: if len(aux_list) < 2: aux_list.append(canal) list_canales[item.extra] = aux_list if mode == 'set_cache': list_canales[item.extra] = list_canales[item.extra][2:] if any_active and len(list_canales[item.extra]) > 0: import math # fix float porque la division se hace mal en python 2.x number_of_channels = float(100) / len(list_canales[item.extra]) for index, channel in enumerate(list_canales[item.extra]): channel_id, channel_title = channel percentage = int(math.ceil((index + 1) * number_of_channels)) # if progreso.iscanceled(): # progreso.close() # logger.info("Búsqueda cancelada") # return itemlist # Modo Multi Thread if multithread: t = Thread(target=get_newest, args=[channel_id, item.extra], name=channel_title) t.start() threads.append(t) if mode == 'normal': progreso.update( percentage, "", config.get_localized_string(60520) % channel_title) # Modo single Thread else: if mode == 'normal': logger.info("Obteniendo novedades de channel_id=" + channel_id) progreso.update( percentage, "", config.get_localized_string(60520) % channel_title) get_newest(channel_id, item.extra) # Modo Multi Thread: esperar q todos los hilos terminen if multithread: pendent = [a for a in threads if a.isAlive()] t = float(100) / len(pendent) while pendent: index = (len(threads) - len(pendent)) + 1 percentage = int(math.ceil(index * t)) list_pendent_names = [a.getName() for a in pendent] if mode == 'normal': mensaje = config.get_localized_string(30994) % ( ", ".join(list_pendent_names)) progreso.update( percentage, config.get_localized_string(60521) % (len(threads) - len(pendent), len(threads)), mensaje) logger.debug(mensaje) if progreso.iscanceled(): logger.info("Busqueda de novedades cancelada") break time.sleep(0.5) pendent = [a for a in threads if a.isAlive()] if mode == 'normal': mensaje = config.get_localized_string(60522) % ( len(list_newest), time.time() - start_time) progreso.update(100, mensaje, " ", " ") logger.info(mensaje) start_time = time.time() # logger.debug(start_time) result_mode = config.get_setting("result_mode", "news") if mode != 'normal': result_mode = 0 if result_mode == 0: # Agrupados por contenido ret = group_by_content(list_newest) elif result_mode == 1: # Agrupados por canales ret = group_by_channel(list_newest) else: # Sin agrupar ret = no_group(list_newest) while time.time() - start_time < 2: # mostrar cuadro de progreso con el tiempo empleado durante almenos 2 segundos time.sleep(0.5) if mode == 'normal': progreso.close() if mode == 'silent': set_cache(item) item.mode = 'set_cache' ret = add_menu_items(item, ret) if mode != 'set_cache': return ret else: if mode != 'set_cache': no_channels = platformtools.dialog_ok( config.get_localized_string(30130) + ' - ' + item.extra, config.get_localized_string(70661), config.get_localized_string(70662)) return
def find_and_set_infoLabels(item): logger.info() # logger.info("item es %s" % item) p_dialog = None if not item.contentSeason: p_dialog = platformtools.dialog_progress_bg( config.get_localized_string(60296), config.get_localized_string(60293)) global otvdb_global tvdb_result = None title = item.contentSerieName # Si el titulo incluye el (año) se lo quitamos year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$") if year: title = title.replace(year, "").strip() item.infoLabels['year'] = year[1:-1] if not item.infoLabels.get("tvdb_id"): if not item.infoLabels.get("imdb_id"): otvdb_global = Tvdb(search=title, year=item.infoLabels['year']) else: otvdb_global = Tvdb(imdb_id=item.infoLabels.get("imdb_id")) elif not otvdb_global or otvdb_global.get_id( ) != item.infoLabels['tvdb_id']: otvdb_global = Tvdb(tvdb_id=item.infoLabels['tvdb_id']) if not item.contentSeason: p_dialog.update(50, config.get_localized_string(60296), config.get_localized_string(60295)) results, info_load = otvdb_global.get_list_results() logger.debug("results es %s" % results) if not item.contentSeason: p_dialog.update(100, config.get_localized_string(60296), config.get_localized_string(60297) % len(results)) p_dialog.close() if len(results) > 1: tvdb_result = platformtools.show_video_info( results, item=item, scraper=Tvdb, caption=config.get_localized_string(60298) % title) elif len(results) > 0: tvdb_result = results[0] # todo revisar if isinstance(item.infoLabels, InfoLabels): logger.debug("es instancia de infoLabels") infoLabels = item.infoLabels else: logger.debug("NO ES instancia de infoLabels") infoLabels = InfoLabels() if tvdb_result: infoLabels['tvdb_id'] = tvdb_result['id'] infoLabels['url_scraper'] = [ "http://thetvdb.com/index.php?tab=series&id=%s" % infoLabels['tvdb_id'] ] if not info_load: if otvdb_global.get_id() != infoLabels['tvdb_id']: otvdb_global = Tvdb(tvdb_id=infoLabels['tvdb_id']) otvdb_global.get_images(infoLabels['tvdb_id'], image="poster") otvdb_global.get_images(infoLabels['tvdb_id'], image="fanart") otvdb_global.get_tvshow_cast(infoLabels['tvdb_id']) item.infoLabels = infoLabels set_infoLabels_item(item) return True else: item.infoLabels = infoLabels return False
def mainlist(item): logger.info() itemlist = [] # list_canales, any_active = get_channels_list() channel_language = config.get_setting("channel_language", default="auto") if channel_language == 'auto': channel_language = auto_filter() #if list_canales['peliculas']: thumbnail = get_thumb("movie.png") new_item = Item(channel=item.channel, action="novedades", extra="peliculas", title=config.get_localized_string(30122), thumbnail=thumbnail) set_category_context(new_item) itemlist.append(new_item) # thumbnail = get_thumb("movie_4k.png") # new_item = Item(channel=item.channel, action="novedades", extra="4k", title=config.get_localized_string(70208), thumbnail=thumbnail) # # set_category_context(new_item) # itemlist.append(new_item) #if list_canales['terror']: # thumbnail = get_thumb("channels_horror.png") # new_item = Item(channel=item.channel, action="novedades", extra="terror", title=config.get_localized_string(70209), # thumbnail=thumbnail) # set_category_context(new_item) # itemlist.append(new_item) #if list_canales['infantiles']: # thumbnail = get_thumb("children.png") # new_item = Item(channel=item.channel, action="novedades", extra="infantiles", title=config.get_localized_string(60510), # thumbnail=thumbnail) # set_category_context(new_item) # itemlist.append(new_item) #if list_canales['series']: thumbnail = get_thumb("tvshow.png") new_item = Item(channel=item.channel, action="novedades", extra="series", title=config.get_localized_string(60511), thumbnail=thumbnail) set_category_context(new_item) itemlist.append(new_item) #if list_canales['anime']: thumbnail = get_thumb("anime.png") new_item = Item(channel=item.channel, action="novedades", extra="anime", title=config.get_localized_string(60512), thumbnail=thumbnail) set_category_context(new_item) itemlist.append(new_item) # if channel_language == "all": # # if list_canales['Italiano']: # thumbnail = get_thumb("italian.png") # new_item = Item(channel=item.channel, action="novedades", extra="italiano", title=config.get_localized_string(70563), # thumbnail=thumbnail) # set_category_context(new_item) # itemlist.append(new_item) # if list_canales['Torrent']: # thumbnail = get_thumb("channels_torrent.png") # new_item = Item(channel=item.channel, action="novedades", extra="torrent", title=config.get_localized_string(70171), thumbnail=thumbnail) # set_category_context(new_item) # itemlist.append(new_item) #if list_canales['documentales']: thumbnail = get_thumb("documentary.png") new_item = Item(channel=item.channel, action="novedades", extra="documentales", title=config.get_localized_string(60513), thumbnail=thumbnail) set_category_context(new_item) itemlist.append(new_item) thumbnail = get_thumb("setting_0.png") itemlist.append( Item(channel='shortcuts', action="SettingOnPosition", category=5, setting=0, title=typo(config.get_localized_string(70285), 'bold color kod'), thumbnail=thumbnail)) return itemlist
def get_default_settings(channel_name): import filetools, inspect # Check if it is a real channel try: channel = __import__('channels.%s' % channel_name, fromlist=["channels.%s" % channel_name]) except: return get_channel_json(channel_name).get('settings', list()) list_language = get_lang(channel_name) # Check if the automatic renumbering function exists renumber = False if 'episodios' in dir(channel): from core import scrapertoolsV2 if scrapertoolsV2.find_single_match(inspect.getsource(channel), r'(anime\s*=\s*True)') \ or scrapertoolsV2.find_single_match(inspect.getsource(channel), r'(autorenumber\()'): renumber = True # Collects configurations channel_language = categories = get_channel_json(channel_name).get( 'language', list()) channel_controls = get_channel_json(channel_name).get('settings', list()) default_path = filetools.join(config.get_runtime_path(), 'default_channel_settings' + '.json') default_controls = jsontools.load(filetools.read(default_path)).get( 'settings', list()) default_controls_renumber = jsontools.load( filetools.read(default_path)).get('renumber', list()) categories = get_channel_json(channel_name).get('categories', list()) not_active = get_channel_json(channel_name).get('not_active', list()) default_off = get_channel_json(channel_name).get('default_off', list()) logger.info('NON ATTIVI= ' + str(not_active)) # Apply default configurations if they do not exist for control in default_controls: if control['id'] not in str(channel_controls): if 'include_in_newest' in control[ 'id'] and 'include_in_newest' not in not_active: label = control['id'].split('_') label = label[-1] if label == 'peliculas': if 'movie' in categories: control['label'] = config.get_localized_string( 70727) + ' - ' + config.get_localized_string(30122) control[ 'default'] = True if 'include_in_newest' not in default_off else False channel_controls.append(control) else: pass elif label == 'series': if 'tvshow' in categories: control['label'] = config.get_localized_string( 70727) + ' - ' + config.get_localized_string(30123) control[ 'default'] = True if 'include_in_newest' not in default_off else False channel_controls.append(control) else: pass elif label == 'anime': if 'anime' in categories: control['label'] = config.get_localized_string( 70727) + ' - ' + config.get_localized_string(30124) control[ 'default'] = True if 'include_in_newest' not in default_off else False channel_controls.append(control) else: pass else: control['label'] = config.get_localized_string( 70727) + ' - ' + label.capitalize() control['default'] = True if control[ 'id'] not in default_off else False channel_controls.append(control) # elif control['id'] == 'filter_languages': # if len(channel_language) > 1: # control['lvalues'] = list_language # channel_controls.append(control) # else: pass elif control[ 'id'] not in not_active and 'include_in_newest' not in control[ 'id']: if type(control['default']) == bool: control['default'] = True if control[ 'id'] not in default_off else False channel_controls.append(control) if renumber: for control in default_controls_renumber: if control['id'] not in str(channel_controls): channel_controls.append(control) else: pass return channel_controls
def setting_channel(item): channels_path = os.path.join(config.get_runtime_path(), "channels", '*.json') channel_language = config.get_setting("channel_language", default="auto") if channel_language == 'auto': channel_language = auto_filter() list_controls = [] for infile in sorted(glob.glob(channels_path)): channel_id = os.path.basename(infile)[:-5] channel_parameters = channeltools.get_channel_parameters(channel_id) # No incluir si es un canal inactivo if not channel_parameters["active"]: continue # No incluir si es un canal para adultos, y el modo adulto está desactivado if channel_parameters["adult"] and config.get_setting( "adult_mode") == 0: continue # No incluir si el canal es en un idioma filtrado if channel_language != "all" and channel_language not in str(channel_parameters["language"]) \ and "*" not in channel_parameters["language"]: continue # No incluir si en su configuracion el canal no existe 'include_in_newest' include_in_newest = config.get_setting( "include_in_newest_" + item.extra, channel_id) if include_in_newest is None: continue control = { 'id': channel_id, 'type': "bool", 'label': channel_parameters["title"], 'default': include_in_newest, 'enabled': True, 'visible': True } list_controls.append(control) caption = config.get_localized_string(60533) + item.title.replace( config.get_localized_string(60525), "- ").strip() if config.get_setting("custom_button_value_news", item.channel): custom_button_label = config.get_localized_string(59992) else: custom_button_label = config.get_localized_string(59991) return platformtools.show_channel_settings(list_controls=list_controls, caption=caption, callback="save_settings", item=item, custom_button={ 'visible': True, 'function': "cb_custom_button", 'close': False, 'label': custom_button_label })
def mainlist(item): logger.info() itemlist = [] if config.is_xbmc(): itemlist.append( Item(title=config.get_localized_string(707429), channel="setting", action="report_menu", thumbnail=get_thumb("error.png"), viewmode="list", folder=True)) itemlist.append( Item(channel=item.channel, action="", title=config.get_localized_string(60447), thumbnail=get_thumb("help.png"), folder=False)) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(60449), thumbnail=get_thumb("help.png"), folder=False, extra="onoff_canales")) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(60450), thumbnail=get_thumb("help.png"), folder=False, extra="trakt_sync")) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(60451), thumbnail=get_thumb("help.png"), folder=False, extra="buscador_juntos")) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(60452), thumbnail=get_thumb("help.png"), folder=False, extra="tiempo_enlaces")) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(60453), thumbnail=get_thumb("help.png"), folder=False, extra="prob_busquedacont")) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(60454), thumbnail=get_thumb("help.png"), folder=False, extra="canal_fallo")) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(70280), thumbnail=get_thumb("help.png"), folder=False, extra="prob_torrent")) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(60455), thumbnail=get_thumb("help.png"), folder=False, extra="prob_bib")) itemlist.append( Item(channel=item.channel, action="faq", title=config.get_localized_string(60456), thumbnail=get_thumb("help.png"), folder=False, extra="")) return itemlist
def resolve_video_urls_for_playing(server, url, video_password="", muestra_dialogo=False, background_dialog=False): """ Function to get the real url of the video @param server: Server where the video is hosted @type server: str @param url: video url @type url: str @param video_password: Password for the video @type video_password: str @param muestra_dialogo: Show progress dialog @type muestra_dialogo: bool @type background_dialog: bool @param background_dialog: if progress dialog should be in background @return: returns the url of the video @rtype: list """ logger.info("Server: %s, Url: %s" % (server, url)) server = server.lower() video_urls = [] video_exists = True error_messages = [] opciones = [] # If the video is "direct" or "local", look no further if server == "directo" or server == "local": if isinstance(video_password, list): return video_password, len(video_password) > 0, "<br/>".join(error_messages) logger.info("Server: %s, url is good" % server) video_urls.append(["%s [%s]" % (urlparse.urlparse(url)[2][-4:], config.get_localized_string(30137)), url]) # Find out the video URL else: if server: server_parameters = get_server_parameters(server) else: server_parameters = {} if server_parameters: # Show a progress dialog if muestra_dialogo: progreso = (platformtools.dialog_progress_bg if background_dialog else platformtools.dialog_progress)(config.get_localized_string(20000), config.get_localized_string(70180) % translate_server_name(server_parameters["name"])) # Count the available options, to calculate the percentage orden = [ ["free"] + [server] + [premium for premium in server_parameters["premium"] if not premium == server], [server] + [premium for premium in server_parameters["premium"] if not premium == server] + ["free"], [premium for premium in server_parameters["premium"] if not premium == server] + [server] + ["free"] ] if server_parameters["free"] == True: opciones.append("free") opciones.extend( [premium for premium in server_parameters["premium"] if config.get_setting("premium", server=premium)]) priority = int(config.get_setting("resolve_priority")) opciones = sorted(opciones, key=lambda x: orden[priority].index(x)) logger.info("Available options: %s | %s" % (len(opciones), opciones)) else: logger.error("There is no connector for the server %s" % server) error_messages.append(config.get_localized_string(60004) % server) muestra_dialogo = False # Import the server try: server_module = __import__('servers.%s' % server, None, None, ["servers.%s" % server]) logger.info("Imported server: %s" % server_module) except: server_module = None if muestra_dialogo: progreso.close() logger.error("Could not import server: %s" % server) import traceback logger.error(traceback.format_exc()) # If it has a function to see if the video exists, check it now if hasattr(server_module, 'test_video_exists'): logger.info("Invoking a %s.test_video_exists" % server) try: video_exists, message = server_module.test_video_exists(page_url=url) if not video_exists: error_messages.append(message) logger.info("test_video_exists says video doesn't exist") if muestra_dialogo: progreso.close() else: logger.info("test_video_exists says the video DOES exist") except: logger.error("Could not verify if the video exists") import traceback logger.error(traceback.format_exc()) # If the video exists and the free mode is available, we get the url if video_exists: for opcion in opciones: # Own free and premium option uses the same server if opcion == "free" or opcion == server: serverid = server_module server_name = translate_server_name(server_parameters["name"]) # Rest of premium options use a debrider else: serverid = __import__('servers.debriders.%s' % opcion, None, None, ["servers.debriders.%s" % opcion]) server_name = get_server_parameters(opcion)["name"] # Show progress if muestra_dialogo: progreso.update((old_div(100, len(opciones))) * opciones.index(opcion), config.get_localized_string(70180) % server_name) # Free mode if opcion == "free": try: logger.info("Invoking a %s.get_video_url" % server) response = serverid.get_video_url(page_url=url, video_password=video_password) video_urls.extend(response) except: logger.error("Error getting url in free mode") error_messages.append(config.get_localized_string(60006) % server_name) import traceback logger.error(traceback.format_exc()) # Premium mode else: try: logger.info("Invoking a %s.get_video_url" % opcion) response = serverid.get_video_url(page_url=url, premium=True, user=config.get_setting("user", server=opcion), password=config.get_setting("password", server=opcion), video_password=video_password) if response and response[0][1]: video_urls.extend(response) elif response and response[0][0]: error_messages.append(response[0][0]) else: error_messages.append(config.get_localized_string(60006) % server_name) except: logger.error("Server errorr: %s" % opcion) error_messages.append(config.get_localized_string(60006) % server_name) import traceback logger.error(traceback.format_exc()) # If we already have URLS, we stop searching if video_urls and config.get_setting("resolve_stop") == True: break # We close progress if muestra_dialogo: progreso.update(100, config.get_localized_string(60008)) progreso.close() # If there are no options available, we show the notice of premium accounts if video_exists and not opciones and server_parameters.get("premium"): listapremium = [get_server_parameters(premium)["name"] for premium in server_parameters["premium"]] error_messages.append( config.get_localized_string(60009) % (server, " o ".join(listapremium))) # If we do not have urls or error messages, we put a generic one elif not video_urls and not error_messages: error_messages.append(config.get_localized_string(60006) % get_server_parameters(server)["name"]) return video_urls, len(video_urls) > 0, "<br/>".join(error_messages)
def mainlist(item): logger.info() item.channel = "search" itemlist = [] context = [{ "title": config.get_localized_string(60412), "action": "setting_channel", "channel": item.channel }] itemlist.append( Item(channel=item.channel, action="sub_menu", title=config.get_localized_string(70305), context=context, thumbnail=get_thumb("search.png"))) itemlist.append( Item(channel=item.channel, action='genres_menu', title=config.get_localized_string(70306), type='movie', thumbnail=get_thumb("genres.png"))) itemlist.append( Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70307), context=context, search_type='list', list_type='movie/popular', thumbnail=get_thumb("popular.png"))) itemlist.append( Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70308), context=context, search_type='list', list_type='movie/top_rated', thumbnail=get_thumb("top_rated.png"))) itemlist.append( Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70309), context=context, search_type='list', list_type='movie/now_playing', thumbnail=get_thumb("now_playing.png"))) itemlist.append( Item(channel=item.channel, action='genres_menu', title=config.get_localized_string(70310), type='tv', thumbnail=get_thumb("genres.png"))) itemlist.append( Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70311), context=context, search_type='list', list_type='tv/popular', thumbnail=get_thumb("popular.png"))) itemlist.append( Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70312), context=context, search_type='list', list_type='tv/on_the_air', thumbnail=get_thumb("on_the_air.png"))) itemlist.append( Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70313), context=context, search_type='list', list_type='tv/top_rated', thumbnail=get_thumb("top_rated.png"))) return itemlist
def translate_server_name(name): if '@' in name: return config.get_localized_string(int(name.replace('@',''))) else: return name
def setting_channel_new(item): import channelselector, xbmcgui from core import channeltools # Cargar lista de opciones (canales activos del usuario y que permitan búsqueda global) # ------------------------ lista = [] ids = [] lista_lang = [] channels_list = channelselector.filterchannels('all') for channel in channels_list: channel_parameters = channeltools.get_channel_parameters( channel.channel) # No incluir si en la configuracion del canal no existe "include_in_global_search" if not channel_parameters['include_in_global_search']: continue lbl = '%s' % channel_parameters['language'] lbl += ' %s' % ', '.join( config.get_localized_category(categ) for categ in channel_parameters['categories']) it = xbmcgui.ListItem(channel.title, lbl) it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart}) lista.append(it) ids.append(channel.channel) lista_lang.append(channel_parameters['language']) # Diálogo para pre-seleccionar # ---------------------------- preselecciones_std = [ 'Modificar selección actual', 'Modificar partiendo de Todos', 'Modificar partiendo de Ninguno', 'Modificar partiendo de Castellano', 'Modificar partiendo de Latino' ] if item.action == 'setting_channel': # Configuración de los canales incluídos en la búsqueda preselecciones = preselecciones_std presel_values = [1, 2, 3, 4, 5] else: # Llamada desde "buscar en otros canales" (se puede saltar la selección e ir directo a la búsqueda) preselecciones = ['Buscar con la selección actual' ] + preselecciones_std presel_values = [0, 1, 2, 3, 4, 5] ret = platformtools.dialog_select(config.get_localized_string(59994), preselecciones) if ret == -1: return False # pedido cancel if presel_values[ret] == 0: return True # continuar sin modificar elif presel_values[ret] == 3: preselect = [] elif presel_values[ret] == 2: preselect = range(len(ids)) elif presel_values[ret] in [4, 5]: busca = 'cast' if presel_values[ret] == 4 else 'lat' preselect = [] for i, lg in enumerate(lista_lang): if busca in lg or '*' in lg: preselect.append(i) else: preselect = [] for i, canal in enumerate(ids): channel_status = config.get_setting('include_in_global_search', canal) if channel_status: preselect.append(i) # Diálogo para seleccionar # ------------------------ ret = xbmcgui.Dialog().multiselect(config.get_localized_string(59994), lista, preselect=preselect, useDetails=True) if ret == None: return False # pedido cancel seleccionados = [ids[i] for i in ret] # Guardar cambios en canales para la búsqueda # ------------------------------------------- for canal in ids: channel_status = config.get_setting('include_in_global_search', canal) if channel_status is None: channel_status = True if channel_status and canal not in seleccionados: config.set_setting('include_in_global_search', False, canal) elif not channel_status and canal in seleccionados: config.set_setting('include_in_global_search', True, canal) return True
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"): 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(70014): 'castellano', config.get_localized_string(59976): 'latino', 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 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(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.info("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.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": import base64 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 else: # # 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 + ' - ' + 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.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": from core import servertools # 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": 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": logger.info("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 = '' tecleado = platformtools.dialog_input(last_search) if tecleado is not None: channeltools.set_channel_setting('Last_searched', tecleado, 'search') if 'search' in dir(channel): itemlist = channel.search(item, tecleado) else: from core import support itemlist = support.search(channel, 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'): 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 urllib2.URLError as e: # import traceback # logger.error(traceback.format_exc()) # # # Grab inner and third party errors # if hasattr(e, 'reason'): # logger.error("Reason for the error, code: %s | Reason: %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(config.get_localized_string(20000), texto) # # # Grab server response errors # elif hasattr(e, 'code'): # logger.error("HTTP error code: %d" % e.code) # # "El sitio web no funciona correctamente (error http %d)" # platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(30051) % e.code) except WebErrorException as e: import traceback from core import scrapertools 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 from core import scrapertools 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: import xbmc if config.get_platform(True)['num_version'] < 14: log_name = "xbmc.log" else: log_name = "kodi.log" log_message = config.get_localized_string(50004) + xbmc.translatePath("special://logpath") + log_name except: log_message = "" if canal: if item.url: if platformtools.dialog_yesno(config.get_localized_string(60087) % canal, config.get_localized_string(60014), log_message, 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) % canal, config.get_localized_string(60014), log_message) else: platformtools.dialog_ok( config.get_localized_string(60038), config.get_localized_string(60015), log_message)