spotifywebapipython.zeroconfapi.zeroconfconnect

@export
class ZeroconfConnect:

Interfaces with the Spotify Connect Zeroconf API to add and remove a device to / from the Spotify Connect active device list.

More information about Spotify Connect Zeroconf API can be found here:
https://developer.spotify.com/documentation/commercial-hardware/implementation/guides/zeroconf

Inspiration and some of the blob encryption encoding was derived from the zerospot GitHub repository.

ZeroconfConnect( hostIpAddress: str, hostIpPort: int, cpath: str, version: str = None, useSSL: bool = False, tokenStorageDir: str = None, tokenStorageFile: str = None, tokenAuthInBrowser: bool = False)

Initializes a new instance of the class.

Arguments:
  • hostIpAddress (str): IP address or alias at which the Spotify Connect Zeroconf API can be reached on the Spotify Connect device (e.g. "192.168.1.81", "Bose-SM2-341513fbeeae.local.", etc).
  • hostIpPort (int): Port number (as an integer) at which the Spotify Connect Zeroconf API can be reached on the Spotify Connect device (e.g. "8200").
  • cpath (str): Spotify Connect Zeroconf API CPath property value (e.g. "/zc").
  • version (str): Spotify Connect Zeroconf API version number that the device supports (e.g. "2.10.0").
    Default is null.
  • useSSL (bool): True if the host device utilizes HTTPS Secure Sockets Layer (SSL) support; otherwise, False to utilize HTTP.
    Default is False (HTTP).
  • tokenStorageDir (str): The directory path that will contain the Token Cache file.
    This is used for Spotify Connect devices that utilize the authorization_code token type. A null value will default to the platform specific storage location:
    Example for Windows OS = C:\ProgramData\SpotifyWebApiPython
  • tokenStorageFile (str): The filename and extension of the Token Cache file.
    Default is SpotifyWebApiPython_tokens.json.
  • tokenAuthInBrowser (bool): True to allow authorization access token to be authorized if necessary via an interactive browser; otherwise, False.
    Default is False.

Set the tokenAuthInBrowser argument to False if your process does not allow user interaction with the local default browser to approve authorization requests (e.g. if your process runs on a server for instance). Set to True if you have a desktop / console application that allows interactive access to the local default browser.

SPOTIFY_CONNECT_CLIENT_VERSION_DEFAULT: str = '2.7.1'

Spotify Connect default version string ('2.7.1').

CPath: str

Path that points to the ZeroConf implementation on the server (e.g. "/zc").

HostIpAddress: str

IP address or alias at which the Spotify Connect Zeroconf API can be reached on the Spotify Connect device (e.g. "192.168.1.81", "Bose-SM2-341513fbeeae.local.", etc).

HostIpPort: int

Port number (as an integer) at which the Spotify Connect Zeroconf API can be reached on the Spotify Connect device (e.g. "8200").

TokenAuthInBrowser: bool

True to allow authorization access token to be authorized if necessary via an interactive browser; otherwise, False.

TokenStorageDir: str

The directory path that will contain the authorization token cache file.

TokenStorageFile: str

The filename and extension of the authorization token cache file.

Uri: str

Spotify Connect Zeroconf API URI that will be used to access the device (e.g. "http://192.168.1.81:8200/zc").

UseSSL: str

True if the host device utilizes HTTPS Secure Sockets Layer (SSL) support; otherwise, False to utilize HTTP.

Default is False (HTTP).

Version: str

Spotify Connect Zeroconf API version number that the device supports (e.g. "", "1.0", "2.10.0", etc.).

def Connect( self, username: str, password: str, loginId: str = None, delay: float = 0.5) -> spotifywebapipython.zeroconfapi.zeroconfresponse.ZeroconfResponse:

Calls the addUser Spotify Zeroconf API endpoint to issue a call to SpConnectionLoginBlob. If successful, the associated device id is added to the Spotify Connect active device list for the specified user account.

