API

Covers every method of xbmcswift2

Plugin Object

class xbmcswift2.Plugin(name=None, addon_id=None, filepath=None, info_type=None)

The Plugin objects encapsulates all the properties and methods necessary for running an XBMC plugin. The plugin instance is a central place for registering view functions and keeping track of plugin state.

Usually the plugin instance is created in the main addon.py file for the plugin. Typical creation looks like this:

from xbmcswift2 import Plugin
plugin = Plugin('Hello XBMC')

Changed in version 0.2: The addon_id and filepath parameters are now optional. They will now default to the correct values.

Parameters:
  • name – The name of the plugin, e.g. ‘Academic Earth’.
  • addon_id – The XBMC addon ID for the plugin, e.g. ‘plugin.video.academicearth’. This parameter is now optional and is really only useful for testing purposes. If it is not provided, the correct value will be parsed from the addon.xml file.
  • filepath – Optional parameter. If provided, it should be the path to the addon.py file in the root of the addon directoy. This only has an effect when xbmcswift2 is running on the command line. Will default to the current working directory since xbmcswift2 requires execution in the root addon directoy anyway. The parameter still exists to ease testing.
add_items(items)

Adds ListItems to the XBMC interface. Each item in the provided list should either be instances of xbmcswift2.ListItem, or regular dictionaries that will be passed to xbmcswift2.ListItem.from_dict. Returns the list of ListItems.

Parameters:items – An iterable of items where each item is either a dictionary with keys/values suitable for passing to xbmcswift2.ListItem.from_dict() or an instance of xbmcswift2.ListItem.
add_sort_method(sort_method, label2_mask=None)

A wrapper for xbmcplugin.addSortMethod(). You can use dir(xbmcswift2.SortMethod) to list all available sort methods.

Parameters:
  • sort_method

    A valid sort method. You can provided the constant from xbmcplugin, an attribute of SortMethod, or a string name. For instance, the following method calls are all equivalent:

    • plugin.add_sort_method(xbmcplugin.SORT_METHOD_TITLE)
    • plugin.add_sort_metohd(SortMethod.TITLE)
    • plugin.add_sort_method('title')
  • label2_mask – A mask pattern for label2. See the XBMC documentation for more information.
add_to_playlist(items, playlist='video')

Adds the provided list of items to the specified playlist. Available playlists include video and music.

add_url_rule(url_rule, view_func, name, options=None)

This method adds a URL rule for routing purposes. The provided name can be different from the view function name if desired. The provided name is what is used in url_for to build a URL.

The route decorator provides the same functionality.

added_items

The list of currently added items.

Even after repeated calls to add_items(), this property will contain the complete list of added items.

addon

This plugin’s wrapped instance of xbmcaddon.Addon.

cached(TTL=1440)

A decorator that will cache the output of the wrapped function. The key used for the cache is the function name as well as the *args and **kwargs passed to the function.

Parameters:TTL – time to live in minutes
cached_route(url_rule, name=None, options=None, TTL=None)

A decorator to add a route to a view and also apply caching. The url_rule, name and options arguments are the same arguments for the route function. The TTL argument if given will passed along to the caching decorator.

clear_function_cache()

Clears the storage that caches results when using xbmcswift2.Plugin.cached_route() or xbmcswift2.Plugin.cached().

end_of_directory(succeeded=True, update_listing=False, cache_to_disc=True)

Wrapper for xbmcplugin.endOfDirectory. Records state in self._end_of_directory.

Typically it is not necessary to call this method directly, as calling finish() will call this method.

finish(items=None, sort_methods=None, succeeded=True, update_listing=False, cache_to_disc=True, view_mode=None)

Adds the provided items to the XBMC interface.

Parameters:
  • items – an iterable of items where each item is either a dictionary with keys/values suitable for passing to xbmcswift2.ListItem.from_dict() or an instance of xbmcswift2.ListItem.
  • sort_methods

    a list of valid XBMC sort_methods. Each item in the list can either be a sort method or a tuple of sort_method, label2_mask. See add_sort_method() for more detail concerning valid sort_methods.

    Example call with sort_methods:

    sort_methods = ['label', 'title', ('date', '%D')]
    plugin.finish(items, sort_methods=sort_methods)
    
  • view_mode – can either be an integer (or parseable integer string) corresponding to a view_mode or the name of a type of view. Currrently the only view type supported is ‘thumbnail’.
