Skip to content

Instantly share code, notes, and snippets.

@relevitt
Created June 3, 2016 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save relevitt/967fe48a0fda04c96f296c879b3a24a8 to your computer and use it in GitHub Desktop.
Save relevitt/967fe48a0fda04c96f296c879b3a24a8 to your computer and use it in GitHub Desktop.
A function for adding a sonos playlist to sonos favorites
import xml.etree.ElementTree as ET
def add_sonos_playlist_to_favorites(device, sonos_playlist_id):
'''device: a soco device
e.g. import soco
device = list(soco.discover())[0].group.coordinator
sonos_playlist_id: e.g. 'SQ:1'
'''
didl = '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"><container id="{0}" parentID="SQ:" restricted="true"><dc:title>{1}</dc:title><res protocolInfo="file:*:audio/mpegurl:*">{2}</res><upnp:class>object.container.playlistContainer</upnp:class><r:type>instantPlay</r:type><r:description>Sonos Playlist</r:description><r:resMD>&lt;DIDL-Lite xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot; xmlns:upnp=&quot;urn:schemas-upnp-org:metadata-1-0/upnp/&quot; xmlns:r=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot; xmlns=&quot;urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/&quot;&gt;&lt;item id=&quot;{0}&quot; parentID=&quot;SQ:&quot; restricted=&quot;true&quot;&gt;&lt;dc:title&gt;{1}&lt;/dc:title&gt;&lt;upnp:class&gt;object.container.playlistContainer&lt;/upnp:class&gt;&lt;desc id=&quot;cdudn&quot; nameSpace=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot;&gt;RINCON_AssociatedZPUDN&lt;/desc&gt;&lt;/item&gt;&lt;/DIDL-Lite&gt;</r:resMD>{3}</container></DIDL-Lite>'
title = ''
source = ''
albumArtURI = ''
r = device.contentDirectory.Browse([
('ObjectID', sonos_playlist_id),
('BrowseFlag', 'BrowseMetadata'),
('Filter', '*'),
('StartingIndex', '0'),
('RequestedCount', '0'),
('SortCriteria', '')
])
meta = r['Result']
firstchild = ET.fromstring(meta)[0]
for item in firstchild:
if 'title' in item.tag:
title = item.text
if 'res' in item.tag:
source = item.text
if 'albumArtURI' in item.tag:
albumArtURI += '<upnp:albumArtURI>' + item.text.replace('&', '&amp;') + '</upnp:albumArtURI>'
didl_string = didl.format(sonos_playlist_id, title, source, albumArtURI)
try:
device.contentDirectory.CreateObject([
('ContainerID', 'FV:2'),
('Elements', didl_string)
])
except Exception as e:
print e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment