Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
('ObjectID',
'FV:2' if favorite_type is SONOS_FAVORITES
else 'R:0/{0}'.format(favorite_type)),
('BrowseFlag', 'BrowseDirectChildren'),
('Filter', '*'),
('StartingIndex', start),
('RequestedCount', max_items),
('SortCriteria', '')
])
result = {}
favorites = []
results_xml = response['Result']
if results_xml != '':
# Favorites are returned in DIDL-Lite format
metadata = XML.fromstring(really_utf8(results_xml))
for item in metadata.findall(
'{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}container'
if favorite_type == RADIO_SHOWS else
'{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}item'):
favorite = {}
favorite['title'] = item.findtext(
'{http://purl.org/dc/elements/1.1/}title')
favorite['uri'] = item.findtext(
'{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}res')
if favorite_type == SONOS_FAVORITES:
favorite['meta'] = item.findtext(
'{urn:schemas-rinconnetworks-com:metadata-1-0/}resMD')
favorites.append(favorite)
result['total'] = response['TotalMatches']
_sockets.append(create_socket(address))
except socket.error as e:
_LOG.warning("Can't make a discovery socket for %s: %s: %s",
address, e.__class__.__name__, e)
# Add a socket using the system default address
_sockets.append(create_socket())
# Used to be logged as:
# list(s.getsockname()[0] for s in _sockets)
# but getsockname fails on Windows with unconnected unbound sockets
# https://bugs.python.org/issue1049
_LOG.info("Sending discovery packets on %s", _sockets)
for _ in range(0, 3):
# Send a few times to each socket. UDP is unreliable
for _sock in _sockets:
_sock.sendto(really_utf8(PLAYER_SEARCH), (MCAST_GRP, MCAST_PORT))
t0 = time.time()
while True:
# Check if the timeout is exceeded. We could do this check just
# before the currently only continue statement of this loop,
# but I feel it is safer to do it here, so that we do not forget
# to do it if/when another continue statement is added later.
# Note: this is sensitive to clock adjustments. AFAIK there
# is no monotonic timer available before Python 3.3.
t1 = time.time()
if t1 - t0 > timeout:
return None
# The timeout of the select call is set to be no greater than
# 100ms, so as not to exceed (too much) the required timeout
# in case the loop is executed more than once.
Returns:
Information about the Sonos speaker, such as the UID, MAC Address, and
Zone Name.
"""
if self.speaker_info and refresh is False:
return self.speaker_info
else:
response = requests.get('http://' + self.speaker_ip +
':1400/status/zp')
dom = XML.fromstring(response.content)
if dom.findtext('.//ZoneName') is not None:
self.speaker_info['zone_name'] = \
really_utf8(dom.findtext('.//ZoneName'))
self.speaker_info['zone_icon'] = dom.findtext('.//ZoneIcon')
self.speaker_info['uid'] = dom.findtext('.//LocalUID')
self.speaker_info['serial_number'] = \
dom.findtext('.//SerialNumber')
self.speaker_info['software_version'] = \
dom.findtext('.//SoftwareVersion')
self.speaker_info['hardware_version'] = \
dom.findtext('.//HardwareVersion')
self.speaker_info['mac_address'] = dom.findtext('.//MACAddress')
return self.speaker_info
def queue_size(self):
"""int: Size of the queue."""
response = self.contentDirectory.Browse([
('ObjectID', 'Q:0'),
('BrowseFlag', 'BrowseMetadata'),
('Filter', '*'),
('StartingIndex', 0),
('RequestedCount', 1),
('SortCriteria', '')
])
dom = XML.fromstring(really_utf8(response['Result']))
queue_size = None
container = dom.find(
'{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}container')
if container is not None:
child_count = container.get('childCount')
if child_count is not None:
queue_size = int(child_count)
return queue_size
response = self.avTransport.GetPositionInfo([
('InstanceID', 0),
('Channel', 'Master')
])
track = {'title': '', 'artist': '', 'album': '', 'album_art': '',
'position': ''}
track['playlist_position'] = response['Track']
track['duration'] = response['TrackDuration']
track['uri'] = response['TrackURI']
track['position'] = response['RelTime']
metadata = response['TrackMetaData']
# Duration seems to be '0:00:00' when listening to radio
if metadata != '' and track['duration'] == '0:00:00':
metadata = XML.fromstring(really_utf8(metadata))
# Try parse trackinfo
trackinfo = metadata.findtext('.//{urn:schemas-rinconnetworks-com:'
'metadata-1-0/}streamContent')
index = trackinfo.find(' - ')
if index > -1:
track['artist'] = trackinfo[:index]
track['title'] = trackinfo[index + 3:]
else:
LOGGER.warning('Could not handle track info: "%s"', trackinfo)
LOGGER.warning(traceback.format_exc())
track['title'] = really_utf8(trackinfo)
# If the speaker is playing from the line-in source, querying for track
# metadata will return "NOT_IMPLEMENTED".
elif metadata not in ('', 'NOT_IMPLEMENTED', None):
('StartingIndex', start),
('RequestedCount', max_items),
('SortCriteria', '')
])
result = {}
favorites = []
results_xml = response['Result']
if results_xml != '':
# Favorites are returned in DIDL-Lite format
metadata = XML.fromstring(really_utf8(results_xml))
for item in metadata.findall(
'.//{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}item'):
favorite = {}
favorite['title'] = really_utf8(item.findtext(
'.//{http://purl.org/dc/elements/1.1/}title'))
favorite['uri'] = item.findtext(
'.//{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}res')
favorites.append(favorite)
result['total'] = response['TotalMatches']
result['returned'] = len(favorites)
result['favorites'] = favorites
return result
search_translation = {'artists': 'A:ARTIST',
'album_artists': 'A:ALBUMARTIST',
'albums': 'A:ALBUM', 'genres': 'A:GENRE',
'composers': 'A:COMPOSER', 'tracks': 'A:TRACKS',
'playlists': 'A:PLAYLISTS', 'share': 'S:'}
search = search_translation[search_type]
response = self.contentDirectory.Browse([
('ObjectID', search),
('BrowseFlag', 'BrowseDirectChildren'),
('Filter', '*'),
('StartingIndex', start),
('RequestedCount', max_items),
('SortCriteria', '')
])
dom = XML.fromstring(really_utf8(response['Result']))
# Get result information
out = {'item_list': [], 'search_type': search_type}
for tag in ['NumberReturned', 'TotalMatches', 'UpdateID']:
out[camel_to_underscore(tag)] = int(response[tag])
# Parse the results
#result_xml = XML.fromstring(really_utf8(dom.findtext('.//Result')))
for container in dom:
item = get_ml_item(container)
# Append the item to the list
out['item_list'].append(item)
return out
elif metadata not in ('', 'NOT_IMPLEMENTED', None):
# Track metadata is returned in DIDL-Lite format
metadata = XML.fromstring(really_utf8(metadata))
md_title = metadata.findtext(
'.//{http://purl.org/dc/elements/1.1/}title')
md_artist = metadata.findtext(
'.//{http://purl.org/dc/elements/1.1/}creator')
md_album = metadata.findtext(
'.//{urn:schemas-upnp-org:metadata-1-0/upnp/}album')
track['title'] = ""
if (md_title):
track['title'] = really_utf8(md_title)
track['artist'] = ""
if (md_artist):
track['artist'] = really_utf8(md_artist)
track['album'] = ""
if (md_album):
track['album'] = really_utf8(md_album)
album_art = metadata.findtext(
'.//{urn:schemas-upnp-org:metadata-1-0/upnp/}albumArtURI')
if album_art is not None:
url = metadata.findtext(
'.//{urn:schemas-upnp-org:metadata-1-0/upnp/}albumArtURI')
if url.startswith(('http:', 'https:')):
track['album_art'] = url
else:
track['album_art'] = 'http://' + self.speaker_ip + ':1400'\
+ url
return track