Returns:

a list of all ListItems added to the XBMC interface.

get_setting(key, converter=None, choices=None)

Returns the settings value for the provided key. If converter is str, unicode, bool or int the settings value will be returned converted to the provided type. If choices is an instance of list or tuple its item at position of the settings value be returned. .. note:: It is suggested to always use unicode for text-settings

because else xbmc returns utf-8 encoded strings.
Parameters:
  • key – The id of the setting defined in settings.xml.
  • converter – (Optional) Choices are str, unicode, bool and int.
  • choices – (Optional) Choices are instances of list or tuple.
Examples:
  • plugin.get_setting('per_page', int)
  • plugin.get_setting('password', unicode)
  • plugin.get_setting('force_viewmode', bool)
  • plugin.get_setting('content', choices=('videos', 'movies'))
get_storage(name='main', file_format='pickle', TTL=None)

Returns a storage for the given name. The returned storage is a fully functioning python dictionary and is designed to be used that way. It is usually not necessary for the caller to load or save the storage manually. If the storage does not already exist, it will be created.

See also

xbmcswift2.TimedStorage for more details.

Parameters:
  • name – The name of the storage to retrieve.
  • file_format

    Choices are ‘pickle’, ‘csv’, and ‘json’. Pickle is recommended as it supports python objects.

    Note

    If a storage already exists for the given name, the file_format parameter is ignored. The format will be determined by the existing storage file.

  • TTL – The time to live for storage items specified in minutes or None for no expiration. Since storage items aren’t expired until a storage is loaded form disk, it is possible to call get_storage() with a different TTL than when the storage was created. The currently specified TTL is always honored.
get_string(stringid)

Returns the localized string from strings.xml for the given stringid.

get_view_mode_id(view_mode)

Attempts to return a view_mode_id for a given view_mode taking into account the current skin. If not view_mode_id can be found, None is returned. ‘thumbnail’ is currently the only suppported view_mode.

handle

The current plugin’s handle. Equal to plugin.request.handle.

id

The id for the addon instance.

keyboard(default=None, heading=None, hidden=False)

Displays the keyboard input window to the user. If the user does not cancel the modal, the value entered by the user will be returned.

Parameters:
  • default – The placeholder text used to prepopulate the input field.
  • heading – The heading for the window. Defaults to the current addon’s name. If you require a blank heading, pass an empty string.
  • hidden – Whether or not the input field should be masked with stars, e.g. a password field.
list_storages()

Returns a list of existing stores. The returned names can then be used to call get_storage().

log

The log instance for the plugin. Returns an instance of the stdlib’s logging.Logger. This log will print to STDOUT when running in CLI mode and will forward messages to XBMC’s log when running in XBMC. Some examples:

plugin.log.debug('Debug message')
plugin.log.warning('Warning message')
plugin.log.error('Error message')
name

The addon’s name

notify(msg='', title=None, delay=5000, image='')

Displays a temporary notification message to the user. If title is not provided, the plugin name will be used. To have a blank title, pass ‘’ for the title argument. The delay argument is in milliseconds.

open_settings()

Opens the settings dialog within XBMC

redirect(url)

Used when you need to redirect to another view, and you only have the final plugin:// url.

register_module(module, url_prefix)

Registers a module with a plugin. Requires a url_prefix that will then enable calls to url_for.

Parameters:
  • module – Should be an instance xbmcswift2.Module.
  • url_prefix – A url prefix to use for all module urls, e.g. ‘/mymodule’
request

The current Request.

Raises an Exception if the request hasn’t been initialized yet via run().

route(url_rule, name=None, options=None)

A decorator to add a route to a view. name is used to differentiate when there are multiple routes for a given view.

run(test=False)

The main entry point for a plugin.

set_content(content)

Sets the content type for the plugin.

set_resolved_url(item=None, subtitles=None)