Arguments:
  • username (str): Spotify Connect user name to login with (e.g. "yourspotifyusername").
    This MUST match the account name (or one of them) that was used to configure Spotify Connect on the manufacturer device.
  • password (str): Spotify Connect user password to login with.
  • loginId (str): Spotify Connect login id to login with (e.g. "31l77fd87g8h9j00k89f07jf87ge").
    This is also known as the canonical user id value.
    This MUST be the value that relates to the username argument.
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the device.
    This delay will give the spotify zeroconf api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Returns:

A ZeroconfResponse object that indicates success or failure (see notes below).

Raises:
  • SpotifyWebApiError: If the Spotify Zeroconf API request response contains error information.

This will first issue a call to the getInfo Spotify Zeroconf API endpoint to retrieve the Spotify Connect device id associated with the device. It will then issue a call to the addUser Spotify Zeroconf API endpoint to add the user to the device.

Some Spotify Connect device types will be "woken up" with the initial addUser request; when this happens, the initial request will return a 203 status (ERROR-INVALID-PUBLICKEY), and return a valid public key in the response. This public key is then used to submit another addUser request to connect to the device with the newly returned public key. When this happens, a ZeroconfResponse object is returned with the result of the final addUser request. If only one addUser request is processed, then a ZeroconfGetInfo object is returned with the result of the addUser request. Note that ZeroconfGetInfo inherits from ZeroconfResponse, so you can always treat the result of this method as a ZeroconfResponse object.

The login (on the device) is performed asynchronously, so the return result only indicates whether the library is able to perform the login attempt. You should issue a call to the Spotify Web API Get Available Devices endpoint to check the current device list to ensure that the device id was successfully added or not.

Note that if you don't have a password setup for your Spotify account (e.g. you utilize the "Continue with Google" or other non-password methods for login), then you will need to define a "device password" in order to use the ZeroConf Connect service; use the Spotify Set Device Password page to define a device password. You will then use your Spotify username and the device password to Connect to the device.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.zeroconfapi import *

try:

    # set credentials used to login to Spotify from the device.
    # username is your Spotify username (e.g. 'yourname@gmail.com', '1234567890', etc).
    # loginid is your Spotify canonical login id (e.g. '31l77548798704mns987fdf0986e').
    username = 'YourSpotifyUsername'    
    password = 'YourSpotifyPassword'
    loginid  = 'YourSpotifyLoginId'

    # create Spotify Zeroconf API connection object for the device.
    zconn:ZeroconfConnect = ZeroconfConnect('192.168.1.81', 8200, '/zc', useSSL=False, tokenStorageDir='./test/testdata')

    # disconnect the device from Spotify Connect.
    print('\nDisconnecting device:%s' % zconn.ToString())
    result:ZeroconfResponse = zconn.Disconnect()
    print('\nResult - %s' % result.ToString())
    print("\nDevice should have been removed from the Spotify Connect device list")

    # connect the device to Spotify Connect, which should make it known to any available
    # Spotify Connect player clients.
    print('\nConnecting device:%s' % zconn.ToString())
    result:ZeroconfResponse = zconn.Connect(username, password, loginid)
    print('\nResult - %s' % result.ToString())
    print("\nDevice should be available in the Spotify Connect device list")

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - spotifyD

from spotifywebapipython import *
from spotifywebapipython.zeroconfapi import *

