soco.music_services.music_service module

Sonos Music Services interface.

This module provides the MusicService class and related functionality.

Known problems:

  1. Not all music services follow the pattern layout for the authentication information completely. This means that it might be necessary to tweak the code for individual services. This is an unfortunate result of Sonos not enforcing data hygiene of its services. The implication for SoCo is that getting all services to work will require more effort and the kind of broader testing we will only get by putting the code out there. Hence, if you are an early adopter of the music service code (added in version 0.26) consider yourselves guinea pigs.

  2. There currently is no way to reset an authentication, at least when authentication has been performed for TIDAL (which uses device link authentication), after it has been done once for a particular household ID, it fails on subsequent attempts. What this might mean is that if you lose the authentication tokens for such a service, it may not be possible to generate new ones. Obviously, some method must exist to reset this, but it is not presently implemented.

class soco.music_services.music_service.MusicServiceSoapClient(endpoint, timeout, music_service, token_store, device=None)[source]

A SOAP client for accessing Music Services.

This class handles all the necessary authentication for accessing third party music services. You are unlikely to need to use it yourself.

Parameters:
  • endpoint (str) – The SOAP endpoint. A url.

  • timeout (int) – Timeout the connection after this number of seconds

  • music_service (MusicService) – The MusicService object to which this client belongs.

  • token_store (TokenStoreBase) – A token store instance. The token store is an instance of a subclass of TokenStoreBase

  • device (SoCo) – (Optional) If provided this device will be used for the communication; if not, the device returned by discovery.any_soco will be used

get_soap_header()[source]

Generate the SOAP authentication header for the related service.

This header contains all the necessary authentication details.

Returns:

A string representation of the XML content of the SOAP

header.

Return type:

str

call(method, args=None)[source]

Call a method on the server.

Parameters:
  • method (str) – The name of the method to call.

  • args (List[Tuple[str, str]] or None) – A list of (parameter, value) pairs representing the parameters of the method. Defaults to None.

Returns:

An OrderedDict representing the response.

Return type:

OrderedDict

Raises:

MusicServiceException – containing details of the error returned by the music service.

begin_authentication()[source]

Perform the first part of a Device or App Link authentication session

See begin_authentication for details

complete_authentication(link_code, link_device_id=None)[source]

Completes a previously initiated authentication session

See complete_authentication for details

class soco.music_services.music_service.MusicService(service_name, token_store=None, device=None)[source]

The MusicService class provides access to third party music services.

Example

List all the services Sonos knows about:

>>> from soco.music_services import MusicService
>>> print(MusicService.get_all_music_services_names())
['Spotify', 'The Hype Machine', 'Saavn', 'Bandcamp',
 'Stitcher SmartRadio', 'Concert Vault',
 ...
 ]

Interact with TuneIn:

>>> tunein = MusicService('TuneIn')
>>> print (tunein)
<MusicService 'TuneIn' at 0x10ad84e10>

Browse an item. By default, the root item is used. An SearchResult is returned (the output of print is here indented for easier reading):

>>> print(tunein.get_metadata())
SearchResult(
  items=[
    <soco.music_services.data_structures.MSContainer object at 0x7f58b038ac10>,
    <soco.music_services.data_structures.MSContainer object at 0x7f58b038a340>,
    <soco.music_services.data_structures.MSContainer object at 0x7f58b038a6d0>,
    <soco.music_services.data_structures.MSContainer object at 0x7f58b038a310>,
    <soco.music_services.data_structures.MSContainer object at 0x7f58b038a100>,
    <soco.music_services.data_structures.MSContainer object at 0x7f58b038a910>
  ],
  search_type='browse'
)

Interact with Spotify (assuming you are subscribed):

>>> spotify = MusicService('Spotify')

Get some metadata about a specific track:

>>> response =  spotify.get_media_metadata(
... item_id='spotify:track:6NmXV4o6bmp704aPGyTVVG')
>>> print(dumps(response, indent=4))
{
    "mediaMetadata": {
        "id": "spotify:track:6NmXV4o6bmp704aPGyTVVG",
        "itemType": "track",
        "title": "Bøn Fra Helvete (Live)",
        "mimeType": "audio/x-spotify",
        "trackMetadata": {
            "artistId": "spotify:artist:1s1DnVoBDfp3jxjjew8cBR",
            "artist": "Kaizers Orchestra",
            "albumId": "spotify:album:6K8NUknbPh5TGaKeZdDwSg",
            "album": "Mann Mot Mann (Ep)",
            "duration": "317",
            "albumArtURI":
            "http://o.scdn.co/image/7b76a5074416e83fa3f3cd...9",
            "canPlay": "true",
            "canSkip": "true",
            "canAddToFavorites": "true"
        }
    }
}
or even a playlist:
>>> response =  spotify.get_metadata(
...    item_id='spotify:user:spotify:playlist:0FQk6BADgIIYd3yTLCThjg')

Find the available search categories, and use them:

>>> print(spotify.available_search_categories)
['albums', 'tracks', 'artists']
>>> result =  spotify.search(category='artists', term='miles')

Note

Some of this code is still unstable, and in particular the data structures returned by methods such as get_metadata may change in future.

Parameters:
  • service_name (str) – The name of the music service, as returned by get_all_music_services_names(), eg ‘Spotify’, or ‘TuneIn’

  • token_store (TokenStoreBase) – A token store instance. If none is given, it will default to an instance of the JsonFileTokenStore using the ‘default’ token collection. The token store must be an instance of a subclass of TokenStoreBase.

  • device (SoCo) – (Optional) If provided this device will be used for the communication, if not the device returned by discovery.any_soco will be used