Takes a url or a listitem to be played. Used in conjunction with a playable list item with a path that calls back into your addon.

Parameters:
  • item

    A playable list item or url. Pass None to alert XBMC of a failure to resolve the item.

    Warning

    When using set_resolved_url you should ensure the initial playable item (which calls back into your addon) doesn’t have a trailing slash in the URL. Otherwise it won’t work reliably with XBMC’s PlayMedia().

  • subtitles – A URL to a remote subtitles file or a local filename for a subtitles file to be played along with the item.
set_view_mode(view_mode_id)

Calls XBMC’s Container.SetViewMode. Requires an integer view_mode_id

storage_path

A full path to the storage folder for this plugin’s addon data.

url_for(endpoint, **items)

Returns a valid XBMC plugin URL for the given endpoint name. endpoint can be the literal name of a function, or it can correspond to the name keyword arguments passed to the route decorator.

Raises AmbiguousUrlException if there is more than one possible view for the given endpoint name.

ListItem

class xbmcswift2.ListItem(label=None, label2=None, icon=None, thumbnail=None, path=None)

A wrapper for the xbmcgui.ListItem class. The class keeps track of any set properties that xbmcgui doesn’t expose getters for.

add_context_menu_items(items, replace_items=False)

Adds context menu items. If replace_items is True all previous context menu items will be removed.

add_stream_info(stream_type, stream_values)

Adds stream details

as_tuple()

Returns a tuple of list item properties: (path, the wrapped xbmcgui.ListItem, is_folder)

as_xbmc_listitem()

Returns the wrapped xbmcgui.ListItem

classmethod from_dict(label=None, label2=None, icon=None, thumbnail=None, path=None, selected=None, info=None, properties=None, context_menu=None, replace_context_menu=False, is_playable=None, info_type='video', stream_info=None)

A ListItem constructor for setting a lot of properties not available in the regular __init__ method. Useful to collect all the properties in a dict and then use the **dct to call this method.

get_context_menu_items()

Returns the list of currently set context_menu items.

get_icon()

Returns the listitem’s icon image

get_is_playable()

Returns True if the listitem is playable, False if it is a directory

get_label()

Sets the listitem’s label

get_label2()

Returns the listitem’s label2

get_path()

Returns the listitem’s path

get_played()

Returns True if the video was played.

get_property(key)

Returns the property associated with the given key

get_thumbnail()

Returns the listitem’s thumbnail image

icon

Returns the listitem’s icon image

is_selected()

Returns True if the listitem is selected.

label

Sets the listitem’s label

label2

Returns the listitem’s label2

path

Returns the listitem’s path

playable

Returns True if the listitem is playable, False if it is a directory

select(selected_status=True)

Sets the listitems selected status to the provided value. Defaults to True.

selected

Returns True if the listitem is selected.

set_icon(icon)

Sets the listitem’s icon image

set_info(type, info_labels)

Sets the listitems info

set_is_playable(is_playable)

Sets the listitem’s playable flag

set_label(label)

Returns the listitem’s label

set_label2(label)

Sets the listitem’s label2

set_path(path)

Sets the listitem’s path

set_played(was_played)

Sets the played status of the listitem. Used to differentiate between a resolved video versus a playable item. Has no effect on XBMC, it is strictly used for xbmcswift2.

set_property(key, value)

Sets a property for the given key and value

set_thumbnail(thumbnail)

Sets the listitem’s thumbnail image

thumbnail

Returns the listitem’s thumbnail image

Request

class xbmcswift2.Request(url, handle)

The request objects contains all the arguments passed to the plugin via the command line.

Parameters:
  • url – The complete plugin URL being requested. Since XBMC typically passes the URL query string in a separate argument from the base URL, they must be joined into a single string before being provided.
  • handle – The handle associated with the current request.
handle = None

The current request’s handle, an integer.

url = None

The entire request url.

Actions

xbmcswift2.actions

This module contains wrapper functions for XBMC built-in functions.

copyright:
  1. 2012 by Jonathan Beluch
license:

GPLv3, see LICENSE for more details.

xbmcswift2.actions.background(url)[source]