try:

    # set credentials used to login to Spotify from the device.
    # username is your Spotify username (e.g. 'yourname@gmail.com', '1234567890', etc).
    # loginid is your Spotify canonical login id (e.g. '31l77548798704mns987fdf0986e').
    username = 'YourSpotifyUsername'    
    password = 'YourSpotifyPassword'
    loginid  = 'YourSpotifyLoginId'

    # you must copy the librespot `credentials.json` file from the spotifyd cache location
    # directory (e.g. /home/<user>/.cache/spotifyd/credentials.json) to the spotifywebapiPython
    # token storage directory (e.g. ./test/testdata/spotifywebapiPython_librespot_credentials.json).
    # the file must be refreshed if your Spotify password is ever changed.

    # create Spotify Zeroconf API connection object for the device.
    zconn:ZeroconfConnect = ZeroconfConnect('192.168.1.81', 8200, '/', useSSL=False, tokenStorageDir='./test/testdata')

    # NOTE - do not issue a Disconnect call, as librespot does not implement the Spotify Connect
    # Zeroconf `resetUsers` endpoint; a 404 request error will result if you do.

    # connect the device to Spotify Connect on the spotifyd instance.
    print('\nConnecting device:%s' % zconn.ToString())
    result:ZeroconfResponse = zconn.Connect(username, password, loginid)
    print('\nResult - %s' % result.ToString())
    print("\nDevice should be available in the Spotify Connect device list")

except Exception as ex:

    print("** Exception: %s" % str(ex))

def Disconnect( self, delay: float = 0.5, ignoreStatusResult: bool = False) -> spotifywebapipython.zeroconfapi.zeroconfresponse.ZeroconfResponse:

Calls the resetUsers Spotify Zeroconf API endpoint to issue a call to SpConnectionLogout.

Arguments:
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the device.
    This delay will give the spotify zeroconf api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
  • ignoreStatusResult (bool): True to ignore processing of result status code; otherwise, False to check the result status code for errors and raise an exception if needed.
    Default is
Returns:

A ZeroconfResponse object that indicates success or failure (see notes below).

Raises:
  • SpotifyWebApiError: If the Spotify Zeroconf API request response contains error information.

The currently logged in user (if any) will be logged out of Spotify Connect, and the device id removed from the active Spotify Connect device list.

This method should not be attempted for devices or services that utilize librespot, such as spotifyd. The librespot library does not implement the resetUsers Spotify Connect Zeroconf endpoint, and will fail with a 404 error.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.zeroconfapi import *

try:

    # create Spotify Zeroconf API connection object for the device.
    zconn:ZeroconfConnect = ZeroconfConnect('192.168.1.81', 8200, '/zc', useSSL=False, tokenStorageDir='./test/testdata')

    # disconnect the device from Spotify Connect.
    print('\nDisconnecting device:%s' % zconn.ToString())
    result:ZeroconfResponse = zconn.Disconnect()
    print('\nResult - %s' % result.ToString())
    print("\nDevice should have been removed from the Spotify Connect device list")

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetEndpointUri(self) -> str:

Gets a Spotify Zeroconf API endpoint uri.

Returns:

A string containing the endpoint uri.

def GetEndpoint(self, action: str) -> str:

Gets a Spotify Zeroconf API endpoint uri.

Arguments:
  • action (str): Action parameter value (e.g. "getInfo", "addUser", "resetUsers", etc).
Returns:

A string containing the endpoint.

Calls the getInfo Spotify Zeroconf API endpoint to return information about the device.

Returns:

A ZeroconfGetInfo object that indicates success or failure (see notes below), as well as the device information.

Raises:
  • SpotifyWebApiError: If the Spotify Zeroconf API request response contains error information.

The request will timeout after 5 seconds and an exception raised if the device cannot be reached or does not respond within that time frame.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.zeroconfapi import *

try:

    # create Spotify Zeroconf API connection object for the device.
    zconn:ZeroconfConnect = ZeroconfConnect('192.168.1.81', 8200, '/zc', useSSL=False, tokenStorageDir='./test/testdata')

    # get Spotify Zeroconf information for the device.
    print('\nGetting Spotify Zeroconf information for device:%s' % zconn.ToString())
    result:ZeroconfGetInfo = zconn.GetInformation()
    print('\nResult - %s' % result.ToString())

except Exception as ex:

    print("** Exception: %s" % str(ex))

def ToString(self, includeTitle: bool = False) -> str:

Returns a displayable string representation of the class.

Arguments:
  • includeTitle (str): True to include the class name title prefix.