Raises:

MusicServiceException

classmethod get_all_music_services_names()[source]

Get a list of the names of all available music services.

These services have not necessarily been subscribed to.

Returns:

A list of strings.

Return type:

list

classmethod get_data_for_name(service_name)[source]

Get the data relating to a named music service.

Parameters:

service_name (str) – The name of the music service for which data is required.

Returns:

Data relating to the music service.

Return type:

dict

Raises:

MusicServiceException – if the music service cannot be found.

property available_search_categories

The list of search categories (each a string) supported.

May include 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags', or others depending on the service. Some services, such as Spotify, support 'all', but do not advertise it.

Any of the categories in this list may be used as a value for category in search().

Example

>>> print(spotify.available_search_categories)
['albums', 'tracks', 'artists']
>>> result =  spotify.search(category='artists', term='miles')
Type:

list

sonos_uri_from_id(item_id)[source]

Get a uri which can be sent for playing.

Parameters:

item_id (str) – The unique id of a playable item for this music service, such as that returned in the metadata from get_metadata, eg spotify:track:2qs5ZcLByNTctJKbhAZ9JE

Returns:

A URI of the form: soco://spotify%3Atrack %3A2qs5ZcLByNTctJKbhAZ9JE?sid=2311&sn=1 which encodes the item_id, and relevant data from the account for the music service. This URI can be sent to a Sonos device for playing, and the device itself will retrieve all the necessary metadata such as title, album etc.

Return type:

str

property desc

The Sonos descriptor to use for this service.

The Sonos descriptor is used as the content of the <desc> tag in DIDL metadata, to indicate the relevant music service id.

Type:

str

begin_authentication()[source]

Perform the first part of a Device or App Link authentication session

This result of this is an authentication URL, which a user needs visit and complete the necessary authentication on and then proceed to complete_authentication

Note

The begin_authentication and complete_authentication methods must be completed on the same `MusicService` instance unless the link_code and link_device_id values are passed to complete_authentication. These two values can be found as attributes on the MusicService instance after begin_authentication has been executed.

Returns:

Registration URL used for service linking.

Return type:

str

complete_authentication(link_code=None, link_device_id=None)[source]

Completes a previously initiated device or app link authentication session

This method is the second part of a two-step authentication process, see begin_authentication for details on the first part.

Parameters:
  • link_code (str, optional) – A link code generated from begin_authentication. If not provided, cached code will be used.

  • link_device_id (str, optional) – A link device ID generated from begin_authentication. If not provided, cached device ID will be used.

get_metadata(item='root', index=0, count=100, recursive=False)[source]

Get metadata for a container or item.

Parameters:
  • item (str or MusicServiceItem) – The container or item to browse given either as a MusicServiceItem instance or as a str. Defaults to the root item.

  • index (int) – The starting index. Default 0.

  • count (int) – The maximum number of items to return. Default 100.

  • recursive (bool) – Whether the browse should recurse into sub-items (Does not always work). Defaults to False.

Returns:

The item or container’s metadata, or None.

Return type:

OrderedDict

See also

The Sonos getMetadata API.

search(category, term='', index=0, count=100)[source]

Search for an item in a category.

Parameters:
  • category (str) – The search category to use. Standard Sonos search categories are ‘artists’, ‘albums’, ‘tracks’, ‘playlists’, ‘genres’, ‘stations’, ‘tags’. Not all are available for each music service. Call available_search_categories for a list for this service.

  • term (str) – The term to search for.

  • index (int) – The starting index. Default 0.

  • count (int) – The maximum number of items to return. Default 100.

Returns:

The search results, or None.

Return type:

OrderedDict

See also

The Sonos search API

get_media_metadata(item_id)[source]

Get metadata for a media item.

Parameters:

item_id (str) – The item for which metadata is required.

Returns:

The item’s metadata, or None

Return type:

OrderedDict

See also

The Sonos getMediaMetadata API

get_media_uri(item_id)[source]

Get a streaming URI for an item.

Note

You should not need to use this directly. It is used by the Sonos players (not the controllers) to obtain the uri of the media stream. If you want to have a player play a media item, you should add it to the queue using its id and let the player work out where to get the stream from (see On Demand Playback and Programmed Radio)

Parameters:

item_id (str) – The item for which the URI is required

Returns:

The item’s streaming URI.

Return type:

str

get_last_update()[source]

Get last_update details for this music service.

Returns:

A dict with keys ‘catalog’, and ‘favorites’. The value of each is a string which changes each time the catalog or favorites change. You can use this to detect when any caches need to be updated.

Return type:

OrderedDict

get_extended_metadata(item_id)[source]

Get extended metadata for a media item, such as related items.

Parameters:

item_id (str) – The item for which metadata is required.

Returns:

The item’s extended metadata or None.

Return type:

OrderedDict

See also

The Sonos getExtendedMetadata API

get_extended_metadata_text(item_id, metadata_type)[source]

Get extended metadata text for a media item.

Parameters:
  • item_id (str) – The item for which metadata is required

  • metadata_type (str) – The type of text to return, eg

  • 'ARTIST_BIO'

  • Calling (or 'ALBUM_NOTES'.) –

  • extended (get_extended_metadata for the item will show which) –

  • available (metadata_types are) –

Returns:

The item’s extended metadata text or None

Return type:

str

See also

The Sonos getExtendedMetadataText API