This action will run an addon in the background for the provided URL.

See ‘XBMC.RunPlugin()’ at http://wiki.xbmc.org/index.php?title=List_of_built-in_functions.

xbmcswift2.actions.update_view(url)[source]

This action will update the current container view with provided url.

See ‘XBMC.Container.Update()’ at http://wiki.xbmc.org/index.php?title=List_of_built-in_functions.

Extended API

Module

class xbmcswift2.Module(namespace)

Modules are basically mini plugins except they don’t have any functionality until they are registered with a Plugin.

add_items(items)

Adds ListItems to the XBMC interface. Each item in the provided list should either be instances of xbmcswift2.ListItem, or regular dictionaries that will be passed to xbmcswift2.ListItem.from_dict. Returns the list of ListItems.

Parameters:items – An iterable of items where each item is either a dictionary with keys/values suitable for passing to xbmcswift2.ListItem.from_dict() or an instance of xbmcswift2.ListItem.
add_sort_method(sort_method, label2_mask=None)

A wrapper for xbmcplugin.addSortMethod(). You can use dir(xbmcswift2.SortMethod) to list all available sort methods.

Parameters:
  • sort_method

    A valid sort method. You can provided the constant from xbmcplugin, an attribute of SortMethod, or a string name. For instance, the following method calls are all equivalent:

    • plugin.add_sort_method(xbmcplugin.SORT_METHOD_TITLE)
    • plugin.add_sort_metohd(SortMethod.TITLE)
    • plugin.add_sort_method('title')
  • label2_mask

    A mask pattern for label2. See the XBMC documentation for more information.

add_to_playlist(items, playlist='video')

Adds the provided list of items to the specified playlist. Available playlists include video and music.

add_url_rule(url_rule, view_func, name, options=None)

This method adds a URL rule for routing purposes. The provided name can be different from the view function name if desired. The provided name is what is used in url_for to build a URL.

The route decorator provides the same functionality.

added_items

Returns this module’s added_items

addon

Returns the module’s addon

cache_path

Returns the module’s cache_path.

cached(TTL=1440)

A decorator that will cache the output of the wrapped function. The key used for the cache is the function name as well as the *args and **kwargs passed to the function.

Parameters:TTL – time to live in minutes
clear_function_cache()

Clears the storage that caches results when using xbmcswift2.Plugin.cached_route() or xbmcswift2.Plugin.cached().

end_of_directory(succeeded=True, update_listing=False, cache_to_disc=True)

Wrapper for xbmcplugin.endOfDirectory. Records state in self._end_of_directory.

Typically it is not necessary to call this method directly, as calling finish() will call this method.

finish(items=None, sort_methods=None, succeeded=True, update_listing=False, cache_to_disc=True, view_mode=None)

Adds the provided items to the XBMC interface.

Parameters:
  • items – an iterable of items where each item is either a dictionary with keys/values suitable for passing to xbmcswift2.ListItem.from_dict() or an instance of xbmcswift2.ListItem.
  • sort_methods

    a list of valid XBMC sort_methods. Each item in the list can either be a sort method or a tuple of sort_method, label2_mask. See add_sort_method() for more detail concerning valid sort_methods.

    Example call with sort_methods:

    sort_methods = ['label', 'title', ('date', '%D')]
    plugin.finish(items, sort_methods=sort_methods)
    
  • view_mode – can either be an integer (or parseable integer string) corresponding to a view_mode or the name of a type of view. Currrently the only view type supported is ‘thumbnail’.
Returns:

a list of all ListItems added to the XBMC interface.

get_setting(key, converter=None, choices=None)

Returns the settings value for the provided key. If converter is str, unicode, bool or int the settings value will be returned converted to the provided type. If choices is an instance of list or tuple its item at position of the settings value be returned. .. note:: It is suggested to always use unicode for text-settings

because else xbmc returns utf-8 encoded strings.
Parameters:
  • key – The id of the setting defined in settings.xml.
  • converter – (Optional) Choices are str, unicode, bool and int.
  • choices – (Optional) Choices are instances of list or tuple.
