我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用xbmcplugin.setPluginCategory()。
def channeltypes(params,url,category): logger.info("channelselector.channeltypes") lista = getchanneltypes() for item in lista: addfolder(item.title,item.channel,item.action,category=item.category,thumbnailname=item.thumbnail) if config.get_platform()=="kodi-krypton": import plugintools plugintools.set_view( plugintools.TV_SHOWS ) # Label (top-right)... import xbmcplugin xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category="" ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True ) if config.get_setting("forceview")=="true": # Confluence - Thumbnail import xbmc xbmc.executebuiltin("Container.SetViewMode(500)")
def listchannels(params,url,category): logger.info("channelselector.listchannels") lista = filterchannels(category) for channel in lista: if config.is_xbmc() and (channel.type=="xbmc" or channel.type=="generic"): addfolder(channel.title , channel.channel , "mainlist" , channel.channel) elif config.get_platform()=="boxee" and channel.extra!="rtmp": addfolder(channel.title , channel.channel , "mainlist" , channel.channel) if config.get_platform()=="kodi-krypton": import plugintools plugintools.set_view( plugintools.TV_SHOWS ) # Label (top-right)... import xbmcplugin xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True ) if config.get_setting("forceview")=="true": # Confluence - Thumbnail import xbmc xbmc.executebuiltin("Container.SetViewMode(500)")
def channeltypes(params,url,category): logger.info("channelselector.mainlist channeltypes") categoria=category.decode('latin1').encode('utf-8') if config.get_localized_string(30119) in categoria: lista = getchanneltypes() for item in lista: addfolder(item.title,item.channel,item.action,item.category,item.thumbnail,item.thumbnail) # Label (top-right)... import xbmcplugin xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category="" ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True ) if config.get_setting("forceview")=="true": # Confluence - Thumbnail import xbmc xbmc.executebuiltin("Container.SetViewMode(500)") else: listchannels({'action': 'listchannels', 'category': '%2a', 'channel': 'channelselector'},'','*')
def create_listing(listing, succeeded=True, update_listing=False, cache_to_disk=False, sort_methods=None, view_mode=None, content=None, category=None): """ Create and return a context dict for a virtual folder listing :param listing: the list of the plugin virtual folder items :type listing: list or types.GeneratorType :param succeeded: if ``False`` Kodi won't open a new listing and stays on the current level. :type succeeded: bool :param update_listing: if ``True``, Kodi won't open a sub-listing but refresh the current one. :type update_listing: bool :param cache_to_disk: cache this view to disk. :type cache_to_disk: bool :param sort_methods: the list of integer constants representing virtual folder sort methods. :type sort_methods: tuple :param view_mode: a numeric code for a skin view mode. View mode codes are different in different skins except for ``50`` (basic listing). :type view_mode: int :param content: string - current plugin content, e.g. 'movies' or 'episodes'. See :func:`xbmcplugin.setContent` for more info. :type content: str :param category: str - plugin sub-category, e.g. 'Comedy'. See :func:`xbmcplugin.setPluginCategory` for more info. :type category: str :return: context object containing necessary parameters to create virtual folder listing in Kodi UI. :rtype: ListContext """ return ListContext(listing, succeeded, update_listing, cache_to_disk, sort_methods, view_mode, content, category)
def _add_directory_items(self, context): """ Create a virtual folder listing :param context: context object :type context: ListContext :raises SimplePluginError: if sort_methods parameter is not int, tuple or list """ self.log_debug('Creating listing from {0}'.format(str(context))) if context.category is not None: xbmcplugin.setPluginCategory(self._handle, context.category) if context.content is not None: xbmcplugin.setContent(self._handle, context.content) # This must be at the beginning for item in context.listing: is_folder = item.get('is_folder', True) if item.get('list_item') is not None: list_item = item['list_item'] else: list_item = self.create_list_item(item) if item.get('is_playable'): list_item.setProperty('IsPlayable', 'true') is_folder = False xbmcplugin.addDirectoryItem(self._handle, item['url'], list_item, is_folder) if context.sort_methods is not None: if isinstance(context.sort_methods, int): xbmcplugin.addSortMethod(self._handle, context.sort_methods) elif isinstance(context.sort_methods, (tuple, list)): for method in context.sort_methods: xbmcplugin.addSortMethod(self._handle, method) else: raise TypeError( 'sort_methods parameter must be of int, tuple or list type!') xbmcplugin.endOfDirectory(self._handle, context.succeeded, context.update_listing, context.cache_to_disk) if context.view_mode is not None: xbmc.executebuiltin('Container.SetViewMode({0})'.format(context.view_mode))
def mainlist(params,url,category): logger.info("channelselector.mainlist") # Verifica actualizaciones solo en el primer nivel if config.get_platform()!="boxee": try: from core import updater except ImportError: logger.info("channelselector.mainlist No disponible modulo actualizaciones") else: if config.get_setting("updatecheck2") == "true": logger.info("channelselector.mainlist Verificar actualizaciones activado") updater.checkforupdates() else: logger.info("channelselector.mainlist Verificar actualizaciones desactivado") itemlist = getmainlist("squares") for elemento in itemlist: logger.info("channelselector item="+elemento.tostring()) addfolder(elemento.title , elemento.channel , elemento.action , thumbnailname=elemento.thumbnail, folder=elemento.folder) if config.get_platform()=="kodi-krypton": import plugintools plugintools.set_view( plugintools.TV_SHOWS ) # Label (top-right)... import xbmcplugin #xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category="" ) #xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True ) if config.get_setting("forceview")=="true": # Confluence - Thumbnail import xbmc xbmc.executebuiltin("Container.SetViewMode(500)")
def run(self, category=''): """ Run plugin :param category: str - plugin sub-category, e.g. 'Comedy'. See :func:`xbmcplugin.setPluginCategory` for more info. :type category: str :raises simpleplugin.SimplePluginError: if unknown action string is provided. """ self._handle = int(sys.argv[1]) if category: xbmcplugin.setPluginCategory(self._handle, category) params = self.get_params(sys.argv[2][1:]) action = params.get('action', 'root') self.log_debug(str(self)) self.log_debug('Actions: {0}'.format(str(self.actions.keys()))) self.log_debug('Called action "{0}" with params "{1}"'.format(action, str(params))) try: action_callable = self.actions[action] except KeyError: raise SimplePluginError('Invalid action: "{0}"!'.format(action)) else: result = action_callable(params) self.log_debug('Action return value: {0}'.format(str(result))) if isinstance(result, (list, GeneratorType)): self._add_directory_items(self.create_listing(result)) elif isinstance(result, basestring): self._set_resolved_url(self.resolve_url(result)) elif isinstance(result, tuple) and hasattr(result, 'listing'): self._add_directory_items(result) elif isinstance(result, tuple) and hasattr(result, 'path'): self._set_resolved_url(result) else: self.log_debug('The action "{0}" has not returned any valid data to process.'.format(action))
def mainlist(params,url,category): logger.info("[trailertools.py] mainlist") titulo = "" listavideos = GetTrailerbyKeyboard(titulo,category) if len(listavideos)>0: for video in listavideos: titulo = video[1] url = video[0] thumbnail = video[2] xbmctools.addnewvideo( "trailertools" , "youtubeplay" , category , "Directo" , titulo , url , thumbnail , "Ver Video" ) xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def buscartrailer(params,url,category): print "[trailertools.py] Modulo: buscartrailer()" thumbnail = "" solo = "false" videotitle = title = urllib.unquote_plus( params.get("title") ).strip() if ":]" in videotitle: solo = "true" videotitle = re.sub("\[[^\]]+\]","",videotitle).strip() if config.get_localized_string(30110) in videotitle: #"Buscar trailer para" videotitle = videotitle.replace(config.get_localized_string(30110),"").strip() if config.get_localized_string(30111) in videotitle: #"Insatisfecho?, busca otra vez : " videotitle = videotitle.replace(config.get_localized_string(30111),"").strip() listavideos = GetTrailerbyKeyboard(videotitle.strip(),category) else: listavideos = gettrailer(videotitle.strip().strip(),category,solo) if len(listavideos)>0: for video in listavideos: titulo = video[1] url = video[0] thumbnail = video[2] duracion = video[3] xbmctools.addnewvideo( "trailertools" , "youtubeplay" , category , "youtube" , titulo , url , thumbnail , "Ver Video","",duracion ) xbmctools.addnewfolder( CHANNELNAME , "buscartrailer" , category , config.get_localized_string(30111)+" "+videotitle , url , os.path.join(IMAGES_PATH, 'trailertools.png'), "" ) #"Insatisfecho?, busca otra vez : " # Propiedades xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def mainlist(params,url,category): logger.info("channelselector.mainlist") # Verifica actualizaciones solo en el primer nivel if config.get_platform()!="boxee": try: from core import updater except ImportError: logger.info("channelselector.mainlist No disponible modulo actualizaciones") else: if config.get_setting("updatecheck2") == "true": logger.info("channelselector.mainlist Verificar actualizaciones activado") try: updater.checkforupdates() except: import xbmcgui dialog = xbmcgui.Dialog() dialog.ok("Impossibile connettersi","Non è stato possibile verificare","la disponibilità di aggiornamenti") logger.info("channelselector.mainlist Fallo al verificar la actualización") pass else: logger.info("channelselector.mainlist Verificar actualizaciones desactivado") itemlist = getmainlist() for elemento in itemlist: logger.info("channelselector.mainlist item="+elemento.title) addfolder(elemento.title , elemento.channel , elemento.action , thumbnail=elemento.thumbnail, folder=elemento.folder) # Label (top-right)... import xbmcplugin xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category="" ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True ) if config.get_setting("forceview")=="true": # Confluence - Thumbnail import xbmc xbmc.executebuiltin("Container.SetViewMode(500)")
def Populate(self, content): self.PrefixActions() content() xbmcplugin.setPluginCategory(self.handle, PLUGIN_NAME) xbmcplugin.endOfDirectory(self.handle)
def search(self): xbmcplugin.setContent(self.addon_handle, "files") xbmcplugin.setPluginCategory(self.addon_handle, xbmc.getLocalizedString(283)) kb = xbmc.Keyboard('', xbmc.getLocalizedString(16017)) kb.doModal() if kb.isConfirmed(): value = kb.getText() items = [] result = self.sp.search( q="%s" % value, type='artist,album,track,playlist', limit=1, market=self.usercountry) items.append( ("%s (%s)" % (xbmc.getLocalizedString(133), result["artists"]["total"]), "plugin://plugin.audio.spotify/?action=search_artists&artistid=%s" % (value))) items.append( ("%s (%s)" % (xbmc.getLocalizedString(136), result["playlists"]["total"]), "plugin://plugin.audio.spotify/?action=search_playlists&playlistid=%s" % (value))) items.append( ("%s (%s)" % (xbmc.getLocalizedString(132), result["albums"]["total"]), "plugin://plugin.audio.spotify/?action=search_albums&albumid=%s" % (value))) items.append( ("%s (%s)" % (xbmc.getLocalizedString(134), result["tracks"]["total"]), "plugin://plugin.audio.spotify/?action=search_tracks&trackid=%s" % (value))) for item in items: li = xbmcgui.ListItem( item[0], path=item[1], iconImage="DefaultMusicAlbums.png" ) li.setProperty('do_not_analyze', 'true') li.setProperty('IsPlayable', 'false') li.addContextMenuItems([], True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=item[1], listitem=li, isFolder=True) xbmcplugin.endOfDirectory(handle=self.addon_handle)
def add_items_to_kodi_directory(itemlist,parent_item): logger.info("tvalacarta.platformcode.xbmctools add_items_to_kodi_directory") pluginhandle = int( sys.argv[ 1 ] ) # Checks if channel provides context menu for items exec "import channels."+parent_item.channel+" as channelmodule" channel_provides_context_menu = hasattr(channelmodule, 'get_context_menu_for_item') for item in itemlist: # If video has no fanart, here is assigned a new one if item.fanart=="": channel_fanart = os.path.join( config.get_runtime_path(), 'resources', 'images', 'fanart', item.channel+'.jpg') if os.path.exists(channel_fanart): item.fanart = channel_fanart else: item.fanart = os.path.join(config.get_runtime_path(),"fanart.jpg") # Add item to kodi directory add_item_to_kodi_directory(item,itemlist,channel_provides_context_menu) # Closes the XBMC directory xbmcplugin.setPluginCategory( handle=pluginhandle, category=parent_item.category ) xbmcplugin.addSortMethod( handle=pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_NONE ) # Forces the view mode if config.get_setting("forceview")=="true": import plugintools if parent_item.view=="list": plugintools.set_view( plugintools.LIST ) elif parent_item.view=="programs": plugintools.set_view( plugintools.TV_SHOWS ) elif parent_item.view=="channels" or parent_item.view=="thumbnails": if config.get_platform()=="kodi-krypton": plugintools.set_view( plugintools.TV_SHOWS ) else: plugintools.set_view( plugintools.THUMBNAIL ) elif parent_item.view=="videos": plugintools.set_view( plugintools.EPISODES ) xbmcplugin.endOfDirectory( handle=pluginhandle, succeeded=True )
def system(self, data, cl=False): util.debug("[SC] SYSYEM CL: %s" % str(cl)); if cl is False and "setContent" in data: xbmcplugin.setContent(int(sys.argv[1]), data["setContent"]) ''' view_mode=data["setContent"].lower() skin_name=xbmc.getSkinDir() # nacitame meno skinu util.debug("[SC] skin_name='"+skin_name+"'") try: util.debug("[SC] view mode is "+view_mode) view_codes=sctop.ALL_VIEW_CODES.get(view_mode) view_code=view_codes.get(skin_name) util.debug("[SC] view code for "+view_mode+" in "+skin_name+" is "+str(view_code)) xbmc.executebuiltin("Container.SetViewMode("+str(view_code)+")") #xbmc.executebuiltin("Container.Refresh") except: util.debug("[SC] Unable to find view code for view mode "+str(view_mode)+" and skin "+skin_name) ''' if cl is False and "setPluginCategory" in data: xbmcplugin.setPluginCategory(int(sys.argv[1]), data["setPluginCategory"]) if cl is False and "addSortMethod" in data: xbmcplugin.addSortMethod(int(sys.argv[1]), sctop.sortmethod[int(data["addSortMethod"])]) if cl is False and data.get('addSortMethods'): for m in data.get("addSortMethods"): xbmcplugin.addSortMethod(int(sys.argv[1]), sctop.sortmethod[int(m)]) if cl is False and "setPluginFanart" in data: xbmcplugin.setPluginFanart(int(sys.argv[1]), data["setPluginFanart"]) if cl is False and "version" in data: util.info("[SC] kontrola verzie: %s %s" % (str(sctop.addonInfo('version')), data["version"])) if sctop.addonInfo('version') != data["version"] and sctop.getSetting('ver') != data['version']: try: sctop.dialog.ok(sctop.getString(30954), sctop.getString(30955) % str(data['version'])) except: pass xbmc.executebuiltin('UpdateAddonRepos') sctop.setSetting('ver', data['version']) if sctop.getSettingAsBool('cachemigrate') == '' or sctop.getSettingAsBool('cachemigrate') is False: self.parent.cacheMigrate() pass pass if cl is False and "focus" in data: self.parent.system = {"focus": data['focus']} if cl is True and "focus" in data: try: self.parent.endOfDirectory() util.debug("[SC] nastavujem focus na: %d" % int(data['focus'])) xel = xbmcgui.Window(xbmcgui.getCurrentWindowId()) ctr = xel.getControl(xel.getFocusId()) ctr.selectItem(int(data['focus'])) except Exception, e: util.debug("[SC] error focus :-( %s" % str(traceback.format_exc())) pass
def gettrailer(titulovideo,category,solo="false"): print "[trailertools.py] Modulo: gettrailer(titulo = %s , category = %s)" % (titulovideo,category) if not solo=="true": titulo = re.sub('\([^\)]+\)','',titulovideo) titulo = title = re.sub('\[[^\]]+\]','',titulo) sopa_palabras_invalidas = ("dvdrip" , "dvdscreener2" ,"tsscreener" , "latino" , # Esto es para peliculasyonkis o parecidos "dvdrip1", "dvdscreener" ,"tsscreener1", "latino1", "latino2", "dvdscreener1" ,"screener" , "mirror" , "megavideo" ,"vose" , "subtitulada" ) titulo = LimpiarTitulo(titulo) print "el tituloooo es :%s" %titulo trozeado = titulo.split() for trozo in trozeado: if trozo in sopa_palabras_invalidas: titulo = titulo.replace(trozo ,"") titulo = re.sub(' $','',titulo) titulo = titulo.replace("ver pelicula online vos","").strip() titulo = titulo.replace("ver pelicula online","").strip() titulo = titulo.replace("mirror 1","").strip() titulo = titulo.replace("parte 1","").strip() titulo = titulo.replace("part 1","").strip() titulo = titulo.replace("pt 1","").strip() titulo = titulo.replace("peliculas online","").strip() encontrados = [] if len(titulo)==0: titulo = "El_video_no_tiene_titulo" encontrados = GetFrom_Trailersdepeliculas(titulo) # Primero busca en www.trailerdepeliculas.org encontrados = encontrados + GetVideoFeed(titulo) # luego busca con el API de youtube else: titulo = titulovideo encontrados = [] if len(titulo)==0: titulo = "El_video_no_tiene_titulo" encontrados = encontrados + GetVideoFeed(titulo,"true") if len(encontrados)>0: # si encuentra algo, termina return encontrados else: encontrados = GetFromYoutubePlaylist(titulo) # si no encuentra, busca en las listas de la web de youtube if len(encontrados)>0: return encontrados else: respuesta = alertnoencontrado(titulo) # si aun no encuentra,lanza mensaje de alerta y pregunta si quiere if respuesta: # buscar, modificando el titulo, con el teclado encontrados = GetTrailerbyKeyboard(titulo,category) # si respuesta es afirmativa este entrara en un bucle if len(encontrados)>0: # de autollamadas hasta encontrar el trailer o la respuesta return encontrados # del mensaje alerta sea negativo. else:return [] else: xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category ) xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True ) return encontrados