Examples:
  • plugin.get_setting('per_page', int)
  • plugin.get_setting('password', unicode)
  • plugin.get_setting('force_viewmode', bool)
  • plugin.get_setting('content', choices=('videos', 'movies'))
get_storage(name='main', file_format='pickle', TTL=None)

Returns a storage for the given name. The returned storage is a fully functioning python dictionary and is designed to be used that way. It is usually not necessary for the caller to load or save the storage manually. If the storage does not already exist, it will be created.

See also

xbmcswift2.TimedStorage for more details.

Parameters:
  • name – The name of the storage to retrieve.
  • file_format

    Choices are ‘pickle’, ‘csv’, and ‘json’. Pickle is recommended as it supports python objects.

    Note

    If a storage already exists for the given name, the file_format parameter is ignored. The format will be determined by the existing storage file.

  • TTL – The time to live for storage items specified in minutes or None for no expiration. Since storage items aren’t expired until a storage is loaded form disk, it is possible to call get_storage() with a different TTL than when the storage was created. The currently specified TTL is always honored.
get_string(stringid)

Returns the localized string from strings.xml for the given stringid.

get_view_mode_id(view_mode)

Attempts to return a view_mode_id for a given view_mode taking into account the current skin. If not view_mode_id can be found, None is returned. ‘thumbnail’ is currently the only suppported view_mode.

handle

Returns this module’s handle

keyboard(default=None, heading=None, hidden=False)

Displays the keyboard input window to the user. If the user does not cancel the modal, the value entered by the user will be returned.

Parameters:
  • default – The placeholder text used to prepopulate the input field.
  • heading – The heading for the window. Defaults to the current addon’s name. If you require a blank heading, pass an empty string.
  • hidden – Whether or not the input field should be masked with stars, e.g. a password field.
list_storages()

Returns a list of existing stores. The returned names can then be used to call get_storage().

log

Returns the registered plugin’s log.

notify(msg='', title=None, delay=5000, image='')

Displays a temporary notification message to the user. If title is not provided, the plugin name will be used. To have a blank title, pass ‘’ for the title argument. The delay argument is in milliseconds.

open_settings()

Opens the settings dialog within XBMC

plugin

Returns the plugin this module is registered to, or raises a RuntimeError if not registered.

redirect(url)

Used when you need to redirect to another view, and you only have the final plugin:// url.

request

Returns the current request

route(url_rule, name=None, options=None)

A decorator to add a route to a view. name is used to differentiate when there are multiple routes for a given view.

set_content(content)

Sets the content type for the plugin.

set_resolved_url(item=None, subtitles=None)

Takes a url or a listitem to be played. Used in conjunction with a playable list item with a path that calls back into your addon.

Parameters:
  • item

    A playable list item or url. Pass None to alert XBMC of a failure to resolve the item.

    Warning

    When using set_resolved_url you should ensure the initial playable item (which calls back into your addon) doesn’t have a trailing slash in the URL. Otherwise it won’t work reliably with XBMC’s PlayMedia().

  • subtitles – A URL to a remote subtitles file or a local filename for a subtitles file to be played along with the item.
set_view_mode(view_mode_id)

Calls XBMC’s Container.SetViewMode. Requires an integer view_mode_id

url_for(endpoint, explicit=False, **items)

Returns a valid XBMC plugin URL for the given endpoint name. endpoint can be the literal name of a function, or it can correspond to the name keyword arguments passed to the route decorator.

Currently, view names must be unique across all plugins and modules. There are not namespace prefixes for modules.

url_prefix

Sets or gets the url prefix of the module.

Raises an Exception if this module is not registered with a Plugin.

TimedStorage

class xbmcswift2.TimedStorage(filename, file_format='pickle', TTL=None)

A dict with the ability to persist to disk and TTL for items.

close()

Calls sync

dump(fileobj)

Handles the writing of the dict to the file object

initial_update(mapping)

Initially fills the underlying dictionary with keys, values and timestamps.

load(fileobj)

Load the dict from the file object

raw_dict()

Returns the wrapped dict

sync()

Write the dict to disk

Table Of Contents

Related Topics

This Page