repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
SoCo/SoCo
soco/plugins/wimp.py
Wimp.get_music_service_information
def get_music_service_information(self, search_type, search, start=0, max_items=100): """Search for music service information items. :param search_type: The type of search to perform, possible values are: 'artists', 'albums', 'tracks' and 'playlists' :type search_type: str :param search: The search string to use :type search: str :param start: The starting index of the returned items :type start: int :param max_items: The maximum number of returned items :type max_items: int Note: Un-intuitively the playlist search returns MSAlbumList items. See note in class doc string for details. """ # Check input if search_type not in ['artists', 'albums', 'tracks', 'playlists']: message = 'The requested search {} is not valid'\ .format(search_type) raise ValueError(message) # Transform search: tracks -> tracksearch search_type = '{}earch'.format(search_type) parent_id = SEARCH_PREFIX.format(search_type=search_type, search=search) # Perform search body = self._search_body(search_type, search, start, max_items) headers = _get_header('search') response = _post(self._url, headers, body, **self._http_vars) self._check_for_errors(response) result_dom = XML.fromstring(response.text.encode('utf-8')) # Parse results search_result = result_dom.find('.//' + _ns_tag('', 'searchResult')) out = {'item_list': []} for element in ['index', 'count', 'total']: out[element] = search_result.findtext(_ns_tag('', element)) if search_type == 'tracksearch': item_name = 'mediaMetadata' else: item_name = 'mediaCollection' for element in search_result.findall(_ns_tag('', item_name)): out['item_list'].append(get_ms_item(element, self, parent_id)) return out
python
def get_music_service_information(self, search_type, search, start=0, max_items=100): """Search for music service information items. :param search_type: The type of search to perform, possible values are: 'artists', 'albums', 'tracks' and 'playlists' :type search_type: str :param search: The search string to use :type search: str :param start: The starting index of the returned items :type start: int :param max_items: The maximum number of returned items :type max_items: int Note: Un-intuitively the playlist search returns MSAlbumList items. See note in class doc string for details. """ # Check input if search_type not in ['artists', 'albums', 'tracks', 'playlists']: message = 'The requested search {} is not valid'\ .format(search_type) raise ValueError(message) # Transform search: tracks -> tracksearch search_type = '{}earch'.format(search_type) parent_id = SEARCH_PREFIX.format(search_type=search_type, search=search) # Perform search body = self._search_body(search_type, search, start, max_items) headers = _get_header('search') response = _post(self._url, headers, body, **self._http_vars) self._check_for_errors(response) result_dom = XML.fromstring(response.text.encode('utf-8')) # Parse results search_result = result_dom.find('.//' + _ns_tag('', 'searchResult')) out = {'item_list': []} for element in ['index', 'count', 'total']: out[element] = search_result.findtext(_ns_tag('', element)) if search_type == 'tracksearch': item_name = 'mediaMetadata' else: item_name = 'mediaCollection' for element in search_result.findall(_ns_tag('', item_name)): out['item_list'].append(get_ms_item(element, self, parent_id)) return out
[ "def", "get_music_service_information", "(", "self", ",", "search_type", ",", "search", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "# Check input", "if", "search_type", "not", "in", "[", "'artists'", ",", "'albums'", ",", "'tracks'", ","...
Search for music service information items. :param search_type: The type of search to perform, possible values are: 'artists', 'albums', 'tracks' and 'playlists' :type search_type: str :param search: The search string to use :type search: str :param start: The starting index of the returned items :type start: int :param max_items: The maximum number of returned items :type max_items: int Note: Un-intuitively the playlist search returns MSAlbumList items. See note in class doc string for details.
[ "Search", "for", "music", "service", "information", "items", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L229-L277
train
214,700
SoCo/SoCo
soco/plugins/wimp.py
Wimp.browse
def browse(self, ms_item=None): """Return the sub-elements of item or of the root if item is None :param item: Instance of sub-class of :py:class:`soco.data_structures.MusicServiceItem`. This object must have item_id, service_id and extended_id properties Note: Browsing a MSTrack item will return itself. Note: This plugin cannot yet set the parent ID of the results correctly when browsing :py:class:`soco.data_structures.MSFavorites` and :py:class:`soco.data_structures.MSCollection` elements. """ # Check for correct service if ms_item is not None and ms_item.service_id != self._service_id: message = 'This music service item is not for this service' raise ValueError(message) # Form HTTP body and set parent_id if ms_item: body = self._browse_body(ms_item.item_id) parent_id = ms_item.extended_id if parent_id is None: parent_id = '' else: body = self._browse_body('root') parent_id = '0' # Get HTTP header and post headers = _get_header('get_metadata') response = _post(self._url, headers, body, **self._http_vars) # Check for errors and get XML self._check_for_errors(response) result_dom = XML.fromstring(really_utf8(response.text)) # Find the getMetadataResult item ... xpath_search = './/' + _ns_tag('', 'getMetadataResult') metadata_result = list(result_dom.findall(xpath_search)) # ... and make sure there is exactly 1 if len(metadata_result) != 1: raise UnknownXMLStructure( 'The results XML has more than 1 \'getMetadataResult\'. This ' 'is unexpected and parsing will dis-continue.' ) metadata_result = metadata_result[0] # Browse the children of metadata result out = {'item_list': []} for element in ['index', 'count', 'total']: out[element] = metadata_result.findtext(_ns_tag('', element)) for result in metadata_result: if result.tag in [_ns_tag('', 'mediaCollection'), _ns_tag('', 'mediaMetadata')]: out['item_list'].append(get_ms_item(result, self, parent_id)) return out
python
def browse(self, ms_item=None): """Return the sub-elements of item or of the root if item is None :param item: Instance of sub-class of :py:class:`soco.data_structures.MusicServiceItem`. This object must have item_id, service_id and extended_id properties Note: Browsing a MSTrack item will return itself. Note: This plugin cannot yet set the parent ID of the results correctly when browsing :py:class:`soco.data_structures.MSFavorites` and :py:class:`soco.data_structures.MSCollection` elements. """ # Check for correct service if ms_item is not None and ms_item.service_id != self._service_id: message = 'This music service item is not for this service' raise ValueError(message) # Form HTTP body and set parent_id if ms_item: body = self._browse_body(ms_item.item_id) parent_id = ms_item.extended_id if parent_id is None: parent_id = '' else: body = self._browse_body('root') parent_id = '0' # Get HTTP header and post headers = _get_header('get_metadata') response = _post(self._url, headers, body, **self._http_vars) # Check for errors and get XML self._check_for_errors(response) result_dom = XML.fromstring(really_utf8(response.text)) # Find the getMetadataResult item ... xpath_search = './/' + _ns_tag('', 'getMetadataResult') metadata_result = list(result_dom.findall(xpath_search)) # ... and make sure there is exactly 1 if len(metadata_result) != 1: raise UnknownXMLStructure( 'The results XML has more than 1 \'getMetadataResult\'. This ' 'is unexpected and parsing will dis-continue.' ) metadata_result = metadata_result[0] # Browse the children of metadata result out = {'item_list': []} for element in ['index', 'count', 'total']: out[element] = metadata_result.findtext(_ns_tag('', element)) for result in metadata_result: if result.tag in [_ns_tag('', 'mediaCollection'), _ns_tag('', 'mediaMetadata')]: out['item_list'].append(get_ms_item(result, self, parent_id)) return out
[ "def", "browse", "(", "self", ",", "ms_item", "=", "None", ")", ":", "# Check for correct service", "if", "ms_item", "is", "not", "None", "and", "ms_item", ".", "service_id", "!=", "self", ".", "_service_id", ":", "message", "=", "'This music service item is not...
Return the sub-elements of item or of the root if item is None :param item: Instance of sub-class of :py:class:`soco.data_structures.MusicServiceItem`. This object must have item_id, service_id and extended_id properties Note: Browsing a MSTrack item will return itself. Note: This plugin cannot yet set the parent ID of the results correctly when browsing :py:class:`soco.data_structures.MSFavorites` and :py:class:`soco.data_structures.MSCollection` elements.
[ "Return", "the", "sub", "-", "elements", "of", "item", "or", "of", "the", "root", "if", "item", "is", "None" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L279-L337
train
214,701
SoCo/SoCo
soco/plugins/wimp.py
Wimp.id_to_extended_id
def id_to_extended_id(item_id, item_class): """Return the extended ID from an ID. :param item_id: The ID of the music library item :type item_id: str :param cls: The class of the music service item :type cls: Sub-class of :py:class:`soco.data_structures.MusicServiceItem` The extended id can be something like 00030020trackid_22757082 where the id is just trackid_22757082. For classes where the prefix is not known returns None. """ out = ID_PREFIX[item_class] if out: out += item_id return out
python
def id_to_extended_id(item_id, item_class): """Return the extended ID from an ID. :param item_id: The ID of the music library item :type item_id: str :param cls: The class of the music service item :type cls: Sub-class of :py:class:`soco.data_structures.MusicServiceItem` The extended id can be something like 00030020trackid_22757082 where the id is just trackid_22757082. For classes where the prefix is not known returns None. """ out = ID_PREFIX[item_class] if out: out += item_id return out
[ "def", "id_to_extended_id", "(", "item_id", ",", "item_class", ")", ":", "out", "=", "ID_PREFIX", "[", "item_class", "]", "if", "out", ":", "out", "+=", "item_id", "return", "out" ]
Return the extended ID from an ID. :param item_id: The ID of the music library item :type item_id: str :param cls: The class of the music service item :type cls: Sub-class of :py:class:`soco.data_structures.MusicServiceItem` The extended id can be something like 00030020trackid_22757082 where the id is just trackid_22757082. For classes where the prefix is not known returns None.
[ "Return", "the", "extended", "ID", "from", "an", "ID", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L340-L356
train
214,702
SoCo/SoCo
soco/plugins/wimp.py
Wimp.form_uri
def form_uri(item_content, item_class): """Form the URI for a music service element. :param item_content: The content dict of the item :type item_content: dict :param item_class: The class of the item :type item_class: Sub-class of :py:class:`soco.data_structures.MusicServiceItem` """ extension = None if 'mime_type' in item_content: extension = MIME_TYPE_TO_EXTENSION[item_content['mime_type']] out = URIS.get(item_class) if out: out = out.format(extension=extension, **item_content) return out
python
def form_uri(item_content, item_class): """Form the URI for a music service element. :param item_content: The content dict of the item :type item_content: dict :param item_class: The class of the item :type item_class: Sub-class of :py:class:`soco.data_structures.MusicServiceItem` """ extension = None if 'mime_type' in item_content: extension = MIME_TYPE_TO_EXTENSION[item_content['mime_type']] out = URIS.get(item_class) if out: out = out.format(extension=extension, **item_content) return out
[ "def", "form_uri", "(", "item_content", ",", "item_class", ")", ":", "extension", "=", "None", "if", "'mime_type'", "in", "item_content", ":", "extension", "=", "MIME_TYPE_TO_EXTENSION", "[", "item_content", "[", "'mime_type'", "]", "]", "out", "=", "URIS", "....
Form the URI for a music service element. :param item_content: The content dict of the item :type item_content: dict :param item_class: The class of the item :type item_class: Sub-class of :py:class:`soco.data_structures.MusicServiceItem`
[ "Form", "the", "URI", "for", "a", "music", "service", "element", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L359-L374
train
214,703
SoCo/SoCo
soco/plugins/wimp.py
Wimp._search_body
def _search_body(self, search_type, search_term, start, max_items): """Return the search XML body. :param search_type: The search type :type search_type: str :param search_term: The search term e.g. 'Jon Bon Jovi' :type search_term: str :param start: The start index of the returned results :type start: int :param max_items: The maximum number of returned results :type max_items: int The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <search xmlns="http://www.sonos.com/Services/1.1"> <id>search_type</id> <term>search_term</term> <index>start</index> <count>max_items</count> </search> </s:Body> """ xml = self._base_body() # Add the Body part XML.SubElement(xml, 's:Body') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } search = XML.SubElement(xml[1], 'search', item_attrib) XML.SubElement(search, 'id').text = search_type XML.SubElement(search, 'term').text = search_term XML.SubElement(search, 'index').text = str(start) XML.SubElement(search, 'count').text = str(max_items) return XML.tostring(xml)
python
def _search_body(self, search_type, search_term, start, max_items): """Return the search XML body. :param search_type: The search type :type search_type: str :param search_term: The search term e.g. 'Jon Bon Jovi' :type search_term: str :param start: The start index of the returned results :type start: int :param max_items: The maximum number of returned results :type max_items: int The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <search xmlns="http://www.sonos.com/Services/1.1"> <id>search_type</id> <term>search_term</term> <index>start</index> <count>max_items</count> </search> </s:Body> """ xml = self._base_body() # Add the Body part XML.SubElement(xml, 's:Body') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } search = XML.SubElement(xml[1], 'search', item_attrib) XML.SubElement(search, 'id').text = search_type XML.SubElement(search, 'term').text = search_term XML.SubElement(search, 'index').text = str(start) XML.SubElement(search, 'count').text = str(max_items) return XML.tostring(xml)
[ "def", "_search_body", "(", "self", ",", "search_type", ",", "search_term", ",", "start", ",", "max_items", ")", ":", "xml", "=", "self", ".", "_base_body", "(", ")", "# Add the Body part", "XML", ".", "SubElement", "(", "xml", ",", "'s:Body'", ")", "item_...
Return the search XML body. :param search_type: The search type :type search_type: str :param search_term: The search term e.g. 'Jon Bon Jovi' :type search_term: str :param start: The start index of the returned results :type start: int :param max_items: The maximum number of returned results :type max_items: int The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <search xmlns="http://www.sonos.com/Services/1.1"> <id>search_type</id> <term>search_term</term> <index>start</index> <count>max_items</count> </search> </s:Body>
[ "Return", "the", "search", "XML", "body", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L376-L415
train
214,704
SoCo/SoCo
soco/plugins/wimp.py
Wimp._browse_body
def _browse_body(self, search_id): """Return the browse XML body. The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <getMetadata xmlns="http://www.sonos.com/Services/1.1"> <id>root</id> <index>0</index> <count>100</count> </getMetadata> </s:Body> .. note:: The XML contains index and count, but the service does not seem to respect them, so therefore they have not been included as arguments. """ xml = self._base_body() # Add the Body part XML.SubElement(xml, 's:Body') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } search = XML.SubElement(xml[1], 'getMetadata', item_attrib) XML.SubElement(search, 'id').text = search_id # Investigate this index, count stuff more XML.SubElement(search, 'index').text = '0' XML.SubElement(search, 'count').text = '100' return XML.tostring(xml)
python
def _browse_body(self, search_id): """Return the browse XML body. The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <getMetadata xmlns="http://www.sonos.com/Services/1.1"> <id>root</id> <index>0</index> <count>100</count> </getMetadata> </s:Body> .. note:: The XML contains index and count, but the service does not seem to respect them, so therefore they have not been included as arguments. """ xml = self._base_body() # Add the Body part XML.SubElement(xml, 's:Body') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } search = XML.SubElement(xml[1], 'getMetadata', item_attrib) XML.SubElement(search, 'id').text = search_id # Investigate this index, count stuff more XML.SubElement(search, 'index').text = '0' XML.SubElement(search, 'count').text = '100' return XML.tostring(xml)
[ "def", "_browse_body", "(", "self", ",", "search_id", ")", ":", "xml", "=", "self", ".", "_base_body", "(", ")", "# Add the Body part", "XML", ".", "SubElement", "(", "xml", ",", "'s:Body'", ")", "item_attrib", "=", "{", "'xmlns'", ":", "'http://www.sonos.co...
Return the browse XML body. The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <getMetadata xmlns="http://www.sonos.com/Services/1.1"> <id>root</id> <index>0</index> <count>100</count> </getMetadata> </s:Body> .. note:: The XML contains index and count, but the service does not seem to respect them, so therefore they have not been included as arguments.
[ "Return", "the", "browse", "XML", "body", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L417-L450
train
214,705
SoCo/SoCo
soco/plugins/wimp.py
Wimp._check_for_errors
def _check_for_errors(self, response): """Check a response for errors. :param response: the response from requests.post() """ if response.status_code != 200: xml_error = really_utf8(response.text) error_dom = XML.fromstring(xml_error) fault = error_dom.find('.//' + _ns_tag('s', 'Fault')) error_description = fault.find('faultstring').text error_code = EXCEPTION_STR_TO_CODE[error_description] message = 'UPnP Error {} received: {} from {}'.format( error_code, error_description, self._url) raise SoCoUPnPException( message=message, error_code=error_code, error_description=error_description, error_xml=really_utf8(response.text) )
python
def _check_for_errors(self, response): """Check a response for errors. :param response: the response from requests.post() """ if response.status_code != 200: xml_error = really_utf8(response.text) error_dom = XML.fromstring(xml_error) fault = error_dom.find('.//' + _ns_tag('s', 'Fault')) error_description = fault.find('faultstring').text error_code = EXCEPTION_STR_TO_CODE[error_description] message = 'UPnP Error {} received: {} from {}'.format( error_code, error_description, self._url) raise SoCoUPnPException( message=message, error_code=error_code, error_description=error_description, error_xml=really_utf8(response.text) )
[ "def", "_check_for_errors", "(", "self", ",", "response", ")", ":", "if", "response", ".", "status_code", "!=", "200", ":", "xml_error", "=", "really_utf8", "(", "response", ".", "text", ")", "error_dom", "=", "XML", ".", "fromstring", "(", "xml_error", ")...
Check a response for errors. :param response: the response from requests.post()
[ "Check", "a", "response", "for", "errors", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L484-L502
train
214,706
SoCo/SoCo
soco/music_services/music_service.py
desc_from_uri
def desc_from_uri(uri): """Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'`` """ # # If there is an sn parameter (which is the serial number of an account), # we can obtain all the information we need from that, because we can find # the relevant service_id in the account database (it is the same as the # service_type). Consequently, the sid parameter is unneeded. But if sn is # missing, we need the sid (service_type) parameter to find a relevant # account # urlparse does not work consistently with custom URI schemes such as # those used by Sonos. This is especially broken in Python 2.6 and # early versions of 2.7: http://bugs.python.org/issue9374 # As a workaround, we split off the scheme manually, and then parse # the uri as if it were http if ":" in uri: _, uri = uri.split(":", 1) query_string = parse_qs(urlparse(uri, 'http').query) # Is there an account serial number? if query_string.get('sn'): account_serial_number = query_string['sn'][0] try: account = Account.get_accounts()[account_serial_number] desc = "SA_RINCON{}_{}".format( account.service_type, account.username) return desc except KeyError: # There is no account matching this serial number. Fall back to # using the service id to find an account pass if query_string.get('sid'): service_id = query_string['sid'][0] for service in MusicService._get_music_services_data().values(): if service_id == service["ServiceID"]: service_type = service["ServiceType"] account = Account.get_accounts_for_service(service_type) if not account: break # Use the first account we find account = account[0] desc = "SA_RINCON{}_{}".format( account.service_type, account.username) return desc # Nothing found. Default to the standard desc value. Is this the right # thing to do? desc = 'RINCON_AssociatedZPUDN' return desc
python
def desc_from_uri(uri): """Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'`` """ # # If there is an sn parameter (which is the serial number of an account), # we can obtain all the information we need from that, because we can find # the relevant service_id in the account database (it is the same as the # service_type). Consequently, the sid parameter is unneeded. But if sn is # missing, we need the sid (service_type) parameter to find a relevant # account # urlparse does not work consistently with custom URI schemes such as # those used by Sonos. This is especially broken in Python 2.6 and # early versions of 2.7: http://bugs.python.org/issue9374 # As a workaround, we split off the scheme manually, and then parse # the uri as if it were http if ":" in uri: _, uri = uri.split(":", 1) query_string = parse_qs(urlparse(uri, 'http').query) # Is there an account serial number? if query_string.get('sn'): account_serial_number = query_string['sn'][0] try: account = Account.get_accounts()[account_serial_number] desc = "SA_RINCON{}_{}".format( account.service_type, account.username) return desc except KeyError: # There is no account matching this serial number. Fall back to # using the service id to find an account pass if query_string.get('sid'): service_id = query_string['sid'][0] for service in MusicService._get_music_services_data().values(): if service_id == service["ServiceID"]: service_type = service["ServiceType"] account = Account.get_accounts_for_service(service_type) if not account: break # Use the first account we find account = account[0] desc = "SA_RINCON{}_{}".format( account.service_type, account.username) return desc # Nothing found. Default to the standard desc value. Is this the right # thing to do? desc = 'RINCON_AssociatedZPUDN' return desc
[ "def", "desc_from_uri", "(", "uri", ")", ":", "#", "# If there is an sn parameter (which is the serial number of an account),", "# we can obtain all the information we need from that, because we can find", "# the relevant service_id in the account database (it is the same as the", "# service_typ...
Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'``
[ "Create", "the", "content", "of", "DIDL", "desc", "element", "from", "a", "uri", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L824-L879
train
214,707
SoCo/SoCo
soco/music_services/music_service.py
MusicServiceSoapClient.get_soap_header
def get_soap_header(self): """Generate the SOAP authentication header for the related service. This header contains all the necessary authentication details. Returns: str: A string representation of the XML content of the SOAP header. """ # According to the SONOS SMAPI, this header must be sent with all # SOAP requests. Building this is an expensive operation (though # occasionally necessary), so f we have a cached value, return it if self._cached_soap_header is not None: return self._cached_soap_header music_service = self.music_service credentials_header = XML.Element( "credentials", {'xmlns': "http://www.sonos.com/Services/1.1"}) device_id = XML.SubElement(credentials_header, 'deviceId') device_id.text = self._device_id device_provider = XML.SubElement(credentials_header, 'deviceProvider') device_provider.text = 'Sonos' if music_service.account.oa_device_id: # OAuth account credentials are present. We must use them to # authenticate. login_token = XML.Element('loginToken') token = XML.SubElement(login_token, 'token') token.text = music_service.account.oa_device_id key = XML.SubElement(login_token, 'key') key.text = music_service.account.key household_id = XML.SubElement(login_token, 'householdId') household_id.text = self._device.household_id credentials_header.append(login_token) # otherwise, perhaps use DeviceLink or UserId auth elif music_service.auth_type in ['DeviceLink', 'UserId']: # We need a session ID from Sonos session_id = self._device.musicServices.GetSessionId([ ('ServiceId', music_service.service_id), ('Username', music_service.account.username) ])['SessionId'] session_elt = XML.Element('sessionId') session_elt.text = session_id credentials_header.append(session_elt) # Anonymous auth. No need for anything further. self._cached_soap_header = XML.tostring( credentials_header, encoding='utf-8').decode(encoding='utf-8') return self._cached_soap_header
python
def get_soap_header(self): """Generate the SOAP authentication header for the related service. This header contains all the necessary authentication details. Returns: str: A string representation of the XML content of the SOAP header. """ # According to the SONOS SMAPI, this header must be sent with all # SOAP requests. Building this is an expensive operation (though # occasionally necessary), so f we have a cached value, return it if self._cached_soap_header is not None: return self._cached_soap_header music_service = self.music_service credentials_header = XML.Element( "credentials", {'xmlns': "http://www.sonos.com/Services/1.1"}) device_id = XML.SubElement(credentials_header, 'deviceId') device_id.text = self._device_id device_provider = XML.SubElement(credentials_header, 'deviceProvider') device_provider.text = 'Sonos' if music_service.account.oa_device_id: # OAuth account credentials are present. We must use them to # authenticate. login_token = XML.Element('loginToken') token = XML.SubElement(login_token, 'token') token.text = music_service.account.oa_device_id key = XML.SubElement(login_token, 'key') key.text = music_service.account.key household_id = XML.SubElement(login_token, 'householdId') household_id.text = self._device.household_id credentials_header.append(login_token) # otherwise, perhaps use DeviceLink or UserId auth elif music_service.auth_type in ['DeviceLink', 'UserId']: # We need a session ID from Sonos session_id = self._device.musicServices.GetSessionId([ ('ServiceId', music_service.service_id), ('Username', music_service.account.username) ])['SessionId'] session_elt = XML.Element('sessionId') session_elt.text = session_id credentials_header.append(session_elt) # Anonymous auth. No need for anything further. self._cached_soap_header = XML.tostring( credentials_header, encoding='utf-8').decode(encoding='utf-8') return self._cached_soap_header
[ "def", "get_soap_header", "(", "self", ")", ":", "# According to the SONOS SMAPI, this header must be sent with all", "# SOAP requests. Building this is an expensive operation (though", "# occasionally necessary), so f we have a cached value, return it", "if", "self", ".", "_cached_soap_head...
Generate the SOAP authentication header for the related service. This header contains all the necessary authentication details. Returns: str: A string representation of the XML content of the SOAP header.
[ "Generate", "the", "SOAP", "authentication", "header", "for", "the", "related", "service", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L76-L125
train
214,708
SoCo/SoCo
soco/music_services/music_service.py
MusicServiceSoapClient.call
def call(self, method, args=None): """Call a method on the server. Args: 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: ~collections.OrderedDict: An OrderedDict representing the response. Raises: `MusicServiceException`: containing details of the error returned by the music service. """ message = SoapMessage( endpoint=self.endpoint, method=method, parameters=[] if args is None else args, http_headers=self.http_headers, soap_action="http://www.sonos.com/Services/1" ".1#{0}".format(method), soap_header=self.get_soap_header(), namespace=self.namespace, timeout=self.timeout) try: result_elt = message.call() except SoapFault as exc: if 'Client.TokenRefreshRequired' in exc.faultcode: log.debug('Token refresh required. Trying again') # Remove any cached value for the SOAP header self._cached_soap_header = None # <detail> # <refreshAuthTokenResult> # <authToken>xxxxxxx</authToken> # <privateKey>zzzzzz</privateKey> # </refreshAuthTokenResult> # </detail> auth_token = exc.detail.findtext('.//authToken') private_key = exc.detail.findtext('.//privateKey') # We have new details - update the account self.music_service.account.oa_device_id = auth_token self.music_service.account.key = private_key message = SoapMessage( endpoint=self.endpoint, method=method, parameters=args, http_headers=self.http_headers, soap_action="http://www.sonos.com/Services/1" ".1#{0}".format(method), soap_header=self.get_soap_header(), namespace=self.namespace, timeout=self.timeout) result_elt = message.call() else: raise MusicServiceException(exc.faultstring, exc.faultcode) # The top key in the OrderedDict will be the methodResult. Its # value may be None if no results were returned. result = list(parse( XML.tostring(result_elt), process_namespaces=True, namespaces={'http://www.sonos.com/Services/1.1': None} ).values())[0] return result if result is not None else {}
python
def call(self, method, args=None): """Call a method on the server. Args: 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: ~collections.OrderedDict: An OrderedDict representing the response. Raises: `MusicServiceException`: containing details of the error returned by the music service. """ message = SoapMessage( endpoint=self.endpoint, method=method, parameters=[] if args is None else args, http_headers=self.http_headers, soap_action="http://www.sonos.com/Services/1" ".1#{0}".format(method), soap_header=self.get_soap_header(), namespace=self.namespace, timeout=self.timeout) try: result_elt = message.call() except SoapFault as exc: if 'Client.TokenRefreshRequired' in exc.faultcode: log.debug('Token refresh required. Trying again') # Remove any cached value for the SOAP header self._cached_soap_header = None # <detail> # <refreshAuthTokenResult> # <authToken>xxxxxxx</authToken> # <privateKey>zzzzzz</privateKey> # </refreshAuthTokenResult> # </detail> auth_token = exc.detail.findtext('.//authToken') private_key = exc.detail.findtext('.//privateKey') # We have new details - update the account self.music_service.account.oa_device_id = auth_token self.music_service.account.key = private_key message = SoapMessage( endpoint=self.endpoint, method=method, parameters=args, http_headers=self.http_headers, soap_action="http://www.sonos.com/Services/1" ".1#{0}".format(method), soap_header=self.get_soap_header(), namespace=self.namespace, timeout=self.timeout) result_elt = message.call() else: raise MusicServiceException(exc.faultstring, exc.faultcode) # The top key in the OrderedDict will be the methodResult. Its # value may be None if no results were returned. result = list(parse( XML.tostring(result_elt), process_namespaces=True, namespaces={'http://www.sonos.com/Services/1.1': None} ).values())[0] return result if result is not None else {}
[ "def", "call", "(", "self", ",", "method", ",", "args", "=", "None", ")", ":", "message", "=", "SoapMessage", "(", "endpoint", "=", "self", ".", "endpoint", ",", "method", "=", "method", ",", "parameters", "=", "[", "]", "if", "args", "is", "None", ...
Call a method on the server. Args: 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: ~collections.OrderedDict: An OrderedDict representing the response. Raises: `MusicServiceException`: containing details of the error returned by the music service.
[ "Call", "a", "method", "on", "the", "server", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L127-L195
train
214,709
SoCo/SoCo
soco/music_services/music_service.py
MusicService._get_music_services_data_xml
def _get_music_services_data_xml(soco=None): """Fetch the music services data xml from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If none is specified, a random device will be used. Defaults to `None`. Returns: str: a string containing the music services data xml """ device = soco or discovery.any_soco() log.debug("Fetching music services data from %s", device) available_services = device.musicServices.ListAvailableServices() descriptor_list_xml = available_services[ 'AvailableServiceDescriptorList'] log.debug("Services descriptor list: %s", descriptor_list_xml) return descriptor_list_xml
python
def _get_music_services_data_xml(soco=None): """Fetch the music services data xml from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If none is specified, a random device will be used. Defaults to `None`. Returns: str: a string containing the music services data xml """ device = soco or discovery.any_soco() log.debug("Fetching music services data from %s", device) available_services = device.musicServices.ListAvailableServices() descriptor_list_xml = available_services[ 'AvailableServiceDescriptorList'] log.debug("Services descriptor list: %s", descriptor_list_xml) return descriptor_list_xml
[ "def", "_get_music_services_data_xml", "(", "soco", "=", "None", ")", ":", "device", "=", "soco", "or", "discovery", ".", "any_soco", "(", ")", "log", ".", "debug", "(", "\"Fetching music services data from %s\"", ",", "device", ")", "available_services", "=", "...
Fetch the music services data xml from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If none is specified, a random device will be used. Defaults to `None`. Returns: str: a string containing the music services data xml
[ "Fetch", "the", "music", "services", "data", "xml", "from", "a", "Sonos", "device", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L371-L387
train
214,710
SoCo/SoCo
soco/music_services/music_service.py
MusicService._get_music_services_data
def _get_music_services_data(cls): """Parse raw account data xml into a useful python datastructure. Returns: dict: Each key is a service_type, and each value is a `dict` containing relevant data. """ # Return from cache if we have it. if cls._music_services_data is not None: return cls._music_services_data result = {} root = XML.fromstring( cls._get_music_services_data_xml().encode('utf-8') ) # <Services SchemaVersion="1"> # <Service Id="163" Name="Spreaker" Version="1.1" # Uri="http://sonos.spreaker.com/sonos/service/v1" # SecureUri="https://sonos.spreaker.com/sonos/service/v1" # ContainerType="MService" # Capabilities="513" # MaxMessagingChars="0"> # <Policy Auth="Anonymous" PollInterval="30" /> # <Presentation> # <Strings # Version="1" # Uri="https:...string_table.xml" /> # <PresentationMap Version="2" # Uri="https://...presentation_map.xml" /> # </Presentation> # </Service> # ... # </ Services> # Ideally, the search path should be './/Service' to find Service # elements at any level, but Python 2.6 breaks with this if Service # is a child of the current element. Since 'Service' works here, we use # that instead services = root.findall('Service') for service in services: result_value = service.attrib.copy() name = service.get('Name') result_value['Name'] = name auth_element = (service.find('Policy')) auth = auth_element.attrib result_value.update(auth) presentation_element = (service.find('.//PresentationMap')) if presentation_element is not None: result_value['PresentationMapUri'] = \ presentation_element.get('Uri') result_value['ServiceID'] = service.get('Id') # ServiceType is used elsewhere in Sonos, eg to form tokens, # and get_subscribed_music_services() below. It is also the # 'Type' used in account_xml (see above). Its value always # seems to be (ID*256) + 7. Some serviceTypes are also # listed in available_services['AvailableServiceTypeList'] # but this does not seem to be comprehensive service_type = str(int(service.get('Id')) * 256 + 7) result_value['ServiceType'] = service_type result[service_type] = result_value # Cache this so we don't need to do it again. cls._music_services_data = result return result
python
def _get_music_services_data(cls): """Parse raw account data xml into a useful python datastructure. Returns: dict: Each key is a service_type, and each value is a `dict` containing relevant data. """ # Return from cache if we have it. if cls._music_services_data is not None: return cls._music_services_data result = {} root = XML.fromstring( cls._get_music_services_data_xml().encode('utf-8') ) # <Services SchemaVersion="1"> # <Service Id="163" Name="Spreaker" Version="1.1" # Uri="http://sonos.spreaker.com/sonos/service/v1" # SecureUri="https://sonos.spreaker.com/sonos/service/v1" # ContainerType="MService" # Capabilities="513" # MaxMessagingChars="0"> # <Policy Auth="Anonymous" PollInterval="30" /> # <Presentation> # <Strings # Version="1" # Uri="https:...string_table.xml" /> # <PresentationMap Version="2" # Uri="https://...presentation_map.xml" /> # </Presentation> # </Service> # ... # </ Services> # Ideally, the search path should be './/Service' to find Service # elements at any level, but Python 2.6 breaks with this if Service # is a child of the current element. Since 'Service' works here, we use # that instead services = root.findall('Service') for service in services: result_value = service.attrib.copy() name = service.get('Name') result_value['Name'] = name auth_element = (service.find('Policy')) auth = auth_element.attrib result_value.update(auth) presentation_element = (service.find('.//PresentationMap')) if presentation_element is not None: result_value['PresentationMapUri'] = \ presentation_element.get('Uri') result_value['ServiceID'] = service.get('Id') # ServiceType is used elsewhere in Sonos, eg to form tokens, # and get_subscribed_music_services() below. It is also the # 'Type' used in account_xml (see above). Its value always # seems to be (ID*256) + 7. Some serviceTypes are also # listed in available_services['AvailableServiceTypeList'] # but this does not seem to be comprehensive service_type = str(int(service.get('Id')) * 256 + 7) result_value['ServiceType'] = service_type result[service_type] = result_value # Cache this so we don't need to do it again. cls._music_services_data = result return result
[ "def", "_get_music_services_data", "(", "cls", ")", ":", "# Return from cache if we have it.", "if", "cls", ".", "_music_services_data", "is", "not", "None", ":", "return", "cls", ".", "_music_services_data", "result", "=", "{", "}", "root", "=", "XML", ".", "fr...
Parse raw account data xml into a useful python datastructure. Returns: dict: Each key is a service_type, and each value is a `dict` containing relevant data.
[ "Parse", "raw", "account", "data", "xml", "into", "a", "useful", "python", "datastructure", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L390-L452
train
214,711
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_subscribed_services_names
def get_subscribed_services_names(cls): """Get a list of the names of all subscribed music services. Returns: list: A list of strings. """ # This is very inefficient - loops within loops within loops, and # many network requests # Optimise it? accounts_for_service = Account.get_accounts_for_service service_data = cls._get_music_services_data().values() return [ service['Name'] for service in service_data if len( accounts_for_service(service['ServiceType']) ) > 0 ]
python
def get_subscribed_services_names(cls): """Get a list of the names of all subscribed music services. Returns: list: A list of strings. """ # This is very inefficient - loops within loops within loops, and # many network requests # Optimise it? accounts_for_service = Account.get_accounts_for_service service_data = cls._get_music_services_data().values() return [ service['Name'] for service in service_data if len( accounts_for_service(service['ServiceType']) ) > 0 ]
[ "def", "get_subscribed_services_names", "(", "cls", ")", ":", "# This is very inefficient - loops within loops within loops, and", "# many network requests", "# Optimise it?", "accounts_for_service", "=", "Account", ".", "get_accounts_for_service", "service_data", "=", "cls", ".", ...
Get a list of the names of all subscribed music services. Returns: list: A list of strings.
[ "Get", "a", "list", "of", "the", "names", "of", "all", "subscribed", "music", "services", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L469-L485
train
214,712
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_data_for_name
def get_data_for_name(cls, service_name): """Get the data relating to a named music service. Args: service_name (str): The name of the music service for which data is required. Returns: dict: Data relating to the music service. Raises: `MusicServiceException`: if the music service cannot be found. """ for service in cls._get_music_services_data().values(): if service_name == service["Name"]: return service raise MusicServiceException( "Unknown music service: '%s'" % service_name)
python
def get_data_for_name(cls, service_name): """Get the data relating to a named music service. Args: service_name (str): The name of the music service for which data is required. Returns: dict: Data relating to the music service. Raises: `MusicServiceException`: if the music service cannot be found. """ for service in cls._get_music_services_data().values(): if service_name == service["Name"]: return service raise MusicServiceException( "Unknown music service: '%s'" % service_name)
[ "def", "get_data_for_name", "(", "cls", ",", "service_name", ")", ":", "for", "service", "in", "cls", ".", "_get_music_services_data", "(", ")", ".", "values", "(", ")", ":", "if", "service_name", "==", "service", "[", "\"Name\"", "]", ":", "return", "serv...
Get the data relating to a named music service. Args: service_name (str): The name of the music service for which data is required. Returns: dict: Data relating to the music service. Raises: `MusicServiceException`: if the music service cannot be found.
[ "Get", "the", "data", "relating", "to", "a", "named", "music", "service", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L488-L505
train
214,713
SoCo/SoCo
soco/music_services/music_service.py
MusicService._get_search_prefix_map
def _get_search_prefix_map(self): """Fetch and parse the service search category mapping. Standard Sonos search categories are 'all', 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service """ # TuneIn does not have a pmap. Its search keys are is search:station, # search:show, search:host # Presentation maps can also define custom categories. See eg # http://sonos-pmap.ws.sonos.com/hypemachine_pmap.6.xml # <SearchCategories> # ... # <CustomCategory mappedId="SBLG" stringId="Blogs"/> # </SearchCategories> # Is it already cached? If so, return it if self._search_prefix_map is not None: return self._search_prefix_map # Not cached. Fetch and parse presentation map self._search_prefix_map = {} # Tunein is a special case. It has no pmap, but supports searching if self.service_name == "TuneIn": self._search_prefix_map = { 'stations': 'search:station', 'shows': 'search:show', 'hosts': 'search:host', } return self._search_prefix_map if self.presentation_map_uri is None: # Assume not searchable? return self._search_prefix_map log.info('Fetching presentation map from %s', self.presentation_map_uri) pmap = requests.get(self.presentation_map_uri, timeout=9) pmap_root = XML.fromstring(pmap.content) # Search translations can appear in Category or CustomCategory elements categories = pmap_root.findall(".//SearchCategories/Category") if categories is None: return self._search_prefix_map for cat in categories: self._search_prefix_map[cat.get('id')] = cat.get('mappedId') custom_categories = pmap_root.findall( ".//SearchCategories/CustomCategory") for cat in custom_categories: self._search_prefix_map[cat.get('stringId')] = cat.get('mappedId') return self._search_prefix_map
python
def _get_search_prefix_map(self): """Fetch and parse the service search category mapping. Standard Sonos search categories are 'all', 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service """ # TuneIn does not have a pmap. Its search keys are is search:station, # search:show, search:host # Presentation maps can also define custom categories. See eg # http://sonos-pmap.ws.sonos.com/hypemachine_pmap.6.xml # <SearchCategories> # ... # <CustomCategory mappedId="SBLG" stringId="Blogs"/> # </SearchCategories> # Is it already cached? If so, return it if self._search_prefix_map is not None: return self._search_prefix_map # Not cached. Fetch and parse presentation map self._search_prefix_map = {} # Tunein is a special case. It has no pmap, but supports searching if self.service_name == "TuneIn": self._search_prefix_map = { 'stations': 'search:station', 'shows': 'search:show', 'hosts': 'search:host', } return self._search_prefix_map if self.presentation_map_uri is None: # Assume not searchable? return self._search_prefix_map log.info('Fetching presentation map from %s', self.presentation_map_uri) pmap = requests.get(self.presentation_map_uri, timeout=9) pmap_root = XML.fromstring(pmap.content) # Search translations can appear in Category or CustomCategory elements categories = pmap_root.findall(".//SearchCategories/Category") if categories is None: return self._search_prefix_map for cat in categories: self._search_prefix_map[cat.get('id')] = cat.get('mappedId') custom_categories = pmap_root.findall( ".//SearchCategories/CustomCategory") for cat in custom_categories: self._search_prefix_map[cat.get('stringId')] = cat.get('mappedId') return self._search_prefix_map
[ "def", "_get_search_prefix_map", "(", "self", ")", ":", "# TuneIn does not have a pmap. Its search keys are is search:station,", "# search:show, search:host", "# Presentation maps can also define custom categories. See eg", "# http://sonos-pmap.ws.sonos.com/hypemachine_pmap.6.xml", "# <SearchCat...
Fetch and parse the service search category mapping. Standard Sonos search categories are 'all', 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service
[ "Fetch", "and", "parse", "the", "service", "search", "category", "mapping", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L507-L553
train
214,714
SoCo/SoCo
soco/music_services/music_service.py
MusicService.sonos_uri_from_id
def sonos_uri_from_id(self, item_id): """Get a uri which can be sent for playing. Args: 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: str: 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. """ # Real Sonos URIs look like this: # x-sonos-http:tr%3a92352286.mp3?sid=2&flags=8224&sn=4 The # extension (.mp3) presumably comes from the mime-type returned in a # MusicService.get_metadata() result (though for Spotify the mime-type # is audio/x-spotify, and there is no extension. See # http://musicpartners.sonos.com/node/464 for supported mime-types and # related extensions). The scheme (x-sonos-http) presumably # indicates how the player is to obtain the stream for playing. It # is not clear what the flags param is used for (perhaps bitrate, # or certain metadata such as canSkip?). Fortunately, none of these # seems to be necessary. We can leave them out, (or in the case of # the scheme, use 'soco' as dummy text, and the players still seem # to do the right thing. # quote_url will break if given unicode on Py2.6, and early 2.7. So # we need to encode. item_id = quote_url(item_id.encode('utf-8')) # Add the account info to the end as query params account = self.account result = "soco://{}?sid={}&sn={}".format( item_id, self.service_id, account.serial_number ) return result
python
def sonos_uri_from_id(self, item_id): """Get a uri which can be sent for playing. Args: 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: str: 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. """ # Real Sonos URIs look like this: # x-sonos-http:tr%3a92352286.mp3?sid=2&flags=8224&sn=4 The # extension (.mp3) presumably comes from the mime-type returned in a # MusicService.get_metadata() result (though for Spotify the mime-type # is audio/x-spotify, and there is no extension. See # http://musicpartners.sonos.com/node/464 for supported mime-types and # related extensions). The scheme (x-sonos-http) presumably # indicates how the player is to obtain the stream for playing. It # is not clear what the flags param is used for (perhaps bitrate, # or certain metadata such as canSkip?). Fortunately, none of these # seems to be necessary. We can leave them out, (or in the case of # the scheme, use 'soco' as dummy text, and the players still seem # to do the right thing. # quote_url will break if given unicode on Py2.6, and early 2.7. So # we need to encode. item_id = quote_url(item_id.encode('utf-8')) # Add the account info to the end as query params account = self.account result = "soco://{}?sid={}&sn={}".format( item_id, self.service_id, account.serial_number ) return result
[ "def", "sonos_uri_from_id", "(", "self", ",", "item_id", ")", ":", "# Real Sonos URIs look like this:", "# x-sonos-http:tr%3a92352286.mp3?sid=2&flags=8224&sn=4 The", "# extension (.mp3) presumably comes from the mime-type returned in a", "# MusicService.get_metadata() result (though for Spotif...
Get a uri which can be sent for playing. Args: 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: str: 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.
[ "Get", "a", "uri", "which", "can", "be", "sent", "for", "playing", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L577-L616
train
214,715
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_metadata
def get_metadata( self, item='root', index=0, count=100, recursive=False): """Get metadata for a container or item. Args: 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: ~collections.OrderedDict: The item or container's metadata, or `None`. See also: The Sonos `getMetadata API <http://musicpartners.sonos.com/node/83>`_. """ if isinstance(item, MusicServiceItem): item_id = item.id # pylint: disable=no-member else: item_id = item response = self.soap_client.call( 'getMetadata', [ ('id', item_id), ('index', index), ('count', count), ('recursive', 1 if recursive else 0)] ) return parse_response(self, response, 'browse')
python
def get_metadata( self, item='root', index=0, count=100, recursive=False): """Get metadata for a container or item. Args: 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: ~collections.OrderedDict: The item or container's metadata, or `None`. See also: The Sonos `getMetadata API <http://musicpartners.sonos.com/node/83>`_. """ if isinstance(item, MusicServiceItem): item_id = item.id # pylint: disable=no-member else: item_id = item response = self.soap_client.call( 'getMetadata', [ ('id', item_id), ('index', index), ('count', count), ('recursive', 1 if recursive else 0)] ) return parse_response(self, response, 'browse')
[ "def", "get_metadata", "(", "self", ",", "item", "=", "'root'", ",", "index", "=", "0", ",", "count", "=", "100", ",", "recursive", "=", "False", ")", ":", "if", "isinstance", "(", "item", ",", "MusicServiceItem", ")", ":", "item_id", "=", "item", "....
Get metadata for a container or item. Args: 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: ~collections.OrderedDict: The item or container's metadata, or `None`. See also: The Sonos `getMetadata API <http://musicpartners.sonos.com/node/83>`_.
[ "Get", "metadata", "for", "a", "container", "or", "item", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L661-L693
train
214,716
SoCo/SoCo
soco/music_services/music_service.py
MusicService.search
def search(self, category, term='', index=0, count=100): """Search for an item in a category. Args: 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: ~collections.OrderedDict: The search results, or `None`. See also: The Sonos `search API <http://musicpartners.sonos.com/node/86>`_ """ search_category = self._get_search_prefix_map().get(category, None) if search_category is None: raise MusicServiceException( "%s does not support the '%s' search category" % ( self.service_name, category)) response = self.soap_client.call( 'search', [ ('id', search_category), ('term', term), ('index', index), ('count', count)]) return parse_response(self, response, category)
python
def search(self, category, term='', index=0, count=100): """Search for an item in a category. Args: 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: ~collections.OrderedDict: The search results, or `None`. See also: The Sonos `search API <http://musicpartners.sonos.com/node/86>`_ """ search_category = self._get_search_prefix_map().get(category, None) if search_category is None: raise MusicServiceException( "%s does not support the '%s' search category" % ( self.service_name, category)) response = self.soap_client.call( 'search', [ ('id', search_category), ('term', term), ('index', index), ('count', count)]) return parse_response(self, response, category)
[ "def", "search", "(", "self", ",", "category", ",", "term", "=", "''", ",", "index", "=", "0", ",", "count", "=", "100", ")", ":", "search_category", "=", "self", ".", "_get_search_prefix_map", "(", ")", ".", "get", "(", "category", ",", "None", ")",...
Search for an item in a category. Args: 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: ~collections.OrderedDict: The search results, or `None`. See also: The Sonos `search API <http://musicpartners.sonos.com/node/86>`_
[ "Search", "for", "an", "item", "in", "a", "category", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L695-L726
train
214,717
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_media_metadata
def get_media_metadata(self, item_id): """Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMediaMetadata API <http://musicpartners.sonos.com/node/83>`_ """ response = self.soap_client.call( 'getMediaMetadata', [('id', item_id)]) return response.get('getMediaMetadataResult', None)
python
def get_media_metadata(self, item_id): """Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMediaMetadata API <http://musicpartners.sonos.com/node/83>`_ """ response = self.soap_client.call( 'getMediaMetadata', [('id', item_id)]) return response.get('getMediaMetadataResult', None)
[ "def", "get_media_metadata", "(", "self", ",", "item_id", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getMediaMetadata'", ",", "[", "(", "'id'", ",", "item_id", ")", "]", ")", "return", "response", ".", "get", "(", "'getMed...
Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMediaMetadata API <http://musicpartners.sonos.com/node/83>`_
[ "Get", "metadata", "for", "a", "media", "item", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L728-L744
train
214,718
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_media_uri
def get_media_uri(self, item_id): """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 add it to the queue using its id and let the player work out where to get the stream from (see `On Demand Playback <http://musicpartners.sonos.com/node/421>`_ and `Programmed Radio <http://musicpartners.sonos.com/node/422>`_) Args: item_id (str): The item for which the URI is required Returns: str: The item's streaming URI. """ response = self.soap_client.call( 'getMediaURI', [('id', item_id)]) return response.get('getMediaURIResult', None)
python
def get_media_uri(self, item_id): """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 add it to the queue using its id and let the player work out where to get the stream from (see `On Demand Playback <http://musicpartners.sonos.com/node/421>`_ and `Programmed Radio <http://musicpartners.sonos.com/node/422>`_) Args: item_id (str): The item for which the URI is required Returns: str: The item's streaming URI. """ response = self.soap_client.call( 'getMediaURI', [('id', item_id)]) return response.get('getMediaURIResult', None)
[ "def", "get_media_uri", "(", "self", ",", "item_id", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getMediaURI'", ",", "[", "(", "'id'", ",", "item_id", ")", "]", ")", "return", "response", ".", "get", "(", "'getMediaURIResul...
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 add it to the queue using its id and let the player work out where to get the stream from (see `On Demand Playback <http://musicpartners.sonos.com/node/421>`_ and `Programmed Radio <http://musicpartners.sonos.com/node/422>`_) Args: item_id (str): The item for which the URI is required Returns: str: The item's streaming URI.
[ "Get", "a", "streaming", "URI", "for", "an", "item", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L746-L767
train
214,719
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_extended_metadata
def get_extended_metadata(self, item_id): """Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <http://musicpartners.sonos.com/node/128>`_ """ response = self.soap_client.call( 'getExtendedMetadata', [('id', item_id)]) return response.get('getExtendedMetadataResult', None)
python
def get_extended_metadata(self, item_id): """Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <http://musicpartners.sonos.com/node/128>`_ """ response = self.soap_client.call( 'getExtendedMetadata', [('id', item_id)]) return response.get('getExtendedMetadataResult', None)
[ "def", "get_extended_metadata", "(", "self", ",", "item_id", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getExtendedMetadata'", ",", "[", "(", "'id'", ",", "item_id", ")", "]", ")", "return", "response", ".", "get", "(", "'...
Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <http://musicpartners.sonos.com/node/128>`_
[ "Get", "extended", "metadata", "for", "a", "media", "item", "such", "as", "related", "items", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L783-L799
train
214,720
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_extended_metadata_text
def get_extended_metadata_text(self, item_id, metadata_type): """Get extended metadata text for a media item. Args: item_id (str): The item for which metadata is required metadata_type (str): The type of text to return, eg ``'ARTIST_BIO'``, or ``'ALBUM_NOTES'``. Calling `get_extended_metadata` for the item will show which extended metadata_types are available (under relatedBrowse and relatedText). Returns: str: The item's extended metadata text or None See also: The Sonos `getExtendedMetadataText API <http://musicpartners.sonos.com/node/127>`_ """ response = self.soap_client.call( 'getExtendedMetadataText', [('id', item_id), ('type', metadata_type)]) return response.get('getExtendedMetadataTextResult', None)
python
def get_extended_metadata_text(self, item_id, metadata_type): """Get extended metadata text for a media item. Args: item_id (str): The item for which metadata is required metadata_type (str): The type of text to return, eg ``'ARTIST_BIO'``, or ``'ALBUM_NOTES'``. Calling `get_extended_metadata` for the item will show which extended metadata_types are available (under relatedBrowse and relatedText). Returns: str: The item's extended metadata text or None See also: The Sonos `getExtendedMetadataText API <http://musicpartners.sonos.com/node/127>`_ """ response = self.soap_client.call( 'getExtendedMetadataText', [('id', item_id), ('type', metadata_type)]) return response.get('getExtendedMetadataTextResult', None)
[ "def", "get_extended_metadata_text", "(", "self", ",", "item_id", ",", "metadata_type", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getExtendedMetadataText'", ",", "[", "(", "'id'", ",", "item_id", ")", ",", "(", "'type'", ",",...
Get extended metadata text for a media item. Args: item_id (str): The item for which metadata is required metadata_type (str): The type of text to return, eg ``'ARTIST_BIO'``, or ``'ALBUM_NOTES'``. Calling `get_extended_metadata` for the item will show which extended metadata_types are available (under relatedBrowse and relatedText). Returns: str: The item's extended metadata text or None See also: The Sonos `getExtendedMetadataText API <http://musicpartners.sonos.com/node/127>`_
[ "Get", "extended", "metadata", "text", "for", "a", "media", "item", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L801-L821
train
214,721
SoCo/SoCo
soco/music_services/data_structures.py
get_class
def get_class(class_key): """Form a music service data structure class from the class key Args: class_key (str): A concatenation of the base class (e.g. MediaMetadata) and the class name Returns: class: Subclass of MusicServiceItem """ if class_key not in CLASSES: for basecls in (MediaMetadata, MediaCollection): if class_key.startswith(basecls.__name__): # So MediaMetadataTrack turns into MSTrack class_name = 'MS' + class_key.replace(basecls.__name__, '') if sys.version_info[0] == 2: class_name = class_name.encode('ascii') CLASSES[class_key] = type(class_name, (basecls,), {}) _LOG.info('Class %s created', CLASSES[class_key]) return CLASSES[class_key]
python
def get_class(class_key): """Form a music service data structure class from the class key Args: class_key (str): A concatenation of the base class (e.g. MediaMetadata) and the class name Returns: class: Subclass of MusicServiceItem """ if class_key not in CLASSES: for basecls in (MediaMetadata, MediaCollection): if class_key.startswith(basecls.__name__): # So MediaMetadataTrack turns into MSTrack class_name = 'MS' + class_key.replace(basecls.__name__, '') if sys.version_info[0] == 2: class_name = class_name.encode('ascii') CLASSES[class_key] = type(class_name, (basecls,), {}) _LOG.info('Class %s created', CLASSES[class_key]) return CLASSES[class_key]
[ "def", "get_class", "(", "class_key", ")", ":", "if", "class_key", "not", "in", "CLASSES", ":", "for", "basecls", "in", "(", "MediaMetadata", ",", "MediaCollection", ")", ":", "if", "class_key", ".", "startswith", "(", "basecls", ".", "__name__", ")", ":",...
Form a music service data structure class from the class key Args: class_key (str): A concatenation of the base class (e.g. MediaMetadata) and the class name Returns: class: Subclass of MusicServiceItem
[ "Form", "a", "music", "service", "data", "structure", "class", "from", "the", "class", "key" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L80-L99
train
214,722
SoCo/SoCo
soco/music_services/data_structures.py
parse_response
def parse_response(service, response, search_type): """Parse the response to a music service query and return a SearchResult Args: service (MusicService): The music service that produced the response response (OrderedDict): The response from the soap client call search_type (str): A string that indicates the search type that the response is from Returns: SearchResult: A SearchResult object """ _LOG.debug('Parse response "%s" from service "%s" of type "%s"', response, service, search_type) items = [] # The result to be parsed is in either searchResult or getMetadataResult if 'searchResult' in response: response = response['searchResult'] elif 'getMetadataResult' in response: response = response['getMetadataResult'] else: raise ValueError('"response" should contain either the key ' '"searchResult" or "getMetadataResult"') # Form the search metadata search_metadata = { 'number_returned': response['count'], 'total_matches': None, 'search_type': search_type, 'update_id': None, } for result_type in ('mediaCollection', 'mediaMetadata'): # Upper case the first letter (used for the class_key) result_type_proper = result_type[0].upper() + result_type[1:] raw_items = response.get(result_type, []) # If there is only 1 result, it is not put in an array if isinstance(raw_items, OrderedDict): raw_items = [raw_items] for raw_item in raw_items: # Form the class_key, which is a unique string for this type, # formed by concatenating the result type with the item type. Turns # into e.g: MediaMetadataTrack class_key = result_type_proper + raw_item['itemType'].title() cls = get_class(class_key) items.append(cls.from_music_service(service, raw_item)) return SearchResult(items, **search_metadata)
python
def parse_response(service, response, search_type): """Parse the response to a music service query and return a SearchResult Args: service (MusicService): The music service that produced the response response (OrderedDict): The response from the soap client call search_type (str): A string that indicates the search type that the response is from Returns: SearchResult: A SearchResult object """ _LOG.debug('Parse response "%s" from service "%s" of type "%s"', response, service, search_type) items = [] # The result to be parsed is in either searchResult or getMetadataResult if 'searchResult' in response: response = response['searchResult'] elif 'getMetadataResult' in response: response = response['getMetadataResult'] else: raise ValueError('"response" should contain either the key ' '"searchResult" or "getMetadataResult"') # Form the search metadata search_metadata = { 'number_returned': response['count'], 'total_matches': None, 'search_type': search_type, 'update_id': None, } for result_type in ('mediaCollection', 'mediaMetadata'): # Upper case the first letter (used for the class_key) result_type_proper = result_type[0].upper() + result_type[1:] raw_items = response.get(result_type, []) # If there is only 1 result, it is not put in an array if isinstance(raw_items, OrderedDict): raw_items = [raw_items] for raw_item in raw_items: # Form the class_key, which is a unique string for this type, # formed by concatenating the result type with the item type. Turns # into e.g: MediaMetadataTrack class_key = result_type_proper + raw_item['itemType'].title() cls = get_class(class_key) items.append(cls.from_music_service(service, raw_item)) return SearchResult(items, **search_metadata)
[ "def", "parse_response", "(", "service", ",", "response", ",", "search_type", ")", ":", "_LOG", ".", "debug", "(", "'Parse response \"%s\" from service \"%s\" of type \"%s\"'", ",", "response", ",", "service", ",", "search_type", ")", "items", "=", "[", "]", "# Th...
Parse the response to a music service query and return a SearchResult Args: service (MusicService): The music service that produced the response response (OrderedDict): The response from the soap client call search_type (str): A string that indicates the search type that the response is from Returns: SearchResult: A SearchResult object
[ "Parse", "the", "response", "to", "a", "music", "service", "query", "and", "return", "a", "SearchResult" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L102-L149
train
214,723
SoCo/SoCo
soco/music_services/data_structures.py
form_uri
def form_uri(item_id, service, is_track): """Form and return a music service item uri Args: item_id (str): The item id service (MusicService): The music service that the item originates from is_track (bool): Whether the item_id is from a track or not Returns: str: The music service item uri """ if is_track: uri = service.sonos_uri_from_id(item_id) else: uri = 'x-rincon-cpcontainer:' + item_id return uri
python
def form_uri(item_id, service, is_track): """Form and return a music service item uri Args: item_id (str): The item id service (MusicService): The music service that the item originates from is_track (bool): Whether the item_id is from a track or not Returns: str: The music service item uri """ if is_track: uri = service.sonos_uri_from_id(item_id) else: uri = 'x-rincon-cpcontainer:' + item_id return uri
[ "def", "form_uri", "(", "item_id", ",", "service", ",", "is_track", ")", ":", "if", "is_track", ":", "uri", "=", "service", ".", "sonos_uri_from_id", "(", "item_id", ")", "else", ":", "uri", "=", "'x-rincon-cpcontainer:'", "+", "item_id", "return", "uri" ]
Form and return a music service item uri Args: item_id (str): The item id service (MusicService): The music service that the item originates from is_track (bool): Whether the item_id is from a track or not Returns: str: The music service item uri
[ "Form", "and", "return", "a", "music", "service", "item", "uri" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L152-L167
train
214,724
SoCo/SoCo
soco/music_services/data_structures.py
bool_str
def bool_str(string): """Returns a boolean from a string imput of 'true' or 'false'""" if string not in BOOL_STRS: raise ValueError('Invalid boolean string: "{}"'.format(string)) return True if string == 'true' else False
python
def bool_str(string): """Returns a boolean from a string imput of 'true' or 'false'""" if string not in BOOL_STRS: raise ValueError('Invalid boolean string: "{}"'.format(string)) return True if string == 'true' else False
[ "def", "bool_str", "(", "string", ")", ":", "if", "string", "not", "in", "BOOL_STRS", ":", "raise", "ValueError", "(", "'Invalid boolean string: \"{}\"'", ".", "format", "(", "string", ")", ")", "return", "True", "if", "string", "==", "'true'", "else", "Fals...
Returns a boolean from a string imput of 'true' or 'false
[ "Returns", "a", "boolean", "from", "a", "string", "imput", "of", "true", "or", "false" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L174-L178
train
214,725
SoCo/SoCo
soco/music_services/accounts.py
Account._get_account_xml
def _get_account_xml(soco): """Fetch the account data from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If soco is `None`, a random device will be used. Returns: str: a byte string containing the account data xml """ # It is likely that the same information is available over UPnP as well # via a call to # systemProperties.GetStringX([('VariableName','R_SvcAccounts')])) # This returns an encrypted string, and, so far, we cannot decrypt it device = soco or discovery.any_soco() log.debug("Fetching account data from %s", device) settings_url = "http://{}:1400/status/accounts".format( device.ip_address) result = requests.get(settings_url).content log.debug("Account data: %s", result) return result
python
def _get_account_xml(soco): """Fetch the account data from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If soco is `None`, a random device will be used. Returns: str: a byte string containing the account data xml """ # It is likely that the same information is available over UPnP as well # via a call to # systemProperties.GetStringX([('VariableName','R_SvcAccounts')])) # This returns an encrypted string, and, so far, we cannot decrypt it device = soco or discovery.any_soco() log.debug("Fetching account data from %s", device) settings_url = "http://{}:1400/status/accounts".format( device.ip_address) result = requests.get(settings_url).content log.debug("Account data: %s", result) return result
[ "def", "_get_account_xml", "(", "soco", ")", ":", "# It is likely that the same information is available over UPnP as well", "# via a call to", "# systemProperties.GetStringX([('VariableName','R_SvcAccounts')]))", "# This returns an encrypted string, and, so far, we cannot decrypt it", "device",...
Fetch the account data from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If soco is `None`, a random device will be used. Returns: str: a byte string containing the account data xml
[ "Fetch", "the", "account", "data", "from", "a", "Sonos", "device", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/accounts.py#L67-L87
train
214,726
SoCo/SoCo
soco/music_services/accounts.py
Account.get_accounts
def get_accounts(cls, soco=None): """Get all accounts known to the Sonos system. Args: soco (`SoCo`, optional): a `SoCo` instance to query. If `None`, a random instance is used. Defaults to `None`. Returns: dict: A dict containing account instances. Each key is the account's serial number, and each value is the related Account instance. Accounts which have been marked as deleted are excluded. Note: Any existing Account instance will have its attributes updated to those currently stored on the Sonos system. """ root = XML.fromstring(cls._get_account_xml(soco)) # _get_account_xml returns an ElementTree element like this: # <ZPSupportInfo type="User"> # <Accounts # LastUpdateDevice="RINCON_000XXXXXXXX400" # Version="8" NextSerialNum="5"> # <Account Type="2311" SerialNum="1"> # <UN>12345678</UN> # <MD>1</MD> # <NN></NN> # <OADevID></OADevID> # <Key></Key> # </Account> # <Account Type="41735" SerialNum="3" Deleted="1"> # <UN></UN> # <MD>1</MD> # <NN>Nickname</NN> # <OADevID></OADevID> # <Key></Key> # </Account> # ... # <Accounts /> xml_accounts = root.findall('.//Account') result = {} for xml_account in xml_accounts: serial_number = xml_account.get('SerialNum') is_deleted = True if xml_account.get('Deleted') == '1' else False # cls._all_accounts is a weakvaluedict keyed by serial number. # We use it as a database to store details of the accounts we # know about. We need to update it with info obtained from the # XML just obtained, so (1) check to see if we already have an # entry in cls._all_accounts for the account we have found in # XML; (2) if so, delete it if the XML says it has been deleted; # and (3) if not, create an entry for it if cls._all_accounts.get(serial_number): # We have an existing entry in our database. Do we need to # delete it? if is_deleted: # Yes, so delete it and move to the next XML account del cls._all_accounts[serial_number] continue else: # No, so load up its details, ready to update them account = cls._all_accounts.get(serial_number) else: # We have no existing entry for this account if is_deleted: # but it is marked as deleted, so we don't need one continue # If it is not marked as deleted, we need to create an entry account = Account() account.serial_number = serial_number cls._all_accounts[serial_number] = account # Now, update the entry in our database with the details from XML account.service_type = xml_account.get('Type') account.deleted = is_deleted account.username = xml_account.findtext('UN') # Not sure what 'MD' stands for. Metadata? May Delete? account.metadata = xml_account.findtext('MD') account.nickname = xml_account.findtext('NN') account.oa_device_id = xml_account.findtext('OADevID') account.key = xml_account.findtext('Key') result[serial_number] = account # There is always a TuneIn account, but it is handled separately # by Sonos, and does not appear in the xml account data. We # need to add it ourselves. tunein = Account() tunein.service_type = '65031' # Is this always the case? tunein.deleted = False tunein.username = '' tunein.metadata = '' tunein.nickname = '' tunein.oa_device_id = '' tunein.key = '' tunein.serial_number = '0' result['0'] = tunein return result
python
def get_accounts(cls, soco=None): """Get all accounts known to the Sonos system. Args: soco (`SoCo`, optional): a `SoCo` instance to query. If `None`, a random instance is used. Defaults to `None`. Returns: dict: A dict containing account instances. Each key is the account's serial number, and each value is the related Account instance. Accounts which have been marked as deleted are excluded. Note: Any existing Account instance will have its attributes updated to those currently stored on the Sonos system. """ root = XML.fromstring(cls._get_account_xml(soco)) # _get_account_xml returns an ElementTree element like this: # <ZPSupportInfo type="User"> # <Accounts # LastUpdateDevice="RINCON_000XXXXXXXX400" # Version="8" NextSerialNum="5"> # <Account Type="2311" SerialNum="1"> # <UN>12345678</UN> # <MD>1</MD> # <NN></NN> # <OADevID></OADevID> # <Key></Key> # </Account> # <Account Type="41735" SerialNum="3" Deleted="1"> # <UN></UN> # <MD>1</MD> # <NN>Nickname</NN> # <OADevID></OADevID> # <Key></Key> # </Account> # ... # <Accounts /> xml_accounts = root.findall('.//Account') result = {} for xml_account in xml_accounts: serial_number = xml_account.get('SerialNum') is_deleted = True if xml_account.get('Deleted') == '1' else False # cls._all_accounts is a weakvaluedict keyed by serial number. # We use it as a database to store details of the accounts we # know about. We need to update it with info obtained from the # XML just obtained, so (1) check to see if we already have an # entry in cls._all_accounts for the account we have found in # XML; (2) if so, delete it if the XML says it has been deleted; # and (3) if not, create an entry for it if cls._all_accounts.get(serial_number): # We have an existing entry in our database. Do we need to # delete it? if is_deleted: # Yes, so delete it and move to the next XML account del cls._all_accounts[serial_number] continue else: # No, so load up its details, ready to update them account = cls._all_accounts.get(serial_number) else: # We have no existing entry for this account if is_deleted: # but it is marked as deleted, so we don't need one continue # If it is not marked as deleted, we need to create an entry account = Account() account.serial_number = serial_number cls._all_accounts[serial_number] = account # Now, update the entry in our database with the details from XML account.service_type = xml_account.get('Type') account.deleted = is_deleted account.username = xml_account.findtext('UN') # Not sure what 'MD' stands for. Metadata? May Delete? account.metadata = xml_account.findtext('MD') account.nickname = xml_account.findtext('NN') account.oa_device_id = xml_account.findtext('OADevID') account.key = xml_account.findtext('Key') result[serial_number] = account # There is always a TuneIn account, but it is handled separately # by Sonos, and does not appear in the xml account data. We # need to add it ourselves. tunein = Account() tunein.service_type = '65031' # Is this always the case? tunein.deleted = False tunein.username = '' tunein.metadata = '' tunein.nickname = '' tunein.oa_device_id = '' tunein.key = '' tunein.serial_number = '0' result['0'] = tunein return result
[ "def", "get_accounts", "(", "cls", ",", "soco", "=", "None", ")", ":", "root", "=", "XML", ".", "fromstring", "(", "cls", ".", "_get_account_xml", "(", "soco", ")", ")", "# _get_account_xml returns an ElementTree element like this:", "# <ZPSupportInfo type=\"User\">",...
Get all accounts known to the Sonos system. Args: soco (`SoCo`, optional): a `SoCo` instance to query. If `None`, a random instance is used. Defaults to `None`. Returns: dict: A dict containing account instances. Each key is the account's serial number, and each value is the related Account instance. Accounts which have been marked as deleted are excluded. Note: Any existing Account instance will have its attributes updated to those currently stored on the Sonos system.
[ "Get", "all", "accounts", "known", "to", "the", "Sonos", "system", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/accounts.py#L90-L187
train
214,727
SoCo/SoCo
soco/music_services/accounts.py
Account.get_accounts_for_service
def get_accounts_for_service(cls, service_type): """Get a list of accounts for a given music service. Args: service_type (str): The service_type to use. Returns: list: A list of `Account` instances. """ return [ a for a in cls.get_accounts().values() if a.service_type == service_type ]
python
def get_accounts_for_service(cls, service_type): """Get a list of accounts for a given music service. Args: service_type (str): The service_type to use. Returns: list: A list of `Account` instances. """ return [ a for a in cls.get_accounts().values() if a.service_type == service_type ]
[ "def", "get_accounts_for_service", "(", "cls", ",", "service_type", ")", ":", "return", "[", "a", "for", "a", "in", "cls", ".", "get_accounts", "(", ")", ".", "values", "(", ")", "if", "a", ".", "service_type", "==", "service_type", "]" ]
Get a list of accounts for a given music service. Args: service_type (str): The service_type to use. Returns: list: A list of `Account` instances.
[ "Get", "a", "list", "of", "accounts", "for", "a", "given", "music", "service", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/accounts.py#L190-L202
train
214,728
SoCo/SoCo
examples/snapshot/multi_zone_snap.py
play_alert
def play_alert(zones, alert_uri, alert_volume=20, alert_duration=0, fade_back=False): """ Demo function using soco.snapshot across multiple Sonos players. Args: zones (set): a set of SoCo objects alert_uri (str): uri that Sonos can play as an alert alert_volume (int): volume level for playing alert (0 tp 100) alert_duration (int): length of alert (if zero then length of track) fade_back (bool): on reinstating the zones fade up the sound? """ # Use soco.snapshot to capture current state of each zone to allow restore for zone in zones: zone.snap = Snapshot(zone) zone.snap.snapshot() print('snapshot of zone: {}'.format(zone.player_name)) # prepare all zones for playing the alert for zone in zones: # Each Sonos group has one coordinator only these can play, pause, etc. if zone.is_coordinator: if not zone.is_playing_tv: # can't pause TV - so don't try! # pause music for each coordinators if playing trans_state = zone.get_current_transport_info() if trans_state['current_transport_state'] == 'PLAYING': zone.pause() # For every Sonos player set volume and mute for every zone zone.volume = alert_volume zone.mute = False # play the sound (uri) on each sonos coordinator print('will play: {} on all coordinators'.format(alert_uri)) for zone in zones: if zone.is_coordinator: zone.play_uri(uri=alert_uri, title='Sonos Alert') # wait for alert_duration time.sleep(alert_duration) # restore each zone to previous state for zone in zones: print('restoring {}'.format(zone.player_name)) zone.snap.restore(fade=fade_back)
python
def play_alert(zones, alert_uri, alert_volume=20, alert_duration=0, fade_back=False): """ Demo function using soco.snapshot across multiple Sonos players. Args: zones (set): a set of SoCo objects alert_uri (str): uri that Sonos can play as an alert alert_volume (int): volume level for playing alert (0 tp 100) alert_duration (int): length of alert (if zero then length of track) fade_back (bool): on reinstating the zones fade up the sound? """ # Use soco.snapshot to capture current state of each zone to allow restore for zone in zones: zone.snap = Snapshot(zone) zone.snap.snapshot() print('snapshot of zone: {}'.format(zone.player_name)) # prepare all zones for playing the alert for zone in zones: # Each Sonos group has one coordinator only these can play, pause, etc. if zone.is_coordinator: if not zone.is_playing_tv: # can't pause TV - so don't try! # pause music for each coordinators if playing trans_state = zone.get_current_transport_info() if trans_state['current_transport_state'] == 'PLAYING': zone.pause() # For every Sonos player set volume and mute for every zone zone.volume = alert_volume zone.mute = False # play the sound (uri) on each sonos coordinator print('will play: {} on all coordinators'.format(alert_uri)) for zone in zones: if zone.is_coordinator: zone.play_uri(uri=alert_uri, title='Sonos Alert') # wait for alert_duration time.sleep(alert_duration) # restore each zone to previous state for zone in zones: print('restoring {}'.format(zone.player_name)) zone.snap.restore(fade=fade_back)
[ "def", "play_alert", "(", "zones", ",", "alert_uri", ",", "alert_volume", "=", "20", ",", "alert_duration", "=", "0", ",", "fade_back", "=", "False", ")", ":", "# Use soco.snapshot to capture current state of each zone to allow restore", "for", "zone", "in", "zones", ...
Demo function using soco.snapshot across multiple Sonos players. Args: zones (set): a set of SoCo objects alert_uri (str): uri that Sonos can play as an alert alert_volume (int): volume level for playing alert (0 tp 100) alert_duration (int): length of alert (if zero then length of track) fade_back (bool): on reinstating the zones fade up the sound?
[ "Demo", "function", "using", "soco", ".", "snapshot", "across", "multiple", "Sonos", "players", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/examples/snapshot/multi_zone_snap.py#L27-L71
train
214,729
SoCo/SoCo
soco/cache.py
TimedCache.get
def get(self, *args, **kwargs): """Get an item from the cache for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. Returns: object: The object which has been found in the cache, or `None` if no unexpired item is found. This means that there is no point storing an item in the cache if it is `None`. """ if not self.enabled: return None # Look in the cache to see if there is an unexpired item. If there is # we can just return the cached result. cache_key = self.make_key(args, kwargs) # Lock and load with self._cache_lock: if cache_key in self._cache: expirytime, item = self._cache[cache_key] if expirytime >= time(): return item else: # An expired item is present - delete it del self._cache[cache_key] # Nothing found return None
python
def get(self, *args, **kwargs): """Get an item from the cache for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. Returns: object: The object which has been found in the cache, or `None` if no unexpired item is found. This means that there is no point storing an item in the cache if it is `None`. """ if not self.enabled: return None # Look in the cache to see if there is an unexpired item. If there is # we can just return the cached result. cache_key = self.make_key(args, kwargs) # Lock and load with self._cache_lock: if cache_key in self._cache: expirytime, item = self._cache[cache_key] if expirytime >= time(): return item else: # An expired item is present - delete it del self._cache[cache_key] # Nothing found return None
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "None", "# Look in the cache to see if there is an unexpired item. If there is", "# we can just return the cached result.", "cache_key", ...
Get an item from the cache for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. Returns: object: The object which has been found in the cache, or `None` if no unexpired item is found. This means that there is no point storing an item in the cache if it is `None`.
[ "Get", "an", "item", "from", "the", "cache", "for", "this", "combination", "of", "args", "and", "kwargs", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/cache.py#L117-L146
train
214,730
SoCo/SoCo
soco/cache.py
TimedCache.put
def put(self, item, *args, **kwargs): """Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available for retrieval for ``timeout`` seconds. If ``timeout`` is `None` or not specified, the ``default_timeout`` for this cache will be used. Specify a ``timeout`` of 0 (or ensure that the ``default_timeout`` for this cache is 0) if this item is not to be cached. """ if not self.enabled: return # Check for a timeout keyword, store and remove it. timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.default_timeout cache_key = self.make_key(args, kwargs) # Store the item, along with the time at which it will expire with self._cache_lock: self._cache[cache_key] = (time() + timeout, item)
python
def put(self, item, *args, **kwargs): """Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available for retrieval for ``timeout`` seconds. If ``timeout`` is `None` or not specified, the ``default_timeout`` for this cache will be used. Specify a ``timeout`` of 0 (or ensure that the ``default_timeout`` for this cache is 0) if this item is not to be cached. """ if not self.enabled: return # Check for a timeout keyword, store and remove it. timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.default_timeout cache_key = self.make_key(args, kwargs) # Store the item, along with the time at which it will expire with self._cache_lock: self._cache[cache_key] = (time() + timeout, item)
[ "def", "put", "(", "self", ",", "item", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "# Check for a timeout keyword, store and remove it.", "timeout", "=", "kwargs", ".", "pop", "(", "'timeout'", ...
Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available for retrieval for ``timeout`` seconds. If ``timeout`` is `None` or not specified, the ``default_timeout`` for this cache will be used. Specify a ``timeout`` of 0 (or ensure that the ``default_timeout`` for this cache is 0) if this item is not to be cached.
[ "Put", "an", "item", "into", "the", "cache", "for", "this", "combination", "of", "args", "and", "kwargs", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/cache.py#L148-L170
train
214,731
SoCo/SoCo
soco/cache.py
TimedCache.delete
def delete(self, *args, **kwargs): """Delete an item from the cache for this combination of args and kwargs.""" cache_key = self.make_key(args, kwargs) with self._cache_lock: try: del self._cache[cache_key] except KeyError: pass
python
def delete(self, *args, **kwargs): """Delete an item from the cache for this combination of args and kwargs.""" cache_key = self.make_key(args, kwargs) with self._cache_lock: try: del self._cache[cache_key] except KeyError: pass
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cache_key", "=", "self", ".", "make_key", "(", "args", ",", "kwargs", ")", "with", "self", ".", "_cache_lock", ":", "try", ":", "del", "self", ".", "_cache", "[", ...
Delete an item from the cache for this combination of args and kwargs.
[ "Delete", "an", "item", "from", "the", "cache", "for", "this", "combination", "of", "args", "and", "kwargs", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/cache.py#L172-L180
train
214,732
SoCo/SoCo
soco/music_library.py
MusicLibrary.build_album_art_full_uri
def build_album_art_full_uri(self, url): """Ensure an Album Art URI is an absolute URI. Args: url (str): the album art URI. Returns: str: An absolute URI. """ # Add on the full album art link, as the URI version # does not include the ipaddress if not url.startswith(('http:', 'https:')): url = 'http://' + self.soco.ip_address + ':1400' + url return url
python
def build_album_art_full_uri(self, url): """Ensure an Album Art URI is an absolute URI. Args: url (str): the album art URI. Returns: str: An absolute URI. """ # Add on the full album art link, as the URI version # does not include the ipaddress if not url.startswith(('http:', 'https:')): url = 'http://' + self.soco.ip_address + ':1400' + url return url
[ "def", "build_album_art_full_uri", "(", "self", ",", "url", ")", ":", "# Add on the full album art link, as the URI version", "# does not include the ipaddress", "if", "not", "url", ".", "startswith", "(", "(", "'http:'", ",", "'https:'", ")", ")", ":", "url", "=", ...
Ensure an Album Art URI is an absolute URI. Args: url (str): the album art URI. Returns: str: An absolute URI.
[ "Ensure", "an", "Album", "Art", "URI", "is", "an", "absolute", "URI", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L59-L72
train
214,733
SoCo/SoCo
soco/music_library.py
MusicLibrary._update_album_art_to_full_uri
def _update_album_art_to_full_uri(self, item): """Update an item's Album Art URI to be an absolute URI. Args: item: The item to update the URI for """ if getattr(item, 'album_art_uri', False): item.album_art_uri = self.build_album_art_full_uri( item.album_art_uri)
python
def _update_album_art_to_full_uri(self, item): """Update an item's Album Art URI to be an absolute URI. Args: item: The item to update the URI for """ if getattr(item, 'album_art_uri', False): item.album_art_uri = self.build_album_art_full_uri( item.album_art_uri)
[ "def", "_update_album_art_to_full_uri", "(", "self", ",", "item", ")", ":", "if", "getattr", "(", "item", ",", "'album_art_uri'", ",", "False", ")", ":", "item", ".", "album_art_uri", "=", "self", ".", "build_album_art_full_uri", "(", "item", ".", "album_art_u...
Update an item's Album Art URI to be an absolute URI. Args: item: The item to update the URI for
[ "Update", "an", "item", "s", "Album", "Art", "URI", "to", "be", "an", "absolute", "URI", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L74-L82
train
214,734
SoCo/SoCo
soco/music_library.py
MusicLibrary.get_music_library_information
def get_music_library_information(self, search_type, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None, complete_result=False): """Retrieve music information objects from the music library. This method is the main method to get music information items, like e.g. tracks, albums etc., from the music library with. It can be used in a few different ways: The ``search_term`` argument performs a fuzzy search on that string in the results, so e.g calling:: get_music_library_information('artists', search_term='Metallica') will perform a fuzzy search for the term 'Metallica' among all the artists. Using the ``subcategories`` argument, will jump directly into that subcategory of the search and return results from there. So. e.g knowing that among the artist is one called 'Metallica', calling:: get_music_library_information('artists', subcategories=['Metallica']) will jump directly into the 'Metallica' sub category and return the albums associated with Metallica and:: get_music_library_information('artists', subcategories=['Metallica', 'Black']) will return the tracks of the album 'Black' by the artist 'Metallica'. The order of sub category types is: Genres->Artists->Albums->Tracks. It is also possible to combine the two, to perform a fuzzy search in a sub category. The ``start``, ``max_items`` and ``complete_result`` arguments all have to do with paging of the results. By default the searches are always paged, because there is a limit to how many items we can get at a time. This paging is exposed to the user with the ``start`` and ``max_items`` arguments. So calling:: get_music_library_information('artists', start=0, max_items=100) get_music_library_information('artists', start=100, max_items=100) will get the first and next 100 items, respectively. It is also possible to ask for all the elements at once:: get_music_library_information('artists', complete_result=True) This will perform the paging internally and simply return all the items. Args: search_type (str): The kind of information to retrieve. Can be one of: ``'artists'``, ``'album_artists'``, ``'albums'``, ``'genres'``, ``'composers'``, ``'tracks'``, ``'share'``, ``'sonos_playlists'``, or ``'playlists'``, where playlists are the imported playlists from the music library. start (int, optional): starting number of returned matches (zero based). Default 0. max_items (int, optional): Maximum number of returned matches. Default 100. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. search_term (str, optional): a string that will be used to perform a fuzzy search among the search results. If used in combination with subcategories, the fuzzy search will be performed in the subcategory. subcategories (str, optional): A list of strings that indicate one or more subcategories to dive into. complete_result (bool): if `True`, will disable paging (ignore ``start`` and ``max_items``) and return all results for the search. Warning: Getting e.g. all the tracks in a large collection might take some time. Returns: `SearchResult`: an instance of `SearchResult`. Note: * The maximum numer of results may be restricted by the unit, presumably due to transfer size consideration, so check the returned number against that requested. * The playlists that are returned with the ``'playlists'`` search, are the playlists imported from the music library, they are not the Sonos playlists. Raises: `SoCoException` upon errors. """ search = self.SEARCH_TRANSLATION[search_type] # Add sub categories if subcategories is not None: for category in subcategories: search += '/' + url_escape_path(really_unicode(category)) # Add fuzzy search if search_term is not None: search += ':' + url_escape_path(really_unicode(search_term)) item_list = [] metadata = {'total_matches': 100000} while len(item_list) < metadata['total_matches']: # Change start and max for complete searches if complete_result: start, max_items = len(item_list), 100000 # Try and get this batch of results try: response, metadata = \ self._music_lib_search(search, start, max_items) except SoCoUPnPException as exception: # 'No such object' UPnP errors if exception.error_code == '701': return SearchResult([], search_type, 0, 0, None) else: raise exception # Parse the results items = from_didl_string(response['Result']) for item in items: # Check if the album art URI should be fully qualified if full_album_art_uri: self._update_album_art_to_full_uri(item) # Append the item to the list item_list.append(item) # If we are not after the complete results, the stop after 1 # iteration if not complete_result: break metadata['search_type'] = search_type if complete_result: metadata['number_returned'] = len(item_list) # pylint: disable=star-args return SearchResult(item_list, **metadata)
python
def get_music_library_information(self, search_type, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None, complete_result=False): """Retrieve music information objects from the music library. This method is the main method to get music information items, like e.g. tracks, albums etc., from the music library with. It can be used in a few different ways: The ``search_term`` argument performs a fuzzy search on that string in the results, so e.g calling:: get_music_library_information('artists', search_term='Metallica') will perform a fuzzy search for the term 'Metallica' among all the artists. Using the ``subcategories`` argument, will jump directly into that subcategory of the search and return results from there. So. e.g knowing that among the artist is one called 'Metallica', calling:: get_music_library_information('artists', subcategories=['Metallica']) will jump directly into the 'Metallica' sub category and return the albums associated with Metallica and:: get_music_library_information('artists', subcategories=['Metallica', 'Black']) will return the tracks of the album 'Black' by the artist 'Metallica'. The order of sub category types is: Genres->Artists->Albums->Tracks. It is also possible to combine the two, to perform a fuzzy search in a sub category. The ``start``, ``max_items`` and ``complete_result`` arguments all have to do with paging of the results. By default the searches are always paged, because there is a limit to how many items we can get at a time. This paging is exposed to the user with the ``start`` and ``max_items`` arguments. So calling:: get_music_library_information('artists', start=0, max_items=100) get_music_library_information('artists', start=100, max_items=100) will get the first and next 100 items, respectively. It is also possible to ask for all the elements at once:: get_music_library_information('artists', complete_result=True) This will perform the paging internally and simply return all the items. Args: search_type (str): The kind of information to retrieve. Can be one of: ``'artists'``, ``'album_artists'``, ``'albums'``, ``'genres'``, ``'composers'``, ``'tracks'``, ``'share'``, ``'sonos_playlists'``, or ``'playlists'``, where playlists are the imported playlists from the music library. start (int, optional): starting number of returned matches (zero based). Default 0. max_items (int, optional): Maximum number of returned matches. Default 100. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. search_term (str, optional): a string that will be used to perform a fuzzy search among the search results. If used in combination with subcategories, the fuzzy search will be performed in the subcategory. subcategories (str, optional): A list of strings that indicate one or more subcategories to dive into. complete_result (bool): if `True`, will disable paging (ignore ``start`` and ``max_items``) and return all results for the search. Warning: Getting e.g. all the tracks in a large collection might take some time. Returns: `SearchResult`: an instance of `SearchResult`. Note: * The maximum numer of results may be restricted by the unit, presumably due to transfer size consideration, so check the returned number against that requested. * The playlists that are returned with the ``'playlists'`` search, are the playlists imported from the music library, they are not the Sonos playlists. Raises: `SoCoException` upon errors. """ search = self.SEARCH_TRANSLATION[search_type] # Add sub categories if subcategories is not None: for category in subcategories: search += '/' + url_escape_path(really_unicode(category)) # Add fuzzy search if search_term is not None: search += ':' + url_escape_path(really_unicode(search_term)) item_list = [] metadata = {'total_matches': 100000} while len(item_list) < metadata['total_matches']: # Change start and max for complete searches if complete_result: start, max_items = len(item_list), 100000 # Try and get this batch of results try: response, metadata = \ self._music_lib_search(search, start, max_items) except SoCoUPnPException as exception: # 'No such object' UPnP errors if exception.error_code == '701': return SearchResult([], search_type, 0, 0, None) else: raise exception # Parse the results items = from_didl_string(response['Result']) for item in items: # Check if the album art URI should be fully qualified if full_album_art_uri: self._update_album_art_to_full_uri(item) # Append the item to the list item_list.append(item) # If we are not after the complete results, the stop after 1 # iteration if not complete_result: break metadata['search_type'] = search_type if complete_result: metadata['number_returned'] = len(item_list) # pylint: disable=star-args return SearchResult(item_list, **metadata)
[ "def", "get_music_library_information", "(", "self", ",", "search_type", ",", "start", "=", "0", ",", "max_items", "=", "100", ",", "full_album_art_uri", "=", "False", ",", "search_term", "=", "None", ",", "subcategories", "=", "None", ",", "complete_result", ...
Retrieve music information objects from the music library. This method is the main method to get music information items, like e.g. tracks, albums etc., from the music library with. It can be used in a few different ways: The ``search_term`` argument performs a fuzzy search on that string in the results, so e.g calling:: get_music_library_information('artists', search_term='Metallica') will perform a fuzzy search for the term 'Metallica' among all the artists. Using the ``subcategories`` argument, will jump directly into that subcategory of the search and return results from there. So. e.g knowing that among the artist is one called 'Metallica', calling:: get_music_library_information('artists', subcategories=['Metallica']) will jump directly into the 'Metallica' sub category and return the albums associated with Metallica and:: get_music_library_information('artists', subcategories=['Metallica', 'Black']) will return the tracks of the album 'Black' by the artist 'Metallica'. The order of sub category types is: Genres->Artists->Albums->Tracks. It is also possible to combine the two, to perform a fuzzy search in a sub category. The ``start``, ``max_items`` and ``complete_result`` arguments all have to do with paging of the results. By default the searches are always paged, because there is a limit to how many items we can get at a time. This paging is exposed to the user with the ``start`` and ``max_items`` arguments. So calling:: get_music_library_information('artists', start=0, max_items=100) get_music_library_information('artists', start=100, max_items=100) will get the first and next 100 items, respectively. It is also possible to ask for all the elements at once:: get_music_library_information('artists', complete_result=True) This will perform the paging internally and simply return all the items. Args: search_type (str): The kind of information to retrieve. Can be one of: ``'artists'``, ``'album_artists'``, ``'albums'``, ``'genres'``, ``'composers'``, ``'tracks'``, ``'share'``, ``'sonos_playlists'``, or ``'playlists'``, where playlists are the imported playlists from the music library. start (int, optional): starting number of returned matches (zero based). Default 0. max_items (int, optional): Maximum number of returned matches. Default 100. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. search_term (str, optional): a string that will be used to perform a fuzzy search among the search results. If used in combination with subcategories, the fuzzy search will be performed in the subcategory. subcategories (str, optional): A list of strings that indicate one or more subcategories to dive into. complete_result (bool): if `True`, will disable paging (ignore ``start`` and ``max_items``) and return all results for the search. Warning: Getting e.g. all the tracks in a large collection might take some time. Returns: `SearchResult`: an instance of `SearchResult`. Note: * The maximum numer of results may be restricted by the unit, presumably due to transfer size consideration, so check the returned number against that requested. * The playlists that are returned with the ``'playlists'`` search, are the playlists imported from the music library, they are not the Sonos playlists. Raises: `SoCoException` upon errors.
[ "Retrieve", "music", "information", "objects", "from", "the", "music", "library", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L188-L334
train
214,735
SoCo/SoCo
soco/music_library.py
MusicLibrary._music_lib_search
def _music_lib_search(self, search, start, max_items): """Perform a music library search and extract search numbers. You can get an overview of all the relevant search prefixes (like 'A:') and their meaning with the request: .. code :: response = device.contentDirectory.Browse([ ('ObjectID', '0'), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', 0), ('RequestedCount', 100), ('SortCriteria', '') ]) Args: search (str): The ID to search. start (int): The index of the forst item to return. max_items (int): The maximum number of items to return. Returns: tuple: (response, metadata) where response is the returned metadata and metadata is a dict with the 'number_returned', 'total_matches' and 'update_id' integers """ response = self.contentDirectory.Browse([ ('ObjectID', search), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', start), ('RequestedCount', max_items), ('SortCriteria', '') ]) # Get result information metadata = {} for tag in ['NumberReturned', 'TotalMatches', 'UpdateID']: metadata[camel_to_underscore(tag)] = int(response[tag]) return response, metadata
python
def _music_lib_search(self, search, start, max_items): """Perform a music library search and extract search numbers. You can get an overview of all the relevant search prefixes (like 'A:') and their meaning with the request: .. code :: response = device.contentDirectory.Browse([ ('ObjectID', '0'), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', 0), ('RequestedCount', 100), ('SortCriteria', '') ]) Args: search (str): The ID to search. start (int): The index of the forst item to return. max_items (int): The maximum number of items to return. Returns: tuple: (response, metadata) where response is the returned metadata and metadata is a dict with the 'number_returned', 'total_matches' and 'update_id' integers """ response = self.contentDirectory.Browse([ ('ObjectID', search), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', start), ('RequestedCount', max_items), ('SortCriteria', '') ]) # Get result information metadata = {} for tag in ['NumberReturned', 'TotalMatches', 'UpdateID']: metadata[camel_to_underscore(tag)] = int(response[tag]) return response, metadata
[ "def", "_music_lib_search", "(", "self", ",", "search", ",", "start", ",", "max_items", ")", ":", "response", "=", "self", ".", "contentDirectory", ".", "Browse", "(", "[", "(", "'ObjectID'", ",", "search", ")", ",", "(", "'BrowseFlag'", ",", "'BrowseDirec...
Perform a music library search and extract search numbers. You can get an overview of all the relevant search prefixes (like 'A:') and their meaning with the request: .. code :: response = device.contentDirectory.Browse([ ('ObjectID', '0'), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', 0), ('RequestedCount', 100), ('SortCriteria', '') ]) Args: search (str): The ID to search. start (int): The index of the forst item to return. max_items (int): The maximum number of items to return. Returns: tuple: (response, metadata) where response is the returned metadata and metadata is a dict with the 'number_returned', 'total_matches' and 'update_id' integers
[ "Perform", "a", "music", "library", "search", "and", "extract", "search", "numbers", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L446-L486
train
214,736
SoCo/SoCo
soco/music_library.py
MusicLibrary.search_track
def search_track(self, artist, album=None, track=None, full_album_art_uri=False): """Search for an artist, an artist's albums, or specific track. Args: artist (str): an artist's name. album (str, optional): an album name. Default `None`. track (str, optional): a track name. Default `None`. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance. """ subcategories = [artist] subcategories.append(album or '') # Perform the search result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, search_term=track, complete_result=True) result._metadata['search_type'] = 'search_track' return result
python
def search_track(self, artist, album=None, track=None, full_album_art_uri=False): """Search for an artist, an artist's albums, or specific track. Args: artist (str): an artist's name. album (str, optional): an album name. Default `None`. track (str, optional): a track name. Default `None`. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance. """ subcategories = [artist] subcategories.append(album or '') # Perform the search result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, search_term=track, complete_result=True) result._metadata['search_type'] = 'search_track' return result
[ "def", "search_track", "(", "self", ",", "artist", ",", "album", "=", "None", ",", "track", "=", "None", ",", "full_album_art_uri", "=", "False", ")", ":", "subcategories", "=", "[", "artist", "]", "subcategories", ".", "append", "(", "album", "or", "''"...
Search for an artist, an artist's albums, or specific track. Args: artist (str): an artist's name. album (str, optional): an album name. Default `None`. track (str, optional): a track name. Default `None`. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance.
[ "Search", "for", "an", "artist", "an", "artist", "s", "albums", "or", "specific", "track", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L506-L529
train
214,737
SoCo/SoCo
soco/music_library.py
MusicLibrary.get_albums_for_artist
def get_albums_for_artist(self, artist, full_album_art_uri=False): """Get an artist's albums. Args: artist (str): an artist's name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance. """ subcategories = [artist] result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, complete_result=True) reduced = [item for item in result if item.__class__ == DidlMusicAlbum] # It is necessary to update the list of items in two places, due to # a bug in SearchResult result[:] = reduced result._metadata.update({ 'item_list': reduced, 'search_type': 'albums_for_artist', 'number_returned': len(reduced), 'total_matches': len(reduced) }) return result
python
def get_albums_for_artist(self, artist, full_album_art_uri=False): """Get an artist's albums. Args: artist (str): an artist's name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance. """ subcategories = [artist] result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, complete_result=True) reduced = [item for item in result if item.__class__ == DidlMusicAlbum] # It is necessary to update the list of items in two places, due to # a bug in SearchResult result[:] = reduced result._metadata.update({ 'item_list': reduced, 'search_type': 'albums_for_artist', 'number_returned': len(reduced), 'total_matches': len(reduced) }) return result
[ "def", "get_albums_for_artist", "(", "self", ",", "artist", ",", "full_album_art_uri", "=", "False", ")", ":", "subcategories", "=", "[", "artist", "]", "result", "=", "self", ".", "get_album_artists", "(", "full_album_art_uri", "=", "full_album_art_uri", ",", "...
Get an artist's albums. Args: artist (str): an artist's name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance.
[ "Get", "an", "artist", "s", "albums", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L531-L558
train
214,738
SoCo/SoCo
soco/music_library.py
MusicLibrary.get_tracks_for_album
def get_tracks_for_album(self, artist, album, full_album_art_uri=False): """Get the tracks of an artist's album. Args: artist (str): an artist's name. album (str): an album name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance. """ subcategories = [artist, album] result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, complete_result=True) result._metadata['search_type'] = 'tracks_for_album' return result
python
def get_tracks_for_album(self, artist, album, full_album_art_uri=False): """Get the tracks of an artist's album. Args: artist (str): an artist's name. album (str): an album name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance. """ subcategories = [artist, album] result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, complete_result=True) result._metadata['search_type'] = 'tracks_for_album' return result
[ "def", "get_tracks_for_album", "(", "self", ",", "artist", ",", "album", ",", "full_album_art_uri", "=", "False", ")", ":", "subcategories", "=", "[", "artist", ",", "album", "]", "result", "=", "self", ".", "get_album_artists", "(", "full_album_art_uri", "=",...
Get the tracks of an artist's album. Args: artist (str): an artist's name. album (str): an album name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance.
[ "Get", "the", "tracks", "of", "an", "artist", "s", "album", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L560-L578
train
214,739
SoCo/SoCo
soco/discovery.py
any_soco
def any_soco(): """Return any visible soco device, for when it doesn't matter which. Try to obtain an existing instance, or use `discover` if necessary. Note that this assumes that the existing instance has not left the network. Returns: SoCo: A `SoCo` instance (or subclass if `config.SOCO_CLASS` is set, or `None` if no instances are found """ cls = config.SOCO_CLASS # pylint: disable=no-member, protected-access try: # Try to get the first pre-existing soco instance we know about, # as long as it is visible (i.e. not a bridge etc). Otherwise, # perform discovery (again, excluding invisibles) and return one of # those device = next(d for d in cls._instances[cls._class_group].values() if d.is_visible) except (KeyError, StopIteration): devices = discover() return None if devices is None else devices.pop() return device
python
def any_soco(): """Return any visible soco device, for when it doesn't matter which. Try to obtain an existing instance, or use `discover` if necessary. Note that this assumes that the existing instance has not left the network. Returns: SoCo: A `SoCo` instance (or subclass if `config.SOCO_CLASS` is set, or `None` if no instances are found """ cls = config.SOCO_CLASS # pylint: disable=no-member, protected-access try: # Try to get the first pre-existing soco instance we know about, # as long as it is visible (i.e. not a bridge etc). Otherwise, # perform discovery (again, excluding invisibles) and return one of # those device = next(d for d in cls._instances[cls._class_group].values() if d.is_visible) except (KeyError, StopIteration): devices = discover() return None if devices is None else devices.pop() return device
[ "def", "any_soco", "(", ")", ":", "cls", "=", "config", ".", "SOCO_CLASS", "# pylint: disable=no-member, protected-access", "try", ":", "# Try to get the first pre-existing soco instance we know about,", "# as long as it is visible (i.e. not a bridge etc). Otherwise,", "# perform disco...
Return any visible soco device, for when it doesn't matter which. Try to obtain an existing instance, or use `discover` if necessary. Note that this assumes that the existing instance has not left the network. Returns: SoCo: A `SoCo` instance (or subclass if `config.SOCO_CLASS` is set, or `None` if no instances are found
[ "Return", "any", "visible", "soco", "device", "for", "when", "it", "doesn", "t", "matter", "which", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/discovery.py#L188-L213
train
214,740
SoCo/SoCo
soco/services.py
Service.wrap_arguments
def wrap_arguments(args=None): """Wrap a list of tuples in xml ready to pass into a SOAP request. Args: args (list): a list of (name, value) tuples specifying the name of each argument and its value, eg ``[('InstanceID', 0), ('Speed', 1)]``. The value can be a string or something with a string representation. The arguments are escaped and wrapped in <name> and <value> tags. Example: >>> from soco import SoCo >>> device = SoCo('192.168.1.101') >>> s = Service(device) >>> print(s.wrap_arguments([('InstanceID', 0), ('Speed', 1)])) <InstanceID>0</InstanceID><Speed>1</Speed>' """ if args is None: args = [] tags = [] for name, value in args: tag = "<{name}>{value}</{name}>".format( name=name, value=escape("%s" % value, {'"': "&quot;"})) # % converts to unicode because we are using unicode literals. # Avoids use of 'unicode' function which does not exist in python 3 tags.append(tag) xml = "".join(tags) return xml
python
def wrap_arguments(args=None): """Wrap a list of tuples in xml ready to pass into a SOAP request. Args: args (list): a list of (name, value) tuples specifying the name of each argument and its value, eg ``[('InstanceID', 0), ('Speed', 1)]``. The value can be a string or something with a string representation. The arguments are escaped and wrapped in <name> and <value> tags. Example: >>> from soco import SoCo >>> device = SoCo('192.168.1.101') >>> s = Service(device) >>> print(s.wrap_arguments([('InstanceID', 0), ('Speed', 1)])) <InstanceID>0</InstanceID><Speed>1</Speed>' """ if args is None: args = [] tags = [] for name, value in args: tag = "<{name}>{value}</{name}>".format( name=name, value=escape("%s" % value, {'"': "&quot;"})) # % converts to unicode because we are using unicode literals. # Avoids use of 'unicode' function which does not exist in python 3 tags.append(tag) xml = "".join(tags) return xml
[ "def", "wrap_arguments", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "tags", "=", "[", "]", "for", "name", ",", "value", "in", "args", ":", "tag", "=", "\"<{name}>{value}</{name}>\"", ".", "format", "("...
Wrap a list of tuples in xml ready to pass into a SOAP request. Args: args (list): a list of (name, value) tuples specifying the name of each argument and its value, eg ``[('InstanceID', 0), ('Speed', 1)]``. The value can be a string or something with a string representation. The arguments are escaped and wrapped in <name> and <value> tags. Example: >>> from soco import SoCo >>> device = SoCo('192.168.1.101') >>> s = Service(device) >>> print(s.wrap_arguments([('InstanceID', 0), ('Speed', 1)])) <InstanceID>0</InstanceID><Speed>1</Speed>'
[ "Wrap", "a", "list", "of", "tuples", "in", "xml", "ready", "to", "pass", "into", "a", "SOAP", "request", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L233-L263
train
214,741
SoCo/SoCo
soco/services.py
Service.unwrap_arguments
def unwrap_arguments(xml_response): """Extract arguments and their values from a SOAP response. Args: xml_response (str): SOAP/xml response text (unicode, not utf-8). Returns: dict: a dict of ``{argument_name: value}`` items. """ # A UPnP SOAP response (including headers) looks like this: # HTTP/1.1 200 OK # CONTENT-LENGTH: bytes in body # CONTENT-TYPE: text/xml; charset="utf-8" DATE: when response was # generated # EXT: # SERVER: OS/version UPnP/1.0 product/version # # <?xml version="1.0"?> # <s:Envelope # xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" # s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> # <s:Body> # <u:actionNameResponse # xmlns:u="urn:schemas-upnp-org:service:serviceType:v"> # <argumentName>out arg value</argumentName> # ... other out args and their values go here, if any # </u:actionNameResponse> # </s:Body> # </s:Envelope> # Get all tags in order. Elementree (in python 2.x) seems to prefer to # be fed bytes, rather than unicode xml_response = xml_response.encode('utf-8') try: tree = XML.fromstring(xml_response) except XML.ParseError: # Try to filter illegal xml chars (as unicode), in case that is # the reason for the parse error filtered = illegal_xml_re.sub('', xml_response.decode('utf-8'))\ .encode('utf-8') tree = XML.fromstring(filtered) # Get the first child of the <Body> tag which will be # <{actionNameResponse}> (depends on what actionName is). Turn the # children of this into a {tagname, content} dict. XML unescaping # is carried out for us by elementree. action_response = tree.find( "{http://schemas.xmlsoap.org/soap/envelope/}Body")[0] return dict((i.tag, i.text or "") for i in action_response)
python
def unwrap_arguments(xml_response): """Extract arguments and their values from a SOAP response. Args: xml_response (str): SOAP/xml response text (unicode, not utf-8). Returns: dict: a dict of ``{argument_name: value}`` items. """ # A UPnP SOAP response (including headers) looks like this: # HTTP/1.1 200 OK # CONTENT-LENGTH: bytes in body # CONTENT-TYPE: text/xml; charset="utf-8" DATE: when response was # generated # EXT: # SERVER: OS/version UPnP/1.0 product/version # # <?xml version="1.0"?> # <s:Envelope # xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" # s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> # <s:Body> # <u:actionNameResponse # xmlns:u="urn:schemas-upnp-org:service:serviceType:v"> # <argumentName>out arg value</argumentName> # ... other out args and their values go here, if any # </u:actionNameResponse> # </s:Body> # </s:Envelope> # Get all tags in order. Elementree (in python 2.x) seems to prefer to # be fed bytes, rather than unicode xml_response = xml_response.encode('utf-8') try: tree = XML.fromstring(xml_response) except XML.ParseError: # Try to filter illegal xml chars (as unicode), in case that is # the reason for the parse error filtered = illegal_xml_re.sub('', xml_response.decode('utf-8'))\ .encode('utf-8') tree = XML.fromstring(filtered) # Get the first child of the <Body> tag which will be # <{actionNameResponse}> (depends on what actionName is). Turn the # children of this into a {tagname, content} dict. XML unescaping # is carried out for us by elementree. action_response = tree.find( "{http://schemas.xmlsoap.org/soap/envelope/}Body")[0] return dict((i.tag, i.text or "") for i in action_response)
[ "def", "unwrap_arguments", "(", "xml_response", ")", ":", "# A UPnP SOAP response (including headers) looks like this:", "# HTTP/1.1 200 OK", "# CONTENT-LENGTH: bytes in body", "# CONTENT-TYPE: text/xml; charset=\"utf-8\" DATE: when response was", "# generated", "# EXT:", "# SERVER: OS/versi...
Extract arguments and their values from a SOAP response. Args: xml_response (str): SOAP/xml response text (unicode, not utf-8). Returns: dict: a dict of ``{argument_name: value}`` items.
[ "Extract", "arguments", "and", "their", "values", "from", "a", "SOAP", "response", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L266-L316
train
214,742
SoCo/SoCo
soco/services.py
Service.compose_args
def compose_args(self, action_name, in_argdict): """Compose the argument list from an argument dictionary, with respect for default values. Args: action_name (str): The name of the action to be performed. in_argdict (dict): Arguments as a dict, eg ``{'InstanceID': 0, 'Speed': 1}. The values can be a string or something with a string representation. Returns: list: a list of ``(name, value)`` tuples. Raises: `AttributeError`: If this service does not support the action. `ValueError`: If the argument lists do not match the action signature. """ for action in self.actions: if action.name == action_name: # The found 'action' will be visible from outside the loop break else: raise AttributeError('Unknown Action: {0}'.format(action_name)) # Check for given argument names which do not occur in the expected # argument list # pylint: disable=undefined-loop-variable unexpected = set(in_argdict) - \ set(argument.name for argument in action.in_args) if unexpected: raise ValueError( "Unexpected argument '{0}'. Method signature: {1}" .format(next(iter(unexpected)), str(action)) ) # List the (name, value) tuples for each argument in the argument list composed = [] for argument in action.in_args: name = argument.name if name in in_argdict: composed.append((name, in_argdict[name])) continue if name in self.DEFAULT_ARGS: composed.append((name, self.DEFAULT_ARGS[name])) continue if argument.vartype.default is not None: composed.append((name, argument.vartype.default)) raise ValueError( "Missing argument '{0}'. Method signature: {1}" .format(argument.name, str(action)) ) return composed
python
def compose_args(self, action_name, in_argdict): """Compose the argument list from an argument dictionary, with respect for default values. Args: action_name (str): The name of the action to be performed. in_argdict (dict): Arguments as a dict, eg ``{'InstanceID': 0, 'Speed': 1}. The values can be a string or something with a string representation. Returns: list: a list of ``(name, value)`` tuples. Raises: `AttributeError`: If this service does not support the action. `ValueError`: If the argument lists do not match the action signature. """ for action in self.actions: if action.name == action_name: # The found 'action' will be visible from outside the loop break else: raise AttributeError('Unknown Action: {0}'.format(action_name)) # Check for given argument names which do not occur in the expected # argument list # pylint: disable=undefined-loop-variable unexpected = set(in_argdict) - \ set(argument.name for argument in action.in_args) if unexpected: raise ValueError( "Unexpected argument '{0}'. Method signature: {1}" .format(next(iter(unexpected)), str(action)) ) # List the (name, value) tuples for each argument in the argument list composed = [] for argument in action.in_args: name = argument.name if name in in_argdict: composed.append((name, in_argdict[name])) continue if name in self.DEFAULT_ARGS: composed.append((name, self.DEFAULT_ARGS[name])) continue if argument.vartype.default is not None: composed.append((name, argument.vartype.default)) raise ValueError( "Missing argument '{0}'. Method signature: {1}" .format(argument.name, str(action)) ) return composed
[ "def", "compose_args", "(", "self", ",", "action_name", ",", "in_argdict", ")", ":", "for", "action", "in", "self", ".", "actions", ":", "if", "action", ".", "name", "==", "action_name", ":", "# The found 'action' will be visible from outside the loop", "break", "...
Compose the argument list from an argument dictionary, with respect for default values. Args: action_name (str): The name of the action to be performed. in_argdict (dict): Arguments as a dict, eg ``{'InstanceID': 0, 'Speed': 1}. The values can be a string or something with a string representation. Returns: list: a list of ``(name, value)`` tuples. Raises: `AttributeError`: If this service does not support the action. `ValueError`: If the argument lists do not match the action signature.
[ "Compose", "the", "argument", "list", "from", "an", "argument", "dictionary", "with", "respect", "for", "default", "values", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L318-L371
train
214,743
SoCo/SoCo
soco/services.py
Service.build_command
def build_command(self, action, args=None): """Build a SOAP request. Args: action (str): the name of an action (a string as specified in the service description XML file) to be sent. args (list, optional): Relevant arguments as a list of (name, value) tuples. Returns: tuple: a tuple containing the POST headers (as a dict) and a string containing the relevant SOAP body. Does not set content-length, or host headers, which are completed upon sending. """ # A complete request should look something like this: # POST path of control URL HTTP/1.1 # HOST: host of control URL:port of control URL # CONTENT-LENGTH: bytes in body # CONTENT-TYPE: text/xml; charset="utf-8" # SOAPACTION: "urn:schemas-upnp-org:service:serviceType:v#actionName" # # <?xml version="1.0"?> # <s:Envelope # xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" # s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> # <s:Body> # <u:actionName # xmlns:u="urn:schemas-upnp-org:service:serviceType:v"> # <argumentName>in arg value</argumentName> # ... other in args and their values go here, if any # </u:actionName> # </s:Body> # </s:Envelope> arguments = self.wrap_arguments(args) body = self.soap_body_template.format( arguments=arguments, action=action, service_type=self.service_type, version=self.version) soap_action_template = \ "urn:schemas-upnp-org:service:{service_type}:{version}#{action}" soap_action = soap_action_template.format( service_type=self.service_type, version=self.version, action=action) headers = {'Content-Type': 'text/xml; charset="utf-8"', 'SOAPACTION': soap_action} # Note that although we set the charset to utf-8 here, in fact the # body is still unicode. It will only be converted to bytes when it # is set over the network return (headers, body)
python
def build_command(self, action, args=None): """Build a SOAP request. Args: action (str): the name of an action (a string as specified in the service description XML file) to be sent. args (list, optional): Relevant arguments as a list of (name, value) tuples. Returns: tuple: a tuple containing the POST headers (as a dict) and a string containing the relevant SOAP body. Does not set content-length, or host headers, which are completed upon sending. """ # A complete request should look something like this: # POST path of control URL HTTP/1.1 # HOST: host of control URL:port of control URL # CONTENT-LENGTH: bytes in body # CONTENT-TYPE: text/xml; charset="utf-8" # SOAPACTION: "urn:schemas-upnp-org:service:serviceType:v#actionName" # # <?xml version="1.0"?> # <s:Envelope # xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" # s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> # <s:Body> # <u:actionName # xmlns:u="urn:schemas-upnp-org:service:serviceType:v"> # <argumentName>in arg value</argumentName> # ... other in args and their values go here, if any # </u:actionName> # </s:Body> # </s:Envelope> arguments = self.wrap_arguments(args) body = self.soap_body_template.format( arguments=arguments, action=action, service_type=self.service_type, version=self.version) soap_action_template = \ "urn:schemas-upnp-org:service:{service_type}:{version}#{action}" soap_action = soap_action_template.format( service_type=self.service_type, version=self.version, action=action) headers = {'Content-Type': 'text/xml; charset="utf-8"', 'SOAPACTION': soap_action} # Note that although we set the charset to utf-8 here, in fact the # body is still unicode. It will only be converted to bytes when it # is set over the network return (headers, body)
[ "def", "build_command", "(", "self", ",", "action", ",", "args", "=", "None", ")", ":", "# A complete request should look something like this:", "# POST path of control URL HTTP/1.1", "# HOST: host of control URL:port of control URL", "# CONTENT-LENGTH: bytes in body", "# CONTENT-TYP...
Build a SOAP request. Args: action (str): the name of an action (a string as specified in the service description XML file) to be sent. args (list, optional): Relevant arguments as a list of (name, value) tuples. Returns: tuple: a tuple containing the POST headers (as a dict) and a string containing the relevant SOAP body. Does not set content-length, or host headers, which are completed upon sending.
[ "Build", "a", "SOAP", "request", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L373-L424
train
214,744
SoCo/SoCo
soco/services.py
Service.send_command
def send_command(self, action, args=None, cache=None, cache_timeout=None, **kwargs): """Send a command to a Sonos device. Args: action (str): the name of an action (a string as specified in the service description XML file) to be sent. args (list, optional): Relevant arguments as a list of (name, value) tuples, as an alternative to ``kwargs``. cache (Cache): A cache is operated so that the result will be stored for up to ``cache_timeout`` seconds, and a subsequent call with the same arguments within that period will be returned from the cache, saving a further network call. The cache may be invalidated or even primed from another thread (for example if a UPnP event is received to indicate that the state of the Sonos device has changed). If ``cache_timeout`` is missing or `None`, the cache will use a default value (which may be 0 - see `cache`). By default, the cache identified by the service's `cache` attribute will be used, but a different cache object may be specified in the `cache` parameter. kwargs: Relevant arguments for the command. Returns: dict: a dict of ``{argument_name, value}`` items. Raises: `AttributeError`: If this service does not support the action. `ValueError`: If the argument lists do not match the action signature. `SoCoUPnPException`: if a SOAP error occurs. `UnknownSoCoException`: if an unknonwn UPnP error occurs. `requests.exceptions.HTTPError`: if an http error occurs. """ if args is None: args = self.compose_args(action, kwargs) if cache is None: cache = self.cache result = cache.get(action, args) if result is not None: log.debug("Cache hit") return result # Cache miss, so go ahead and make a network call headers, body = self.build_command(action, args) log.info("Sending %s %s to %s", action, args, self.soco.ip_address) log.debug("Sending %s, %s", headers, prettify(body)) # Convert the body to bytes, and send it. response = requests.post( self.base_url + self.control_url, headers=headers, data=body.encode('utf-8') ) log.debug("Received %s, %s", response.headers, response.text) status = response.status_code log.info( "Received status %s from %s", status, self.soco.ip_address) if status == 200: # The response is good. Get the output params, and return them. # NB an empty dict is a valid result. It just means that no # params are returned. By using response.text, we rely upon # the requests library to convert to unicode for us. result = self.unwrap_arguments(response.text) or True # Store in the cache. There is no need to do this if there was an # error, since we would want to try a network call again. cache.put(result, action, args, timeout=cache_timeout) return result elif status == 500: # Internal server error. UPnP requires this to be returned if the # device does not like the action for some reason. The returned # content will be a SOAP Fault. Parse it and raise an error. try: self.handle_upnp_error(response.text) except Exception as exc: log.exception(str(exc)) raise else: # Something else has gone wrong. Probably a network error. Let # Requests handle it response.raise_for_status() return None
python
def send_command(self, action, args=None, cache=None, cache_timeout=None, **kwargs): """Send a command to a Sonos device. Args: action (str): the name of an action (a string as specified in the service description XML file) to be sent. args (list, optional): Relevant arguments as a list of (name, value) tuples, as an alternative to ``kwargs``. cache (Cache): A cache is operated so that the result will be stored for up to ``cache_timeout`` seconds, and a subsequent call with the same arguments within that period will be returned from the cache, saving a further network call. The cache may be invalidated or even primed from another thread (for example if a UPnP event is received to indicate that the state of the Sonos device has changed). If ``cache_timeout`` is missing or `None`, the cache will use a default value (which may be 0 - see `cache`). By default, the cache identified by the service's `cache` attribute will be used, but a different cache object may be specified in the `cache` parameter. kwargs: Relevant arguments for the command. Returns: dict: a dict of ``{argument_name, value}`` items. Raises: `AttributeError`: If this service does not support the action. `ValueError`: If the argument lists do not match the action signature. `SoCoUPnPException`: if a SOAP error occurs. `UnknownSoCoException`: if an unknonwn UPnP error occurs. `requests.exceptions.HTTPError`: if an http error occurs. """ if args is None: args = self.compose_args(action, kwargs) if cache is None: cache = self.cache result = cache.get(action, args) if result is not None: log.debug("Cache hit") return result # Cache miss, so go ahead and make a network call headers, body = self.build_command(action, args) log.info("Sending %s %s to %s", action, args, self.soco.ip_address) log.debug("Sending %s, %s", headers, prettify(body)) # Convert the body to bytes, and send it. response = requests.post( self.base_url + self.control_url, headers=headers, data=body.encode('utf-8') ) log.debug("Received %s, %s", response.headers, response.text) status = response.status_code log.info( "Received status %s from %s", status, self.soco.ip_address) if status == 200: # The response is good. Get the output params, and return them. # NB an empty dict is a valid result. It just means that no # params are returned. By using response.text, we rely upon # the requests library to convert to unicode for us. result = self.unwrap_arguments(response.text) or True # Store in the cache. There is no need to do this if there was an # error, since we would want to try a network call again. cache.put(result, action, args, timeout=cache_timeout) return result elif status == 500: # Internal server error. UPnP requires this to be returned if the # device does not like the action for some reason. The returned # content will be a SOAP Fault. Parse it and raise an error. try: self.handle_upnp_error(response.text) except Exception as exc: log.exception(str(exc)) raise else: # Something else has gone wrong. Probably a network error. Let # Requests handle it response.raise_for_status() return None
[ "def", "send_command", "(", "self", ",", "action", ",", "args", "=", "None", ",", "cache", "=", "None", ",", "cache_timeout", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "args", "is", "None", ":", "args", "=", "self", ".", "compose_args", ...
Send a command to a Sonos device. Args: action (str): the name of an action (a string as specified in the service description XML file) to be sent. args (list, optional): Relevant arguments as a list of (name, value) tuples, as an alternative to ``kwargs``. cache (Cache): A cache is operated so that the result will be stored for up to ``cache_timeout`` seconds, and a subsequent call with the same arguments within that period will be returned from the cache, saving a further network call. The cache may be invalidated or even primed from another thread (for example if a UPnP event is received to indicate that the state of the Sonos device has changed). If ``cache_timeout`` is missing or `None`, the cache will use a default value (which may be 0 - see `cache`). By default, the cache identified by the service's `cache` attribute will be used, but a different cache object may be specified in the `cache` parameter. kwargs: Relevant arguments for the command. Returns: dict: a dict of ``{argument_name, value}`` items. Raises: `AttributeError`: If this service does not support the action. `ValueError`: If the argument lists do not match the action signature. `SoCoUPnPException`: if a SOAP error occurs. `UnknownSoCoException`: if an unknonwn UPnP error occurs. `requests.exceptions.HTTPError`: if an http error occurs.
[ "Send", "a", "command", "to", "a", "Sonos", "device", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L426-L506
train
214,745
SoCo/SoCo
soco/services.py
Service.handle_upnp_error
def handle_upnp_error(self, xml_error): """Disect a UPnP error, and raise an appropriate exception. Args: xml_error (str): a unicode string containing the body of the UPnP/SOAP Fault response. Raises an exception containing the error code. """ # An error code looks something like this: # HTTP/1.1 500 Internal Server Error # CONTENT-LENGTH: bytes in body # CONTENT-TYPE: text/xml; charset="utf-8" # DATE: when response was generated # EXT: # SERVER: OS/version UPnP/1.0 product/version # <?xml version="1.0"?> # <s:Envelope # xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" # s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> # <s:Body> # <s:Fault> # <faultcode>s:Client</faultcode> # <faultstring>UPnPError</faultstring> # <detail> # <UPnPError xmlns="urn:schemas-upnp-org:control-1-0"> # <errorCode>error code</errorCode> # <errorDescription>error string</errorDescription> # </UPnPError> # </detail> # </s:Fault> # </s:Body> # </s:Envelope> # # All that matters for our purposes is the errorCode. # errorDescription is not required, and Sonos does not seem to use it. # NB need to encode unicode strings before passing to ElementTree xml_error = xml_error.encode('utf-8') error = XML.fromstring(xml_error) log.debug("Error %s", xml_error) error_code = error.findtext( './/{urn:schemas-upnp-org:control-1-0}errorCode') if error_code is not None: description = self.UPNP_ERRORS.get(int(error_code), '') raise SoCoUPnPException( message='UPnP Error {} received: {} from {}'.format( error_code, description, self.soco.ip_address), error_code=error_code, error_description=description, error_xml=xml_error ) else: # Unknown error, so just return the entire response log.error("Unknown error received from %s", self.soco.ip_address) raise UnknownSoCoException(xml_error)
python
def handle_upnp_error(self, xml_error): """Disect a UPnP error, and raise an appropriate exception. Args: xml_error (str): a unicode string containing the body of the UPnP/SOAP Fault response. Raises an exception containing the error code. """ # An error code looks something like this: # HTTP/1.1 500 Internal Server Error # CONTENT-LENGTH: bytes in body # CONTENT-TYPE: text/xml; charset="utf-8" # DATE: when response was generated # EXT: # SERVER: OS/version UPnP/1.0 product/version # <?xml version="1.0"?> # <s:Envelope # xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" # s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> # <s:Body> # <s:Fault> # <faultcode>s:Client</faultcode> # <faultstring>UPnPError</faultstring> # <detail> # <UPnPError xmlns="urn:schemas-upnp-org:control-1-0"> # <errorCode>error code</errorCode> # <errorDescription>error string</errorDescription> # </UPnPError> # </detail> # </s:Fault> # </s:Body> # </s:Envelope> # # All that matters for our purposes is the errorCode. # errorDescription is not required, and Sonos does not seem to use it. # NB need to encode unicode strings before passing to ElementTree xml_error = xml_error.encode('utf-8') error = XML.fromstring(xml_error) log.debug("Error %s", xml_error) error_code = error.findtext( './/{urn:schemas-upnp-org:control-1-0}errorCode') if error_code is not None: description = self.UPNP_ERRORS.get(int(error_code), '') raise SoCoUPnPException( message='UPnP Error {} received: {} from {}'.format( error_code, description, self.soco.ip_address), error_code=error_code, error_description=description, error_xml=xml_error ) else: # Unknown error, so just return the entire response log.error("Unknown error received from %s", self.soco.ip_address) raise UnknownSoCoException(xml_error)
[ "def", "handle_upnp_error", "(", "self", ",", "xml_error", ")", ":", "# An error code looks something like this:", "# HTTP/1.1 500 Internal Server Error", "# CONTENT-LENGTH: bytes in body", "# CONTENT-TYPE: text/xml; charset=\"utf-8\"", "# DATE: when response was generated", "# EXT:", "#...
Disect a UPnP error, and raise an appropriate exception. Args: xml_error (str): a unicode string containing the body of the UPnP/SOAP Fault response. Raises an exception containing the error code.
[ "Disect", "a", "UPnP", "error", "and", "raise", "an", "appropriate", "exception", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L508-L565
train
214,746
SoCo/SoCo
soco/services.py
Service.subscribe
def subscribe( self, requested_timeout=None, auto_renew=False, event_queue=None): """Subscribe to the service's events. Args: requested_timeout (int, optional): If requested_timeout is provided, a subscription valid for that number of seconds will be requested, but not guaranteed. Check `Subscription.timeout` on return to find out what period of validity is actually allocated. auto_renew (bool): If auto_renew is `True`, the subscription will automatically be renewed just before it expires, if possible. Default is `False`. event_queue (:class:`~queue.Queue`): a thread-safe queue object on which received events will be put. If not specified, a (:class:`~queue.Queue`) will be created and used. Returns: `Subscription`: an insance of `Subscription`, representing the new subscription. To unsubscribe, call the `unsubscribe` method on the returned object. """ subscription = Subscription( self, event_queue) subscription.subscribe( requested_timeout=requested_timeout, auto_renew=auto_renew) return subscription
python
def subscribe( self, requested_timeout=None, auto_renew=False, event_queue=None): """Subscribe to the service's events. Args: requested_timeout (int, optional): If requested_timeout is provided, a subscription valid for that number of seconds will be requested, but not guaranteed. Check `Subscription.timeout` on return to find out what period of validity is actually allocated. auto_renew (bool): If auto_renew is `True`, the subscription will automatically be renewed just before it expires, if possible. Default is `False`. event_queue (:class:`~queue.Queue`): a thread-safe queue object on which received events will be put. If not specified, a (:class:`~queue.Queue`) will be created and used. Returns: `Subscription`: an insance of `Subscription`, representing the new subscription. To unsubscribe, call the `unsubscribe` method on the returned object. """ subscription = Subscription( self, event_queue) subscription.subscribe( requested_timeout=requested_timeout, auto_renew=auto_renew) return subscription
[ "def", "subscribe", "(", "self", ",", "requested_timeout", "=", "None", ",", "auto_renew", "=", "False", ",", "event_queue", "=", "None", ")", ":", "subscription", "=", "Subscription", "(", "self", ",", "event_queue", ")", "subscription", ".", "subscribe", "...
Subscribe to the service's events. Args: requested_timeout (int, optional): If requested_timeout is provided, a subscription valid for that number of seconds will be requested, but not guaranteed. Check `Subscription.timeout` on return to find out what period of validity is actually allocated. auto_renew (bool): If auto_renew is `True`, the subscription will automatically be renewed just before it expires, if possible. Default is `False`. event_queue (:class:`~queue.Queue`): a thread-safe queue object on which received events will be put. If not specified, a (:class:`~queue.Queue`) will be created and used. Returns: `Subscription`: an insance of `Subscription`, representing the new subscription. To unsubscribe, call the `unsubscribe` method on the returned object.
[ "Subscribe", "to", "the", "service", "s", "events", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L567-L595
train
214,747
SoCo/SoCo
soco/services.py
Service.actions
def actions(self): """The service's actions with their arguments. Returns: list(`Action`): A list of Action namedtuples, consisting of action_name (str), in_args (list of Argument namedtuples, consisting of name and argtype), and out_args (ditto). The return value looks like this:: [ Action( name='GetMute', in_args=[ Argument(name='InstanceID', ...), Argument( name='Channel', vartype='string', list=['Master', 'LF', 'RF', 'SpeakerOnly'], range=None ) ], out_args=[ Argument(name='CurrentMute, ...) ] ) Action(...) ] Its string representation will look like this:: GetMute(InstanceID: ui4, Channel: [Master, LF, RF, SpeakerOnly]) \ -> {CurrentMute: boolean} """ if self._actions is None: self._actions = list(self.iter_actions()) return self._actions
python
def actions(self): """The service's actions with their arguments. Returns: list(`Action`): A list of Action namedtuples, consisting of action_name (str), in_args (list of Argument namedtuples, consisting of name and argtype), and out_args (ditto). The return value looks like this:: [ Action( name='GetMute', in_args=[ Argument(name='InstanceID', ...), Argument( name='Channel', vartype='string', list=['Master', 'LF', 'RF', 'SpeakerOnly'], range=None ) ], out_args=[ Argument(name='CurrentMute, ...) ] ) Action(...) ] Its string representation will look like this:: GetMute(InstanceID: ui4, Channel: [Master, LF, RF, SpeakerOnly]) \ -> {CurrentMute: boolean} """ if self._actions is None: self._actions = list(self.iter_actions()) return self._actions
[ "def", "actions", "(", "self", ")", ":", "if", "self", ".", "_actions", "is", "None", ":", "self", ".", "_actions", "=", "list", "(", "self", ".", "iter_actions", "(", ")", ")", "return", "self", ".", "_actions" ]
The service's actions with their arguments. Returns: list(`Action`): A list of Action namedtuples, consisting of action_name (str), in_args (list of Argument namedtuples, consisting of name and argtype), and out_args (ditto). The return value looks like this:: [ Action( name='GetMute', in_args=[ Argument(name='InstanceID', ...), Argument( name='Channel', vartype='string', list=['Master', 'LF', 'RF', 'SpeakerOnly'], range=None ) ], out_args=[ Argument(name='CurrentMute, ...) ] ) Action(...) ] Its string representation will look like this:: GetMute(InstanceID: ui4, Channel: [Master, LF, RF, SpeakerOnly]) \ -> {CurrentMute: boolean}
[ "The", "service", "s", "actions", "with", "their", "arguments", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L616-L650
train
214,748
SoCo/SoCo
soco/services.py
Service.event_vars
def event_vars(self): """The service's eventable variables. Returns: list(tuple): A list of (variable name, data type) tuples. """ if self._event_vars is None: self._event_vars = list(self.iter_event_vars()) return self._event_vars
python
def event_vars(self): """The service's eventable variables. Returns: list(tuple): A list of (variable name, data type) tuples. """ if self._event_vars is None: self._event_vars = list(self.iter_event_vars()) return self._event_vars
[ "def", "event_vars", "(", "self", ")", ":", "if", "self", ".", "_event_vars", "is", "None", ":", "self", ".", "_event_vars", "=", "list", "(", "self", ".", "iter_event_vars", "(", ")", ")", "return", "self", ".", "_event_vars" ]
The service's eventable variables. Returns: list(tuple): A list of (variable name, data type) tuples.
[ "The", "service", "s", "eventable", "variables", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L719-L727
train
214,749
SoCo/SoCo
soco/services.py
Service.iter_event_vars
def iter_event_vars(self): """Yield the services eventable variables. Yields: `tuple`: a tuple of (variable name, data type). """ # pylint: disable=invalid-name ns = '{urn:schemas-upnp-org:service-1-0}' scpd_body = requests.get(self.base_url + self.scpd_url).text tree = XML.fromstring(scpd_body.encode('utf-8')) # parse the state variables to get the relevant variable types statevars = tree.findall('{}stateVariable'.format(ns)) for state in statevars: # We are only interested if 'sendEvents' is 'yes', i.e this # is an eventable variable if state.attrib['sendEvents'] == "yes": name = state.findtext('{}name'.format(ns)) vartype = state.findtext('{}dataType'.format(ns)) yield (name, vartype)
python
def iter_event_vars(self): """Yield the services eventable variables. Yields: `tuple`: a tuple of (variable name, data type). """ # pylint: disable=invalid-name ns = '{urn:schemas-upnp-org:service-1-0}' scpd_body = requests.get(self.base_url + self.scpd_url).text tree = XML.fromstring(scpd_body.encode('utf-8')) # parse the state variables to get the relevant variable types statevars = tree.findall('{}stateVariable'.format(ns)) for state in statevars: # We are only interested if 'sendEvents' is 'yes', i.e this # is an eventable variable if state.attrib['sendEvents'] == "yes": name = state.findtext('{}name'.format(ns)) vartype = state.findtext('{}dataType'.format(ns)) yield (name, vartype)
[ "def", "iter_event_vars", "(", "self", ")", ":", "# pylint: disable=invalid-name", "ns", "=", "'{urn:schemas-upnp-org:service-1-0}'", "scpd_body", "=", "requests", ".", "get", "(", "self", ".", "base_url", "+", "self", ".", "scpd_url", ")", ".", "text", "tree", ...
Yield the services eventable variables. Yields: `tuple`: a tuple of (variable name, data type).
[ "Yield", "the", "services", "eventable", "variables", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L729-L748
train
214,750
SoCo/SoCo
soco/services.py
ZoneGroupTopology.GetZoneGroupState
def GetZoneGroupState(self, *args, **kwargs): """Overrides default handling to use the global shared zone group state cache, unless another cache is specified.""" kwargs['cache'] = kwargs.get('cache', zone_group_state_shared_cache) return self.send_command('GetZoneGroupState', *args, **kwargs)
python
def GetZoneGroupState(self, *args, **kwargs): """Overrides default handling to use the global shared zone group state cache, unless another cache is specified.""" kwargs['cache'] = kwargs.get('cache', zone_group_state_shared_cache) return self.send_command('GetZoneGroupState', *args, **kwargs)
[ "def", "GetZoneGroupState", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'cache'", "]", "=", "kwargs", ".", "get", "(", "'cache'", ",", "zone_group_state_shared_cache", ")", "return", "self", ".", "send_command", "(", ...
Overrides default handling to use the global shared zone group state cache, unless another cache is specified.
[ "Overrides", "default", "handling", "to", "use", "the", "global", "shared", "zone", "group", "state", "cache", "unless", "another", "cache", "is", "specified", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L786-L790
train
214,751
SoCo/SoCo
examples/play_local_files/play_local_files.py
add_random_file_from_present_folder
def add_random_file_from_present_folder(machine_ip, port, zone): """Add a random non-py file from this folder and subfolders to soco""" # Make a list of music files, right now it is done by collection all files # below the current folder whose extension does not start with .py # This will probably need to be modded for other pusposes. music_files = [] print('Looking for music files') for path, dirs, files in os.walk('.'): for file_ in files: if not os.path.splitext(file_)[1].startswith('.py'): music_files.append(os.path.relpath(os.path.join(path, file_))) print('Found:', music_files[-1]) random_file = choice(music_files) # urlencode all the path parts (but not the /'s) random_file = os.path.join( *[quote(part) for part in os.path.split(random_file)] ) print('\nPlaying random file:', random_file) netpath = 'http://{}:{}/{}'.format(machine_ip, port, random_file) number_in_queue = zone.add_uri_to_queue(netpath) # play_from_queue indexes are 0-based zone.play_from_queue(number_in_queue - 1)
python
def add_random_file_from_present_folder(machine_ip, port, zone): """Add a random non-py file from this folder and subfolders to soco""" # Make a list of music files, right now it is done by collection all files # below the current folder whose extension does not start with .py # This will probably need to be modded for other pusposes. music_files = [] print('Looking for music files') for path, dirs, files in os.walk('.'): for file_ in files: if not os.path.splitext(file_)[1].startswith('.py'): music_files.append(os.path.relpath(os.path.join(path, file_))) print('Found:', music_files[-1]) random_file = choice(music_files) # urlencode all the path parts (but not the /'s) random_file = os.path.join( *[quote(part) for part in os.path.split(random_file)] ) print('\nPlaying random file:', random_file) netpath = 'http://{}:{}/{}'.format(machine_ip, port, random_file) number_in_queue = zone.add_uri_to_queue(netpath) # play_from_queue indexes are 0-based zone.play_from_queue(number_in_queue - 1)
[ "def", "add_random_file_from_present_folder", "(", "machine_ip", ",", "port", ",", "zone", ")", ":", "# Make a list of music files, right now it is done by collection all files", "# below the current folder whose extension does not start with .py", "# This will probably need to be modded for...
Add a random non-py file from this folder and subfolders to soco
[ "Add", "a", "random", "non", "-", "py", "file", "from", "this", "folder", "and", "subfolders", "to", "soco" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/examples/play_local_files/play_local_files.py#L64-L87
train
214,752
SoCo/SoCo
soco/data_structures.py
DidlResource.to_element
def to_element(self): """Return an ElementTree Element based on this resource. Returns: ~xml.etree.ElementTree.Element: an Element. """ if not self.protocol_info: raise DIDLMetadataError('Could not create Element for this' 'resource:' 'protocolInfo not set (required).') root = XML.Element('res') # Required root.attrib['protocolInfo'] = self.protocol_info # Optional if self.import_uri is not None: root.attrib['importUri'] = self.import_uri if self.size is not None: root.attrib['size'] = str(self.size) if self.duration is not None: root.attrib['duration'] = self.duration if self.bitrate is not None: root.attrib['bitrate'] = str(self.bitrate) if self.sample_frequency is not None: root.attrib['sampleFrequency'] = str(self.sample_frequency) if self.bits_per_sample is not None: root.attrib['bitsPerSample'] = str(self.bits_per_sample) if self.nr_audio_channels is not None: root.attrib['nrAudioChannels'] = str(self.nr_audio_channels) if self.resolution is not None: root.attrib['resolution'] = self.resolution if self.color_depth is not None: root.attrib['colorDepth'] = str(self.color_depth) if self.protection is not None: root.attrib['protection'] = self.protection root.text = self.uri return root
python
def to_element(self): """Return an ElementTree Element based on this resource. Returns: ~xml.etree.ElementTree.Element: an Element. """ if not self.protocol_info: raise DIDLMetadataError('Could not create Element for this' 'resource:' 'protocolInfo not set (required).') root = XML.Element('res') # Required root.attrib['protocolInfo'] = self.protocol_info # Optional if self.import_uri is not None: root.attrib['importUri'] = self.import_uri if self.size is not None: root.attrib['size'] = str(self.size) if self.duration is not None: root.attrib['duration'] = self.duration if self.bitrate is not None: root.attrib['bitrate'] = str(self.bitrate) if self.sample_frequency is not None: root.attrib['sampleFrequency'] = str(self.sample_frequency) if self.bits_per_sample is not None: root.attrib['bitsPerSample'] = str(self.bits_per_sample) if self.nr_audio_channels is not None: root.attrib['nrAudioChannels'] = str(self.nr_audio_channels) if self.resolution is not None: root.attrib['resolution'] = self.resolution if self.color_depth is not None: root.attrib['colorDepth'] = str(self.color_depth) if self.protection is not None: root.attrib['protection'] = self.protection root.text = self.uri return root
[ "def", "to_element", "(", "self", ")", ":", "if", "not", "self", ".", "protocol_info", ":", "raise", "DIDLMetadataError", "(", "'Could not create Element for this'", "'resource:'", "'protocolInfo not set (required).'", ")", "root", "=", "XML", ".", "Element", "(", "...
Return an ElementTree Element based on this resource. Returns: ~xml.etree.ElementTree.Element: an Element.
[ "Return", "an", "ElementTree", "Element", "based", "on", "this", "resource", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures.py#L199-L236
train
214,753
SoCo/SoCo
soco/data_structures.py
DidlResource.to_dict
def to_dict(self, remove_nones=False): """Return a dict representation of the `DidlResource`. Args: remove_nones (bool, optional): Optionally remove dictionary elements when their value is `None`. Returns: dict: a dict representing the `DidlResource` """ content = { 'uri': self.uri, 'protocol_info': self.protocol_info, 'import_uri': self.import_uri, 'size': self.size, 'duration': self.duration, 'bitrate': self.bitrate, 'sample_frequency': self.sample_frequency, 'bits_per_sample': self.bits_per_sample, 'nr_audio_channels': self.nr_audio_channels, 'resolution': self.resolution, 'color_depth': self.color_depth, 'protection': self.protection, } if remove_nones: # delete any elements that have a value of None to optimize size # of the returned structure nones = [k for k in content if content[k] is None] for k in nones: del content[k] return content
python
def to_dict(self, remove_nones=False): """Return a dict representation of the `DidlResource`. Args: remove_nones (bool, optional): Optionally remove dictionary elements when their value is `None`. Returns: dict: a dict representing the `DidlResource` """ content = { 'uri': self.uri, 'protocol_info': self.protocol_info, 'import_uri': self.import_uri, 'size': self.size, 'duration': self.duration, 'bitrate': self.bitrate, 'sample_frequency': self.sample_frequency, 'bits_per_sample': self.bits_per_sample, 'nr_audio_channels': self.nr_audio_channels, 'resolution': self.resolution, 'color_depth': self.color_depth, 'protection': self.protection, } if remove_nones: # delete any elements that have a value of None to optimize size # of the returned structure nones = [k for k in content if content[k] is None] for k in nones: del content[k] return content
[ "def", "to_dict", "(", "self", ",", "remove_nones", "=", "False", ")", ":", "content", "=", "{", "'uri'", ":", "self", ".", "uri", ",", "'protocol_info'", ":", "self", ".", "protocol_info", ",", "'import_uri'", ":", "self", ".", "import_uri", ",", "'size...
Return a dict representation of the `DidlResource`. Args: remove_nones (bool, optional): Optionally remove dictionary elements when their value is `None`. Returns: dict: a dict representing the `DidlResource`
[ "Return", "a", "dict", "representation", "of", "the", "DidlResource", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures.py#L238-L268
train
214,754
SoCo/SoCo
soco/data_structures.py
DidlObject.from_element
def from_element(cls, element): # pylint: disable=R0914 """Create an instance of this class from an ElementTree xml Element. An alternative constructor. The element must be a DIDL-Lite <item> or <container> element, and must be properly namespaced. Args: xml (~xml.etree.ElementTree.Element): An :class:`~xml.etree.ElementTree.Element` object. """ # We used to check here that we have the right sort of element, # ie a container or an item. But Sonos seems to use both # indiscriminately, eg a playlistContainer can be an item or a # container. So we now just check that it is one or the other. tag = element.tag if not (tag.endswith('item') or tag.endswith('container')): raise DIDLMetadataError( "Wrong element. Expected <item> or <container>," " got <{0}> for class {1}'".format( tag, cls.item_class)) # and that the upnp matches what we are expecting item_class = element.find(ns_tag('upnp', 'class')).text # In case this class has an # specified unofficial # subclass, ignore it by stripping it from item_class if '.#' in item_class: item_class = item_class[:item_class.find('.#')] if item_class != cls.item_class: raise DIDLMetadataError( "UPnP class is incorrect. Expected '{0}'," " got '{1}'".format(cls.item_class, item_class)) # parent_id, item_id and restricted are stored as attributes on the # element item_id = element.get('id', None) if item_id is None: raise DIDLMetadataError("Missing id attribute") item_id = really_unicode(item_id) parent_id = element.get('parentID', None) if parent_id is None: raise DIDLMetadataError("Missing parentID attribute") parent_id = really_unicode(parent_id) # CAUTION: This implementation deviates from the spec. # Elements are normally required to have a `restricted` tag, but # Spotify Direct violates this. To make it work, a missing restricted # tag is interpreted as `restricted = True`. restricted = element.get('restricted', None) restricted = False if restricted in [0, 'false', 'False'] else True # Similarily, all elements should have a title tag, but Spotify Direct # does not comply title_elt = element.find(ns_tag('dc', 'title')) if title_elt is None or not title_elt.text: title = '' else: title = really_unicode(title_elt.text) # Deal with any resource elements resources = [] for res_elt in element.findall(ns_tag('', 'res')): resources.append( DidlResource.from_element(res_elt)) # and the desc element (There is only one in Sonos) desc = element.findtext(ns_tag('', 'desc')) # Get values of the elements listed in _translation and add them to # the content dict content = {} for key, value in cls._translation.items(): result = element.findtext(ns_tag(*value)) if result is not None: # We store info as unicode internally. content[key] = really_unicode(result) # Convert type for original track number if content.get('original_track_number') is not None: content['original_track_number'] = \ int(content['original_track_number']) # Now pass the content dict we have just built to the main # constructor, as kwargs, to create the object return cls(title=title, parent_id=parent_id, item_id=item_id, restricted=restricted, resources=resources, desc=desc, **content)
python
def from_element(cls, element): # pylint: disable=R0914 """Create an instance of this class from an ElementTree xml Element. An alternative constructor. The element must be a DIDL-Lite <item> or <container> element, and must be properly namespaced. Args: xml (~xml.etree.ElementTree.Element): An :class:`~xml.etree.ElementTree.Element` object. """ # We used to check here that we have the right sort of element, # ie a container or an item. But Sonos seems to use both # indiscriminately, eg a playlistContainer can be an item or a # container. So we now just check that it is one or the other. tag = element.tag if not (tag.endswith('item') or tag.endswith('container')): raise DIDLMetadataError( "Wrong element. Expected <item> or <container>," " got <{0}> for class {1}'".format( tag, cls.item_class)) # and that the upnp matches what we are expecting item_class = element.find(ns_tag('upnp', 'class')).text # In case this class has an # specified unofficial # subclass, ignore it by stripping it from item_class if '.#' in item_class: item_class = item_class[:item_class.find('.#')] if item_class != cls.item_class: raise DIDLMetadataError( "UPnP class is incorrect. Expected '{0}'," " got '{1}'".format(cls.item_class, item_class)) # parent_id, item_id and restricted are stored as attributes on the # element item_id = element.get('id', None) if item_id is None: raise DIDLMetadataError("Missing id attribute") item_id = really_unicode(item_id) parent_id = element.get('parentID', None) if parent_id is None: raise DIDLMetadataError("Missing parentID attribute") parent_id = really_unicode(parent_id) # CAUTION: This implementation deviates from the spec. # Elements are normally required to have a `restricted` tag, but # Spotify Direct violates this. To make it work, a missing restricted # tag is interpreted as `restricted = True`. restricted = element.get('restricted', None) restricted = False if restricted in [0, 'false', 'False'] else True # Similarily, all elements should have a title tag, but Spotify Direct # does not comply title_elt = element.find(ns_tag('dc', 'title')) if title_elt is None or not title_elt.text: title = '' else: title = really_unicode(title_elt.text) # Deal with any resource elements resources = [] for res_elt in element.findall(ns_tag('', 'res')): resources.append( DidlResource.from_element(res_elt)) # and the desc element (There is only one in Sonos) desc = element.findtext(ns_tag('', 'desc')) # Get values of the elements listed in _translation and add them to # the content dict content = {} for key, value in cls._translation.items(): result = element.findtext(ns_tag(*value)) if result is not None: # We store info as unicode internally. content[key] = really_unicode(result) # Convert type for original track number if content.get('original_track_number') is not None: content['original_track_number'] = \ int(content['original_track_number']) # Now pass the content dict we have just built to the main # constructor, as kwargs, to create the object return cls(title=title, parent_id=parent_id, item_id=item_id, restricted=restricted, resources=resources, desc=desc, **content)
[ "def", "from_element", "(", "cls", ",", "element", ")", ":", "# pylint: disable=R0914", "# We used to check here that we have the right sort of element,", "# ie a container or an item. But Sonos seems to use both", "# indiscriminately, eg a playlistContainer can be an item or a", "# containe...
Create an instance of this class from an ElementTree xml Element. An alternative constructor. The element must be a DIDL-Lite <item> or <container> element, and must be properly namespaced. Args: xml (~xml.etree.ElementTree.Element): An :class:`~xml.etree.ElementTree.Element` object.
[ "Create", "an", "instance", "of", "this", "class", "from", "an", "ElementTree", "xml", "Element", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures.py#L433-L519
train
214,755
SoCo/SoCo
soco/data_structures.py
DidlObject.to_dict
def to_dict(self, remove_nones=False): """Return the dict representation of the instance. Args: remove_nones (bool, optional): Optionally remove dictionary elements when their value is `None`. Returns: dict: a dict representation of the `DidlObject`. """ content = {} # Get the value of each attribute listed in _translation, and add it # to the content dict for key in self._translation: if hasattr(self, key): content[key] = getattr(self, key) # also add parent_id, item_id, restricted, title and resources because # they are not listed in _translation content['parent_id'] = self.parent_id content['item_id'] = self.item_id content['restricted'] = self.restricted content['title'] = self.title if self.resources != []: content['resources'] = [resource.to_dict(remove_nones=remove_nones) for resource in self.resources] content['desc'] = self.desc return content
python
def to_dict(self, remove_nones=False): """Return the dict representation of the instance. Args: remove_nones (bool, optional): Optionally remove dictionary elements when their value is `None`. Returns: dict: a dict representation of the `DidlObject`. """ content = {} # Get the value of each attribute listed in _translation, and add it # to the content dict for key in self._translation: if hasattr(self, key): content[key] = getattr(self, key) # also add parent_id, item_id, restricted, title and resources because # they are not listed in _translation content['parent_id'] = self.parent_id content['item_id'] = self.item_id content['restricted'] = self.restricted content['title'] = self.title if self.resources != []: content['resources'] = [resource.to_dict(remove_nones=remove_nones) for resource in self.resources] content['desc'] = self.desc return content
[ "def", "to_dict", "(", "self", ",", "remove_nones", "=", "False", ")", ":", "content", "=", "{", "}", "# Get the value of each attribute listed in _translation, and add it", "# to the content dict", "for", "key", "in", "self", ".", "_translation", ":", "if", "hasattr"...
Return the dict representation of the instance. Args: remove_nones (bool, optional): Optionally remove dictionary elements when their value is `None`. Returns: dict: a dict representation of the `DidlObject`.
[ "Return", "the", "dict", "representation", "of", "the", "instance", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures.py#L591-L617
train
214,756
SoCo/SoCo
soco/data_structures.py
DidlObject.set_uri
def set_uri(self, uri, resource_nr=0, protocol_info=None): """Set a resource uri for this instance. If no resource exists, create a new one with the given protocol info. Args: uri (str): The resource uri. resource_nr (int): The index of the resource on which to set the uri. If it does not exist, a new resource is added to the list. Note that by default, only the uri of the first resource is used for playing the item. protocol_info (str): Protocol info for the resource. If none is given and the resource does not exist yet, a default protocol info is constructed as '[uri prefix]:*:*:*'. """ try: self.resources[resource_nr].uri = uri if protocol_info is not None: self.resources[resource_nr].protocol_info = protocol_info except IndexError: if protocol_info is None: # create default protcol info protocol_info = uri[:uri.index(':')] + ':*:*:*' self.resources.append(DidlResource(uri, protocol_info))
python
def set_uri(self, uri, resource_nr=0, protocol_info=None): """Set a resource uri for this instance. If no resource exists, create a new one with the given protocol info. Args: uri (str): The resource uri. resource_nr (int): The index of the resource on which to set the uri. If it does not exist, a new resource is added to the list. Note that by default, only the uri of the first resource is used for playing the item. protocol_info (str): Protocol info for the resource. If none is given and the resource does not exist yet, a default protocol info is constructed as '[uri prefix]:*:*:*'. """ try: self.resources[resource_nr].uri = uri if protocol_info is not None: self.resources[resource_nr].protocol_info = protocol_info except IndexError: if protocol_info is None: # create default protcol info protocol_info = uri[:uri.index(':')] + ':*:*:*' self.resources.append(DidlResource(uri, protocol_info))
[ "def", "set_uri", "(", "self", ",", "uri", ",", "resource_nr", "=", "0", ",", "protocol_info", "=", "None", ")", ":", "try", ":", "self", ".", "resources", "[", "resource_nr", "]", ".", "uri", "=", "uri", "if", "protocol_info", "is", "not", "None", "...
Set a resource uri for this instance. If no resource exists, create a new one with the given protocol info. Args: uri (str): The resource uri. resource_nr (int): The index of the resource on which to set the uri. If it does not exist, a new resource is added to the list. Note that by default, only the uri of the first resource is used for playing the item. protocol_info (str): Protocol info for the resource. If none is given and the resource does not exist yet, a default protocol info is constructed as '[uri prefix]:*:*:*'.
[ "Set", "a", "resource", "uri", "for", "this", "instance", ".", "If", "no", "resource", "exists", "create", "a", "new", "one", "with", "the", "given", "protocol", "info", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures.py#L682-L704
train
214,757
SoCo/SoCo
soco/data_structures.py
DidlFavorite.reference
def reference(self): """The Didl object this favorite refers to.""" # Import from_didl_string if it isn't present already. The import # happens here because it would cause cyclic import errors if the # import happened at load time. global _FROM_DIDL_STRING_FUNCTION # pylint: disable=global-statement if not _FROM_DIDL_STRING_FUNCTION: from . import data_structures_entry _FROM_DIDL_STRING_FUNCTION = data_structures_entry.from_didl_string ref = _FROM_DIDL_STRING_FUNCTION( getattr(self, 'resource_meta_data'))[0] # The resMD metadata lacks a <res> tag, so we use the resources from # the favorite to make 'reference' playable. ref.resources = self.resources return ref
python
def reference(self): """The Didl object this favorite refers to.""" # Import from_didl_string if it isn't present already. The import # happens here because it would cause cyclic import errors if the # import happened at load time. global _FROM_DIDL_STRING_FUNCTION # pylint: disable=global-statement if not _FROM_DIDL_STRING_FUNCTION: from . import data_structures_entry _FROM_DIDL_STRING_FUNCTION = data_structures_entry.from_didl_string ref = _FROM_DIDL_STRING_FUNCTION( getattr(self, 'resource_meta_data'))[0] # The resMD metadata lacks a <res> tag, so we use the resources from # the favorite to make 'reference' playable. ref.resources = self.resources return ref
[ "def", "reference", "(", "self", ")", ":", "# Import from_didl_string if it isn't present already. The import", "# happens here because it would cause cyclic import errors if the", "# import happened at load time.", "global", "_FROM_DIDL_STRING_FUNCTION", "# pylint: disable=global-statement", ...
The Didl object this favorite refers to.
[ "The", "Didl", "object", "this", "favorite", "refers", "to", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures.py#L841-L857
train
214,758
SoCo/SoCo
soco/events.py
EventNotifyHandler.do_NOTIFY
def do_NOTIFY(self): # pylint: disable=invalid-name """Serve a ``NOTIFY`` request. A ``NOTIFY`` request will be sent by a Sonos device when a state variable changes. See the `UPnP Spec §4.3 [pdf] <http://upnp.org/specs/arch/UPnP-arch -DeviceArchitecture-v1.1.pdf>`_ for details. """ timestamp = time.time() headers = requests.structures.CaseInsensitiveDict(self.headers) seq = headers['seq'] # Event sequence number sid = headers['sid'] # Event Subscription Identifier content_length = int(headers['content-length']) content = self.rfile.read(content_length) # Find the relevant service and queue from the sid with _subscriptions_lock: subscription = _subscriptions.get(sid) # It might have been removed by another thread if subscription: service = subscription.service log.info( "Event %s received for %s service on thread %s at %s", seq, service.service_id, threading.current_thread(), timestamp) log.debug("Event content: %s", content) variables = parse_event_xml(content) # Build the Event object event = Event(sid, seq, service, timestamp, variables) # pass the event details on to the service so it can update its # cache. # pylint: disable=protected-access service._update_cache_on_event(event) # Put the event on the queue subscription.events.put(event) else: log.info("No service registered for %s", sid) self.send_response(200) self.end_headers()
python
def do_NOTIFY(self): # pylint: disable=invalid-name """Serve a ``NOTIFY`` request. A ``NOTIFY`` request will be sent by a Sonos device when a state variable changes. See the `UPnP Spec §4.3 [pdf] <http://upnp.org/specs/arch/UPnP-arch -DeviceArchitecture-v1.1.pdf>`_ for details. """ timestamp = time.time() headers = requests.structures.CaseInsensitiveDict(self.headers) seq = headers['seq'] # Event sequence number sid = headers['sid'] # Event Subscription Identifier content_length = int(headers['content-length']) content = self.rfile.read(content_length) # Find the relevant service and queue from the sid with _subscriptions_lock: subscription = _subscriptions.get(sid) # It might have been removed by another thread if subscription: service = subscription.service log.info( "Event %s received for %s service on thread %s at %s", seq, service.service_id, threading.current_thread(), timestamp) log.debug("Event content: %s", content) variables = parse_event_xml(content) # Build the Event object event = Event(sid, seq, service, timestamp, variables) # pass the event details on to the service so it can update its # cache. # pylint: disable=protected-access service._update_cache_on_event(event) # Put the event on the queue subscription.events.put(event) else: log.info("No service registered for %s", sid) self.send_response(200) self.end_headers()
[ "def", "do_NOTIFY", "(", "self", ")", ":", "# pylint: disable=invalid-name", "timestamp", "=", "time", ".", "time", "(", ")", "headers", "=", "requests", ".", "structures", ".", "CaseInsensitiveDict", "(", "self", ".", "headers", ")", "seq", "=", "headers", ...
Serve a ``NOTIFY`` request. A ``NOTIFY`` request will be sent by a Sonos device when a state variable changes. See the `UPnP Spec §4.3 [pdf] <http://upnp.org/specs/arch/UPnP-arch -DeviceArchitecture-v1.1.pdf>`_ for details.
[ "Serve", "a", "NOTIFY", "request", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/events.py#L234-L270
train
214,759
SoCo/SoCo
soco/events.py
EventListener.stop
def stop(self): """Stop the event listener.""" # Signal the thread to stop before handling the next request self._listener_thread.stop_flag.set() # Send a dummy request in case the http server is currently listening try: urlopen( 'http://%s:%s/' % (self.address[0], self.address[1])) except URLError: # If the server is already shut down, we receive a socket error, # which we ignore. pass # wait for the thread to finish self._listener_thread.join() self.is_running = False log.info("Event listener stopped")
python
def stop(self): """Stop the event listener.""" # Signal the thread to stop before handling the next request self._listener_thread.stop_flag.set() # Send a dummy request in case the http server is currently listening try: urlopen( 'http://%s:%s/' % (self.address[0], self.address[1])) except URLError: # If the server is already shut down, we receive a socket error, # which we ignore. pass # wait for the thread to finish self._listener_thread.join() self.is_running = False log.info("Event listener stopped")
[ "def", "stop", "(", "self", ")", ":", "# Signal the thread to stop before handling the next request", "self", ".", "_listener_thread", ".", "stop_flag", ".", "set", "(", ")", "# Send a dummy request in case the http server is currently listening", "try", ":", "urlopen", "(", ...
Stop the event listener.
[ "Stop", "the", "event", "listener", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/events.py#L365-L380
train
214,760
SoCo/SoCo
soco/events.py
Subscription.subscribe
def subscribe(self, requested_timeout=None, auto_renew=False): """Subscribe to the service. If requested_timeout is provided, a subscription valid for that number of seconds will be requested, but not guaranteed. Check `timeout` on return to find out what period of validity is actually allocated. Note: SoCo will try to unsubscribe any subscriptions which are still subscribed on program termination, but it is good practice for you to clean up by making sure that you call :meth:`unsubscribe` yourself. Args: requested_timeout(int, optional): The timeout to be requested. auto_renew (bool, optional): If `True`, renew the subscription automatically shortly before timeout. Default `False`. """ class AutoRenewThread(threading.Thread): """Used by the auto_renew code to renew a subscription from within a thread. """ def __init__(self, interval, stop_flag, sub, *args, **kwargs): super(AutoRenewThread, self).__init__(*args, **kwargs) self.interval = interval self.sub = sub self.stop_flag = stop_flag self.daemon = True def run(self): sub = self.sub stop_flag = self.stop_flag interval = self.interval while not stop_flag.wait(interval): log.info("Autorenewing subscription %s", sub.sid) sub.renew() # TIMEOUT is provided for in the UPnP spec, but it is not clear if # Sonos pays any attention to it. A timeout of 86400 secs always seems # to be allocated self.requested_timeout = requested_timeout if self._has_been_unsubscribed: raise SoCoException( 'Cannot resubscribe instance once unsubscribed') service = self.service # The event listener must be running, so start it if not if not event_listener.is_running: event_listener.start(service.soco) # an event subscription looks like this: # SUBSCRIBE publisher path HTTP/1.1 # HOST: publisher host:publisher port # CALLBACK: <delivery URL> # NT: upnp:event # TIMEOUT: Second-requested subscription duration (optional) # pylint: disable=unbalanced-tuple-unpacking ip_address, port = event_listener.address if config.EVENT_ADVERTISE_IP: ip_address = config.EVENT_ADVERTISE_IP headers = { 'Callback': '<http://{}:{}>'.format(ip_address, port), 'NT': 'upnp:event' } if requested_timeout is not None: headers["TIMEOUT"] = "Second-{}".format(requested_timeout) # Lock out EventNotifyHandler during registration with _subscriptions_lock: response = requests.request( 'SUBSCRIBE', service.base_url + service.event_subscription_url, headers=headers) response.raise_for_status() self.sid = response.headers['sid'] timeout = response.headers['timeout'] # According to the spec, timeout can be "infinite" or "second-123" # where 123 is a number of seconds. Sonos uses "Second-123" (with # a capital letter) if timeout.lower() == 'infinite': self.timeout = None else: self.timeout = int(timeout.lstrip('Second-')) self._timestamp = time.time() self.is_subscribed = True log.info( "Subscribed to %s, sid: %s", service.base_url + service.event_subscription_url, self.sid) # Add the subscription to the master dict so it can be looked up # by sid _subscriptions[self.sid] = self # Register this subscription to be unsubscribed at exit if still alive # This will not happen if exit is abnormal (eg in response to a # signal or fatal interpreter error - see the docs for `atexit`). atexit.register(self.unsubscribe) # Set up auto_renew if not auto_renew: return # Autorenew just before expiry, say at 85% of self.timeout seconds interval = self.timeout * 85 / 100 auto_renew_thread = AutoRenewThread( interval, self._auto_renew_thread_flag, self) auto_renew_thread.start()
python
def subscribe(self, requested_timeout=None, auto_renew=False): """Subscribe to the service. If requested_timeout is provided, a subscription valid for that number of seconds will be requested, but not guaranteed. Check `timeout` on return to find out what period of validity is actually allocated. Note: SoCo will try to unsubscribe any subscriptions which are still subscribed on program termination, but it is good practice for you to clean up by making sure that you call :meth:`unsubscribe` yourself. Args: requested_timeout(int, optional): The timeout to be requested. auto_renew (bool, optional): If `True`, renew the subscription automatically shortly before timeout. Default `False`. """ class AutoRenewThread(threading.Thread): """Used by the auto_renew code to renew a subscription from within a thread. """ def __init__(self, interval, stop_flag, sub, *args, **kwargs): super(AutoRenewThread, self).__init__(*args, **kwargs) self.interval = interval self.sub = sub self.stop_flag = stop_flag self.daemon = True def run(self): sub = self.sub stop_flag = self.stop_flag interval = self.interval while not stop_flag.wait(interval): log.info("Autorenewing subscription %s", sub.sid) sub.renew() # TIMEOUT is provided for in the UPnP spec, but it is not clear if # Sonos pays any attention to it. A timeout of 86400 secs always seems # to be allocated self.requested_timeout = requested_timeout if self._has_been_unsubscribed: raise SoCoException( 'Cannot resubscribe instance once unsubscribed') service = self.service # The event listener must be running, so start it if not if not event_listener.is_running: event_listener.start(service.soco) # an event subscription looks like this: # SUBSCRIBE publisher path HTTP/1.1 # HOST: publisher host:publisher port # CALLBACK: <delivery URL> # NT: upnp:event # TIMEOUT: Second-requested subscription duration (optional) # pylint: disable=unbalanced-tuple-unpacking ip_address, port = event_listener.address if config.EVENT_ADVERTISE_IP: ip_address = config.EVENT_ADVERTISE_IP headers = { 'Callback': '<http://{}:{}>'.format(ip_address, port), 'NT': 'upnp:event' } if requested_timeout is not None: headers["TIMEOUT"] = "Second-{}".format(requested_timeout) # Lock out EventNotifyHandler during registration with _subscriptions_lock: response = requests.request( 'SUBSCRIBE', service.base_url + service.event_subscription_url, headers=headers) response.raise_for_status() self.sid = response.headers['sid'] timeout = response.headers['timeout'] # According to the spec, timeout can be "infinite" or "second-123" # where 123 is a number of seconds. Sonos uses "Second-123" (with # a capital letter) if timeout.lower() == 'infinite': self.timeout = None else: self.timeout = int(timeout.lstrip('Second-')) self._timestamp = time.time() self.is_subscribed = True log.info( "Subscribed to %s, sid: %s", service.base_url + service.event_subscription_url, self.sid) # Add the subscription to the master dict so it can be looked up # by sid _subscriptions[self.sid] = self # Register this subscription to be unsubscribed at exit if still alive # This will not happen if exit is abnormal (eg in response to a # signal or fatal interpreter error - see the docs for `atexit`). atexit.register(self.unsubscribe) # Set up auto_renew if not auto_renew: return # Autorenew just before expiry, say at 85% of self.timeout seconds interval = self.timeout * 85 / 100 auto_renew_thread = AutoRenewThread( interval, self._auto_renew_thread_flag, self) auto_renew_thread.start()
[ "def", "subscribe", "(", "self", ",", "requested_timeout", "=", "None", ",", "auto_renew", "=", "False", ")", ":", "class", "AutoRenewThread", "(", "threading", ".", "Thread", ")", ":", "\"\"\"Used by the auto_renew code to renew a subscription from within\n a ...
Subscribe to the service. If requested_timeout is provided, a subscription valid for that number of seconds will be requested, but not guaranteed. Check `timeout` on return to find out what period of validity is actually allocated. Note: SoCo will try to unsubscribe any subscriptions which are still subscribed on program termination, but it is good practice for you to clean up by making sure that you call :meth:`unsubscribe` yourself. Args: requested_timeout(int, optional): The timeout to be requested. auto_renew (bool, optional): If `True`, renew the subscription automatically shortly before timeout. Default `False`.
[ "Subscribe", "to", "the", "service", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/events.py#L418-L526
train
214,761
SoCo/SoCo
soco/events.py
Subscription.renew
def renew(self, requested_timeout=None): """Renew the event subscription. You should not try to renew a subscription which has been unsubscribed, or once it has expired. Args: requested_timeout (int, optional): The period for which a renewal request should be made. If None (the default), use the timeout requested on subscription. """ # NB This code is sometimes called from a separate thread (when # subscriptions are auto-renewed. Be careful to ensure thread-safety if self._has_been_unsubscribed: raise SoCoException( 'Cannot renew subscription once unsubscribed') if not self.is_subscribed: raise SoCoException( 'Cannot renew subscription before subscribing') if self.time_left == 0: raise SoCoException( 'Cannot renew subscription after expiry') # SUBSCRIBE publisher path HTTP/1.1 # HOST: publisher host:publisher port # SID: uuid:subscription UUID # TIMEOUT: Second-requested subscription duration (optional) headers = { 'SID': self.sid } if requested_timeout is None: requested_timeout = self.requested_timeout if requested_timeout is not None: headers["TIMEOUT"] = "Second-{}".format(requested_timeout) response = requests.request( 'SUBSCRIBE', self.service.base_url + self.service.event_subscription_url, headers=headers) response.raise_for_status() timeout = response.headers['timeout'] # According to the spec, timeout can be "infinite" or "second-123" # where 123 is a number of seconds. Sonos uses "Second-123" (with a # a capital letter) if timeout.lower() == 'infinite': self.timeout = None else: self.timeout = int(timeout.lstrip('Second-')) self._timestamp = time.time() self.is_subscribed = True log.info( "Renewed subscription to %s, sid: %s", self.service.base_url + self.service.event_subscription_url, self.sid)
python
def renew(self, requested_timeout=None): """Renew the event subscription. You should not try to renew a subscription which has been unsubscribed, or once it has expired. Args: requested_timeout (int, optional): The period for which a renewal request should be made. If None (the default), use the timeout requested on subscription. """ # NB This code is sometimes called from a separate thread (when # subscriptions are auto-renewed. Be careful to ensure thread-safety if self._has_been_unsubscribed: raise SoCoException( 'Cannot renew subscription once unsubscribed') if not self.is_subscribed: raise SoCoException( 'Cannot renew subscription before subscribing') if self.time_left == 0: raise SoCoException( 'Cannot renew subscription after expiry') # SUBSCRIBE publisher path HTTP/1.1 # HOST: publisher host:publisher port # SID: uuid:subscription UUID # TIMEOUT: Second-requested subscription duration (optional) headers = { 'SID': self.sid } if requested_timeout is None: requested_timeout = self.requested_timeout if requested_timeout is not None: headers["TIMEOUT"] = "Second-{}".format(requested_timeout) response = requests.request( 'SUBSCRIBE', self.service.base_url + self.service.event_subscription_url, headers=headers) response.raise_for_status() timeout = response.headers['timeout'] # According to the spec, timeout can be "infinite" or "second-123" # where 123 is a number of seconds. Sonos uses "Second-123" (with a # a capital letter) if timeout.lower() == 'infinite': self.timeout = None else: self.timeout = int(timeout.lstrip('Second-')) self._timestamp = time.time() self.is_subscribed = True log.info( "Renewed subscription to %s, sid: %s", self.service.base_url + self.service.event_subscription_url, self.sid)
[ "def", "renew", "(", "self", ",", "requested_timeout", "=", "None", ")", ":", "# NB This code is sometimes called from a separate thread (when", "# subscriptions are auto-renewed. Be careful to ensure thread-safety", "if", "self", ".", "_has_been_unsubscribed", ":", "raise", "SoC...
Renew the event subscription. You should not try to renew a subscription which has been unsubscribed, or once it has expired. Args: requested_timeout (int, optional): The period for which a renewal request should be made. If None (the default), use the timeout requested on subscription.
[ "Renew", "the", "event", "subscription", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/events.py#L528-L581
train
214,762
SoCo/SoCo
soco/core.py
only_on_master
def only_on_master(function): """Decorator that raises SoCoSlaveException on master call on slave.""" @wraps(function) def inner_function(self, *args, **kwargs): """Master checking inner function.""" if not self.is_coordinator: message = 'The method or property "{0}" can only be called/used '\ 'on the coordinator in a group'.format(function.__name__) raise SoCoSlaveException(message) return function(self, *args, **kwargs) return inner_function
python
def only_on_master(function): """Decorator that raises SoCoSlaveException on master call on slave.""" @wraps(function) def inner_function(self, *args, **kwargs): """Master checking inner function.""" if not self.is_coordinator: message = 'The method or property "{0}" can only be called/used '\ 'on the coordinator in a group'.format(function.__name__) raise SoCoSlaveException(message) return function(self, *args, **kwargs) return inner_function
[ "def", "only_on_master", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "inner_function", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Master checking inner function.\"\"\"", "if", "not", "self", ".", "is_co...
Decorator that raises SoCoSlaveException on master call on slave.
[ "Decorator", "that", "raises", "SoCoSlaveException", "on", "master", "call", "on", "slave", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L97-L107
train
214,763
SoCo/SoCo
soco/core.py
SoCo.ramp_to_volume
def ramp_to_volume(self, volume, ramp_type='SLEEP_TIMER_RAMP_TYPE'): """Smoothly change the volume. There are three ramp types available: * ``'SLEEP_TIMER_RAMP_TYPE'`` (default): Linear ramp from the current volume up or down to the new volume. The ramp rate is 1.25 steps per second. For example: To change from volume 50 to volume 30 would take 16 seconds. * ``'ALARM_RAMP_TYPE'``: Resets the volume to zero, waits for about 30 seconds, and then ramps the volume up to the desired value at a rate of 2.5 steps per second. For example: Volume 30 would take 12 seconds for the ramp up (not considering the wait time). * ``'AUTOPLAY_RAMP_TYPE'``: Resets the volume to zero and then quickly ramps up at a rate of 50 steps per second. For example: Volume 30 will take only 0.6 seconds. The ramp rate is selected by Sonos based on the chosen ramp type and the resulting transition time returned. This method is non blocking and has no network overhead once sent. Args: volume (int): The new volume. ramp_type (str, optional): The desired ramp type, as described above. Returns: int: The ramp time in seconds, rounded down. Note that this does not include the wait time. """ response = self.renderingControl.RampToVolume([ ('InstanceID', 0), ('Channel', 'Master'), ('RampType', ramp_type), ('DesiredVolume', volume), ('ResetVolumeAfter', False), ('ProgramURI', '') ]) return int(response['RampTime'])
python
def ramp_to_volume(self, volume, ramp_type='SLEEP_TIMER_RAMP_TYPE'): """Smoothly change the volume. There are three ramp types available: * ``'SLEEP_TIMER_RAMP_TYPE'`` (default): Linear ramp from the current volume up or down to the new volume. The ramp rate is 1.25 steps per second. For example: To change from volume 50 to volume 30 would take 16 seconds. * ``'ALARM_RAMP_TYPE'``: Resets the volume to zero, waits for about 30 seconds, and then ramps the volume up to the desired value at a rate of 2.5 steps per second. For example: Volume 30 would take 12 seconds for the ramp up (not considering the wait time). * ``'AUTOPLAY_RAMP_TYPE'``: Resets the volume to zero and then quickly ramps up at a rate of 50 steps per second. For example: Volume 30 will take only 0.6 seconds. The ramp rate is selected by Sonos based on the chosen ramp type and the resulting transition time returned. This method is non blocking and has no network overhead once sent. Args: volume (int): The new volume. ramp_type (str, optional): The desired ramp type, as described above. Returns: int: The ramp time in seconds, rounded down. Note that this does not include the wait time. """ response = self.renderingControl.RampToVolume([ ('InstanceID', 0), ('Channel', 'Master'), ('RampType', ramp_type), ('DesiredVolume', volume), ('ResetVolumeAfter', False), ('ProgramURI', '') ]) return int(response['RampTime'])
[ "def", "ramp_to_volume", "(", "self", ",", "volume", ",", "ramp_type", "=", "'SLEEP_TIMER_RAMP_TYPE'", ")", ":", "response", "=", "self", ".", "renderingControl", ".", "RampToVolume", "(", "[", "(", "'InstanceID'", ",", "0", ")", ",", "(", "'Channel'", ",", ...
Smoothly change the volume. There are three ramp types available: * ``'SLEEP_TIMER_RAMP_TYPE'`` (default): Linear ramp from the current volume up or down to the new volume. The ramp rate is 1.25 steps per second. For example: To change from volume 50 to volume 30 would take 16 seconds. * ``'ALARM_RAMP_TYPE'``: Resets the volume to zero, waits for about 30 seconds, and then ramps the volume up to the desired value at a rate of 2.5 steps per second. For example: Volume 30 would take 12 seconds for the ramp up (not considering the wait time). * ``'AUTOPLAY_RAMP_TYPE'``: Resets the volume to zero and then quickly ramps up at a rate of 50 steps per second. For example: Volume 30 will take only 0.6 seconds. The ramp rate is selected by Sonos based on the chosen ramp type and the resulting transition time returned. This method is non blocking and has no network overhead once sent. Args: volume (int): The new volume. ramp_type (str, optional): The desired ramp type, as described above. Returns: int: The ramp time in seconds, rounded down. Note that this does not include the wait time.
[ "Smoothly", "change", "the", "volume", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L443-L481
train
214,764
SoCo/SoCo
soco/core.py
SoCo.play_from_queue
def play_from_queue(self, index, start=True): """Play a track from the queue by index. The index number is required as an argument, where the first index is 0. Args: index (int): 0-based index of the track to play start (bool): If the item that has been set should start playing """ # Grab the speaker's information if we haven't already since we'll need # it in the next step. if not self.speaker_info: self.get_speaker_info() # first, set the queue itself as the source URI uri = 'x-rincon-queue:{0}#0'.format(self.uid) self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', uri), ('CurrentURIMetaData', '') ]) # second, set the track number with a seek command self.avTransport.Seek([ ('InstanceID', 0), ('Unit', 'TRACK_NR'), ('Target', index + 1) ]) # finally, just play what's set if needed if start: self.play()
python
def play_from_queue(self, index, start=True): """Play a track from the queue by index. The index number is required as an argument, where the first index is 0. Args: index (int): 0-based index of the track to play start (bool): If the item that has been set should start playing """ # Grab the speaker's information if we haven't already since we'll need # it in the next step. if not self.speaker_info: self.get_speaker_info() # first, set the queue itself as the source URI uri = 'x-rincon-queue:{0}#0'.format(self.uid) self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', uri), ('CurrentURIMetaData', '') ]) # second, set the track number with a seek command self.avTransport.Seek([ ('InstanceID', 0), ('Unit', 'TRACK_NR'), ('Target', index + 1) ]) # finally, just play what's set if needed if start: self.play()
[ "def", "play_from_queue", "(", "self", ",", "index", ",", "start", "=", "True", ")", ":", "# Grab the speaker's information if we haven't already since we'll need", "# it in the next step.", "if", "not", "self", ".", "speaker_info", ":", "self", ".", "get_speaker_info", ...
Play a track from the queue by index. The index number is required as an argument, where the first index is 0. Args: index (int): 0-based index of the track to play start (bool): If the item that has been set should start playing
[ "Play", "a", "track", "from", "the", "queue", "by", "index", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L484-L516
train
214,765
SoCo/SoCo
soco/core.py
SoCo.play_uri
def play_uri(self, uri='', meta='', title='', start=True, force_radio=False): """Play a URI. Playing a URI will replace what was playing with the stream given by the URI. For some streams at least a title is required as metadata. This can be provided using the `meta` argument or the `title` argument. If the `title` argument is provided minimal metadata will be generated. If `meta` argument is provided the `title` argument is ignored. Args: uri (str): URI of the stream to be played. meta (str): The metadata to show in the player, DIDL format. title (str): The title to show in the player (if no meta). start (bool): If the URI that has been set should start playing. force_radio (bool): forces a uri to play as a radio stream. On a Sonos controller music is shown with one of the following display formats and controls: * Radio format: Shows the name of the radio station and other available data. No seek, next, previous, or voting capability. Examples: TuneIn, radioPup * Smart Radio: Shows track name, artist, and album. Limited seek, next and sometimes voting capability depending on the Music Service. Examples: Amazon Prime Stations, Pandora Radio Stations. * Track format: Shows track name, artist, and album the same as when playing from a queue. Full seek, next and previous capabilities. Examples: Spotify, Napster, Rhapsody. How it is displayed is determined by the URI prefix: `x-sonosapi-stream:`, `x-sonosapi-radio:`, `x-rincon-mp3radio:`, `hls-radio:` default to radio or smart radio format depending on the stream. Others default to track format: `x-file-cifs:`, `aac:`, `http:`, `https:`, `x-sonos-spotify:` (used by Spotify), `x-sonosapi-hls-static:` (Amazon Prime), `x-sonos-http:` (Google Play & Napster). Some URIs that default to track format could be radio streams, typically `http:`, `https:` or `aac:`. To force display and controls to Radio format set `force_radio=True` .. note:: Other URI prefixes exist but are less common. If you have information on these please add to this doc string. .. note:: A change in Sonos® (as of at least version 6.4.2) means that the devices no longer accepts ordinary `http:` and `https:` URIs for radio stations. This method has the option to replaces these prefixes with the one that Sonos® expects: `x-rincon-mp3radio:` by using the "force_radio=True" parameter. A few streams may fail if not forced to to Radio format. """ if meta == '' and title != '': meta_template = '<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/">'\ '<item id="R:0/0/0" parentID="R:0/0" restricted="true">'\ '<dc:title>{title}</dc:title><upnp:class>'\ 'object.item.audioItem.audioBroadcast</upnp:class><desc '\ 'id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:'\ 'metadata-1-0/">{service}</desc></item></DIDL-Lite>' tunein_service = 'SA_RINCON65031_' # Radio stations need to have at least a title to play meta = meta_template.format( title=escape(title), service=tunein_service) # change uri prefix to force radio style display and commands if force_radio: colon = uri.find(':') if colon > 0: uri = 'x-rincon-mp3radio{0}'.format(uri[colon:]) self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', uri), ('CurrentURIMetaData', meta) ]) # The track is enqueued, now play it if needed if start: return self.play() return False
python
def play_uri(self, uri='', meta='', title='', start=True, force_radio=False): """Play a URI. Playing a URI will replace what was playing with the stream given by the URI. For some streams at least a title is required as metadata. This can be provided using the `meta` argument or the `title` argument. If the `title` argument is provided minimal metadata will be generated. If `meta` argument is provided the `title` argument is ignored. Args: uri (str): URI of the stream to be played. meta (str): The metadata to show in the player, DIDL format. title (str): The title to show in the player (if no meta). start (bool): If the URI that has been set should start playing. force_radio (bool): forces a uri to play as a radio stream. On a Sonos controller music is shown with one of the following display formats and controls: * Radio format: Shows the name of the radio station and other available data. No seek, next, previous, or voting capability. Examples: TuneIn, radioPup * Smart Radio: Shows track name, artist, and album. Limited seek, next and sometimes voting capability depending on the Music Service. Examples: Amazon Prime Stations, Pandora Radio Stations. * Track format: Shows track name, artist, and album the same as when playing from a queue. Full seek, next and previous capabilities. Examples: Spotify, Napster, Rhapsody. How it is displayed is determined by the URI prefix: `x-sonosapi-stream:`, `x-sonosapi-radio:`, `x-rincon-mp3radio:`, `hls-radio:` default to radio or smart radio format depending on the stream. Others default to track format: `x-file-cifs:`, `aac:`, `http:`, `https:`, `x-sonos-spotify:` (used by Spotify), `x-sonosapi-hls-static:` (Amazon Prime), `x-sonos-http:` (Google Play & Napster). Some URIs that default to track format could be radio streams, typically `http:`, `https:` or `aac:`. To force display and controls to Radio format set `force_radio=True` .. note:: Other URI prefixes exist but are less common. If you have information on these please add to this doc string. .. note:: A change in Sonos® (as of at least version 6.4.2) means that the devices no longer accepts ordinary `http:` and `https:` URIs for radio stations. This method has the option to replaces these prefixes with the one that Sonos® expects: `x-rincon-mp3radio:` by using the "force_radio=True" parameter. A few streams may fail if not forced to to Radio format. """ if meta == '' and title != '': meta_template = '<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/">'\ '<item id="R:0/0/0" parentID="R:0/0" restricted="true">'\ '<dc:title>{title}</dc:title><upnp:class>'\ 'object.item.audioItem.audioBroadcast</upnp:class><desc '\ 'id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:'\ 'metadata-1-0/">{service}</desc></item></DIDL-Lite>' tunein_service = 'SA_RINCON65031_' # Radio stations need to have at least a title to play meta = meta_template.format( title=escape(title), service=tunein_service) # change uri prefix to force radio style display and commands if force_radio: colon = uri.find(':') if colon > 0: uri = 'x-rincon-mp3radio{0}'.format(uri[colon:]) self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', uri), ('CurrentURIMetaData', meta) ]) # The track is enqueued, now play it if needed if start: return self.play() return False
[ "def", "play_uri", "(", "self", ",", "uri", "=", "''", ",", "meta", "=", "''", ",", "title", "=", "''", ",", "start", "=", "True", ",", "force_radio", "=", "False", ")", ":", "if", "meta", "==", "''", "and", "title", "!=", "''", ":", "meta_templa...
Play a URI. Playing a URI will replace what was playing with the stream given by the URI. For some streams at least a title is required as metadata. This can be provided using the `meta` argument or the `title` argument. If the `title` argument is provided minimal metadata will be generated. If `meta` argument is provided the `title` argument is ignored. Args: uri (str): URI of the stream to be played. meta (str): The metadata to show in the player, DIDL format. title (str): The title to show in the player (if no meta). start (bool): If the URI that has been set should start playing. force_radio (bool): forces a uri to play as a radio stream. On a Sonos controller music is shown with one of the following display formats and controls: * Radio format: Shows the name of the radio station and other available data. No seek, next, previous, or voting capability. Examples: TuneIn, radioPup * Smart Radio: Shows track name, artist, and album. Limited seek, next and sometimes voting capability depending on the Music Service. Examples: Amazon Prime Stations, Pandora Radio Stations. * Track format: Shows track name, artist, and album the same as when playing from a queue. Full seek, next and previous capabilities. Examples: Spotify, Napster, Rhapsody. How it is displayed is determined by the URI prefix: `x-sonosapi-stream:`, `x-sonosapi-radio:`, `x-rincon-mp3radio:`, `hls-radio:` default to radio or smart radio format depending on the stream. Others default to track format: `x-file-cifs:`, `aac:`, `http:`, `https:`, `x-sonos-spotify:` (used by Spotify), `x-sonosapi-hls-static:` (Amazon Prime), `x-sonos-http:` (Google Play & Napster). Some URIs that default to track format could be radio streams, typically `http:`, `https:` or `aac:`. To force display and controls to Radio format set `force_radio=True` .. note:: Other URI prefixes exist but are less common. If you have information on these please add to this doc string. .. note:: A change in Sonos® (as of at least version 6.4.2) means that the devices no longer accepts ordinary `http:` and `https:` URIs for radio stations. This method has the option to replaces these prefixes with the one that Sonos® expects: `x-rincon-mp3radio:` by using the "force_radio=True" parameter. A few streams may fail if not forced to to Radio format.
[ "Play", "a", "URI", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L528-L610
train
214,766
SoCo/SoCo
soco/core.py
SoCo.volume
def volume(self, volume): """Set the speaker's volume.""" volume = int(volume) volume = max(0, min(volume, 100)) # Coerce in range self.renderingControl.SetVolume([ ('InstanceID', 0), ('Channel', 'Master'), ('DesiredVolume', volume) ])
python
def volume(self, volume): """Set the speaker's volume.""" volume = int(volume) volume = max(0, min(volume, 100)) # Coerce in range self.renderingControl.SetVolume([ ('InstanceID', 0), ('Channel', 'Master'), ('DesiredVolume', volume) ])
[ "def", "volume", "(", "self", ",", "volume", ")", ":", "volume", "=", "int", "(", "volume", ")", "volume", "=", "max", "(", "0", ",", "min", "(", "volume", ",", "100", ")", ")", "# Coerce in range", "self", ".", "renderingControl", ".", "SetVolume", ...
Set the speaker's volume.
[ "Set", "the", "speaker", "s", "volume", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L713-L721
train
214,767
SoCo/SoCo
soco/core.py
SoCo.bass
def bass(self, bass): """Set the speaker's bass.""" bass = int(bass) bass = max(-10, min(bass, 10)) # Coerce in range self.renderingControl.SetBass([ ('InstanceID', 0), ('DesiredBass', bass) ])
python
def bass(self, bass): """Set the speaker's bass.""" bass = int(bass) bass = max(-10, min(bass, 10)) # Coerce in range self.renderingControl.SetBass([ ('InstanceID', 0), ('DesiredBass', bass) ])
[ "def", "bass", "(", "self", ",", "bass", ")", ":", "bass", "=", "int", "(", "bass", ")", "bass", "=", "max", "(", "-", "10", ",", "min", "(", "bass", ",", "10", ")", ")", "# Coerce in range", "self", ".", "renderingControl", ".", "SetBass", "(", ...
Set the speaker's bass.
[ "Set", "the", "speaker", "s", "bass", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L738-L745
train
214,768
SoCo/SoCo
soco/core.py
SoCo.treble
def treble(self, treble): """Set the speaker's treble.""" treble = int(treble) treble = max(-10, min(treble, 10)) # Coerce in range self.renderingControl.SetTreble([ ('InstanceID', 0), ('DesiredTreble', treble) ])
python
def treble(self, treble): """Set the speaker's treble.""" treble = int(treble) treble = max(-10, min(treble, 10)) # Coerce in range self.renderingControl.SetTreble([ ('InstanceID', 0), ('DesiredTreble', treble) ])
[ "def", "treble", "(", "self", ",", "treble", ")", ":", "treble", "=", "int", "(", "treble", ")", "treble", "=", "max", "(", "-", "10", ",", "min", "(", "treble", ",", "10", ")", ")", "# Coerce in range", "self", ".", "renderingControl", ".", "SetTreb...
Set the speaker's treble.
[ "Set", "the", "speaker", "s", "treble", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L762-L769
train
214,769
SoCo/SoCo
soco/core.py
SoCo._parse_zone_group_state
def _parse_zone_group_state(self): """The Zone Group State contains a lot of useful information. Retrieve and parse it, and populate the relevant properties. """ # zoneGroupTopology.GetZoneGroupState()['ZoneGroupState'] returns XML like # this: # # <ZoneGroups> # <ZoneGroup Coordinator="RINCON_000XXX1400" ID="RINCON_000XXXX1400:0"> # <ZoneGroupMember # BootSeq="33" # Configuration="1" # Icon="x-rincon-roomicon:zoneextender" # Invisible="1" # IsZoneBridge="1" # Location="http://192.168.1.100:1400/xml/device_description.xml" # MinCompatibleVersion="22.0-00000" # SoftwareVersion="24.1-74200" # UUID="RINCON_000ZZZ1400" # ZoneName="BRIDGE"/> # </ZoneGroup> # <ZoneGroup Coordinator="RINCON_000XXX1400" ID="RINCON_000XXX1400:46"> # <ZoneGroupMember # BootSeq="44" # Configuration="1" # Icon="x-rincon-roomicon:living" # Location="http://192.168.1.101:1400/xml/device_description.xml" # MinCompatibleVersion="22.0-00000" # SoftwareVersion="24.1-74200" # UUID="RINCON_000XXX1400" # ZoneName="Living Room"/> # <ZoneGroupMember # BootSeq="52" # Configuration="1" # Icon="x-rincon-roomicon:kitchen" # Location="http://192.168.1.102:1400/xml/device_description.xml" # MinCompatibleVersion="22.0-00000" # SoftwareVersion="24.1-74200" # UUID="RINCON_000YYY1400" # ZoneName="Kitchen"/> # </ZoneGroup> # </ZoneGroups> # def parse_zone_group_member(member_element): """Parse a ZoneGroupMember or Satellite element from Zone Group State, create a SoCo instance for the member, set basic attributes and return it.""" # Create a SoCo instance for each member. Because SoCo # instances are singletons, this is cheap if they have already # been created, and useful if they haven't. We can then # update various properties for that instance. member_attribs = member_element.attrib ip_addr = member_attribs['Location'].\ split('//')[1].split(':')[0] zone = config.SOCO_CLASS(ip_addr) # uid doesn't change, but it's not harmful to (re)set it, in case # the zone is as yet unseen. zone._uid = member_attribs['UUID'] zone._player_name = member_attribs['ZoneName'] # add the zone to the set of all members, and to the set # of visible members if appropriate is_visible = False if member_attribs.get( 'Invisible') == '1' else True if is_visible: self._visible_zones.add(zone) self._all_zones.add(zone) return zone # This is called quite frequently, so it is worth optimising it. # Maintain a private cache. If the zgt has not changed, there is no # need to repeat all the XML parsing. In addition, switch on network # caching for a short interval (5 secs). zgs = self.zoneGroupTopology.GetZoneGroupState( cache_timeout=5)['ZoneGroupState'] if zgs == self._zgs_cache: return self._zgs_cache = zgs tree = XML.fromstring(zgs.encode('utf-8')) # Empty the set of all zone_groups self._groups.clear() # and the set of all members self._all_zones.clear() self._visible_zones.clear() # Loop over each ZoneGroup Element for group_element in tree.findall('ZoneGroup'): coordinator_uid = group_element.attrib['Coordinator'] group_uid = group_element.attrib['ID'] group_coordinator = None members = set() for member_element in group_element.findall('ZoneGroupMember'): zone = parse_zone_group_member(member_element) # Perform extra processing relevant to direct zone group # members # # If this element has the same UUID as the coordinator, it is # the coordinator if zone._uid == coordinator_uid: group_coordinator = zone zone._is_coordinator = True else: zone._is_coordinator = False # is_bridge doesn't change, but it does no real harm to # set/reset it here, just in case the zone has not been seen # before zone._is_bridge = True if member_element.attrib.get( 'IsZoneBridge') == '1' else False # add the zone to the members for this group members.add(zone) # Loop over Satellite elements if present, and process as for # ZoneGroup elements for satellite_element in member_element.findall('Satellite'): zone = parse_zone_group_member(satellite_element) # Assume a satellite can't be a bridge or coordinator, so # no need to check. # # Add the zone to the members for this group. members.add(zone) # Now create a ZoneGroup with this info and add it to the list # of groups self._groups.add(ZoneGroup(group_uid, group_coordinator, members))
python
def _parse_zone_group_state(self): """The Zone Group State contains a lot of useful information. Retrieve and parse it, and populate the relevant properties. """ # zoneGroupTopology.GetZoneGroupState()['ZoneGroupState'] returns XML like # this: # # <ZoneGroups> # <ZoneGroup Coordinator="RINCON_000XXX1400" ID="RINCON_000XXXX1400:0"> # <ZoneGroupMember # BootSeq="33" # Configuration="1" # Icon="x-rincon-roomicon:zoneextender" # Invisible="1" # IsZoneBridge="1" # Location="http://192.168.1.100:1400/xml/device_description.xml" # MinCompatibleVersion="22.0-00000" # SoftwareVersion="24.1-74200" # UUID="RINCON_000ZZZ1400" # ZoneName="BRIDGE"/> # </ZoneGroup> # <ZoneGroup Coordinator="RINCON_000XXX1400" ID="RINCON_000XXX1400:46"> # <ZoneGroupMember # BootSeq="44" # Configuration="1" # Icon="x-rincon-roomicon:living" # Location="http://192.168.1.101:1400/xml/device_description.xml" # MinCompatibleVersion="22.0-00000" # SoftwareVersion="24.1-74200" # UUID="RINCON_000XXX1400" # ZoneName="Living Room"/> # <ZoneGroupMember # BootSeq="52" # Configuration="1" # Icon="x-rincon-roomicon:kitchen" # Location="http://192.168.1.102:1400/xml/device_description.xml" # MinCompatibleVersion="22.0-00000" # SoftwareVersion="24.1-74200" # UUID="RINCON_000YYY1400" # ZoneName="Kitchen"/> # </ZoneGroup> # </ZoneGroups> # def parse_zone_group_member(member_element): """Parse a ZoneGroupMember or Satellite element from Zone Group State, create a SoCo instance for the member, set basic attributes and return it.""" # Create a SoCo instance for each member. Because SoCo # instances are singletons, this is cheap if they have already # been created, and useful if they haven't. We can then # update various properties for that instance. member_attribs = member_element.attrib ip_addr = member_attribs['Location'].\ split('//')[1].split(':')[0] zone = config.SOCO_CLASS(ip_addr) # uid doesn't change, but it's not harmful to (re)set it, in case # the zone is as yet unseen. zone._uid = member_attribs['UUID'] zone._player_name = member_attribs['ZoneName'] # add the zone to the set of all members, and to the set # of visible members if appropriate is_visible = False if member_attribs.get( 'Invisible') == '1' else True if is_visible: self._visible_zones.add(zone) self._all_zones.add(zone) return zone # This is called quite frequently, so it is worth optimising it. # Maintain a private cache. If the zgt has not changed, there is no # need to repeat all the XML parsing. In addition, switch on network # caching for a short interval (5 secs). zgs = self.zoneGroupTopology.GetZoneGroupState( cache_timeout=5)['ZoneGroupState'] if zgs == self._zgs_cache: return self._zgs_cache = zgs tree = XML.fromstring(zgs.encode('utf-8')) # Empty the set of all zone_groups self._groups.clear() # and the set of all members self._all_zones.clear() self._visible_zones.clear() # Loop over each ZoneGroup Element for group_element in tree.findall('ZoneGroup'): coordinator_uid = group_element.attrib['Coordinator'] group_uid = group_element.attrib['ID'] group_coordinator = None members = set() for member_element in group_element.findall('ZoneGroupMember'): zone = parse_zone_group_member(member_element) # Perform extra processing relevant to direct zone group # members # # If this element has the same UUID as the coordinator, it is # the coordinator if zone._uid == coordinator_uid: group_coordinator = zone zone._is_coordinator = True else: zone._is_coordinator = False # is_bridge doesn't change, but it does no real harm to # set/reset it here, just in case the zone has not been seen # before zone._is_bridge = True if member_element.attrib.get( 'IsZoneBridge') == '1' else False # add the zone to the members for this group members.add(zone) # Loop over Satellite elements if present, and process as for # ZoneGroup elements for satellite_element in member_element.findall('Satellite'): zone = parse_zone_group_member(satellite_element) # Assume a satellite can't be a bridge or coordinator, so # no need to check. # # Add the zone to the members for this group. members.add(zone) # Now create a ZoneGroup with this info and add it to the list # of groups self._groups.add(ZoneGroup(group_uid, group_coordinator, members))
[ "def", "_parse_zone_group_state", "(", "self", ")", ":", "# zoneGroupTopology.GetZoneGroupState()['ZoneGroupState'] returns XML like", "# this:", "#", "# <ZoneGroups>", "# <ZoneGroup Coordinator=\"RINCON_000XXX1400\" ID=\"RINCON_000XXXX1400:0\">", "# <ZoneGroupMember", "# BootS...
The Zone Group State contains a lot of useful information. Retrieve and parse it, and populate the relevant properties.
[ "The", "Zone", "Group", "State", "contains", "a", "lot", "of", "useful", "information", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L865-L987
train
214,770
SoCo/SoCo
soco/core.py
SoCo.partymode
def partymode(self): """Put all the speakers in the network in the same group, a.k.a Party Mode. This blog shows the initial research responsible for this: http://blog.travelmarx.com/2010/06/exploring-sonos-via-upnp.html The trick seems to be (only tested on a two-speaker setup) to tell each speaker which to join. There's probably a bit more to it if multiple groups have been defined. """ # Tell every other visible zone to join this one # pylint: disable = expression-not-assigned [zone.join(self) for zone in self.visible_zones if zone is not self]
python
def partymode(self): """Put all the speakers in the network in the same group, a.k.a Party Mode. This blog shows the initial research responsible for this: http://blog.travelmarx.com/2010/06/exploring-sonos-via-upnp.html The trick seems to be (only tested on a two-speaker setup) to tell each speaker which to join. There's probably a bit more to it if multiple groups have been defined. """ # Tell every other visible zone to join this one # pylint: disable = expression-not-assigned [zone.join(self) for zone in self.visible_zones if zone is not self]
[ "def", "partymode", "(", "self", ")", ":", "# Tell every other visible zone to join this one", "# pylint: disable = expression-not-assigned", "[", "zone", ".", "join", "(", "self", ")", "for", "zone", "in", "self", ".", "visible_zones", "if", "zone", "is", "not", "s...
Put all the speakers in the network in the same group, a.k.a Party Mode. This blog shows the initial research responsible for this: http://blog.travelmarx.com/2010/06/exploring-sonos-via-upnp.html The trick seems to be (only tested on a two-speaker setup) to tell each speaker which to join. There's probably a bit more to it if multiple groups have been defined.
[ "Put", "all", "the", "speakers", "in", "the", "network", "in", "the", "same", "group", "a", ".", "k", ".", "a", "Party", "Mode", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1031-L1044
train
214,771
SoCo/SoCo
soco/core.py
SoCo.switch_to_line_in
def switch_to_line_in(self, source=None): """ Switch the speaker's input to line-in. Args: source (SoCo): The speaker whose line-in should be played. Default is line-in from the speaker itself. """ if source: uid = source.uid else: uid = self.uid self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', 'x-rincon-stream:{0}'.format(uid)), ('CurrentURIMetaData', '') ])
python
def switch_to_line_in(self, source=None): """ Switch the speaker's input to line-in. Args: source (SoCo): The speaker whose line-in should be played. Default is line-in from the speaker itself. """ if source: uid = source.uid else: uid = self.uid self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', 'x-rincon-stream:{0}'.format(uid)), ('CurrentURIMetaData', '') ])
[ "def", "switch_to_line_in", "(", "self", ",", "source", "=", "None", ")", ":", "if", "source", ":", "uid", "=", "source", ".", "uid", "else", ":", "uid", "=", "self", ".", "uid", "self", ".", "avTransport", ".", "SetAVTransportURI", "(", "[", "(", "'...
Switch the speaker's input to line-in. Args: source (SoCo): The speaker whose line-in should be played. Default is line-in from the speaker itself.
[ "Switch", "the", "speaker", "s", "input", "to", "line", "-", "in", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1070-L1086
train
214,772
SoCo/SoCo
soco/core.py
SoCo.get_current_track_info
def get_current_track_info(self): """Get information about the currently playing track. Returns: dict: A dictionary containing information about the currently playing track: playlist_position, duration, title, artist, album, position and an album_art link. If we're unable to return data for a field, we'll return an empty string. This can happen for all kinds of reasons so be sure to check values. For example, a track may not have complete metadata and be missing an album name. In this case track['album'] will be an empty string. .. note:: Calling this method on a slave in a group will not return the track the group is playing, but the last track this speaker was playing. """ 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'] # Store the entire Metadata entry in the track, this can then be # used if needed by the client to restart a given URI track['metadata'] = metadata # 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') or '' index = trackinfo.find(' - ') if index > -1: track['artist'] = trackinfo[:index] track['title'] = trackinfo[index + 3:] else: # Might find some kind of title anyway in metadata track['title'] = metadata.findtext('.//{http://purl.org/dc/' 'elements/1.1/}title') if not track['title']: track['title'] = 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): # 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'] = md_title track['artist'] = "" if md_artist: track['artist'] = md_artist track['album'] = "" if md_album: track['album'] = md_album album_art_url = metadata.findtext( './/{urn:schemas-upnp-org:metadata-1-0/upnp/}albumArtURI') if album_art_url is not None: track['album_art'] = \ self.music_library.build_album_art_full_uri(album_art_url) return track
python
def get_current_track_info(self): """Get information about the currently playing track. Returns: dict: A dictionary containing information about the currently playing track: playlist_position, duration, title, artist, album, position and an album_art link. If we're unable to return data for a field, we'll return an empty string. This can happen for all kinds of reasons so be sure to check values. For example, a track may not have complete metadata and be missing an album name. In this case track['album'] will be an empty string. .. note:: Calling this method on a slave in a group will not return the track the group is playing, but the last track this speaker was playing. """ 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'] # Store the entire Metadata entry in the track, this can then be # used if needed by the client to restart a given URI track['metadata'] = metadata # 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') or '' index = trackinfo.find(' - ') if index > -1: track['artist'] = trackinfo[:index] track['title'] = trackinfo[index + 3:] else: # Might find some kind of title anyway in metadata track['title'] = metadata.findtext('.//{http://purl.org/dc/' 'elements/1.1/}title') if not track['title']: track['title'] = 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): # 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'] = md_title track['artist'] = "" if md_artist: track['artist'] = md_artist track['album'] = "" if md_album: track['album'] = md_album album_art_url = metadata.findtext( './/{urn:schemas-upnp-org:metadata-1-0/upnp/}albumArtURI') if album_art_url is not None: track['album_art'] = \ self.music_library.build_album_art_full_uri(album_art_url) return track
[ "def", "get_current_track_info", "(", "self", ")", ":", "response", "=", "self", ".", "avTransport", ".", "GetPositionInfo", "(", "[", "(", "'InstanceID'", ",", "0", ")", ",", "(", "'Channel'", ",", "'Master'", ")", "]", ")", "track", "=", "{", "'title'"...
Get information about the currently playing track. Returns: dict: A dictionary containing information about the currently playing track: playlist_position, duration, title, artist, album, position and an album_art link. If we're unable to return data for a field, we'll return an empty string. This can happen for all kinds of reasons so be sure to check values. For example, a track may not have complete metadata and be missing an album name. In this case track['album'] will be an empty string. .. note:: Calling this method on a slave in a group will not return the track the group is playing, but the last track this speaker was playing.
[ "Get", "information", "about", "the", "currently", "playing", "track", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1146-L1227
train
214,773
SoCo/SoCo
soco/core.py
SoCo.get_speaker_info
def get_speaker_info(self, refresh=False, timeout=None): """Get information about the Sonos speaker. Arguments: refresh(bool): Refresh the speaker info cache. timeout: How long to wait for the server to send data before giving up, as a float, or a `(connect timeout, read timeout)` tuple e.g. (3, 5). Default is no timeout. Returns: dict: 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.ip_address + ':1400/xml/device_description.xml', timeout=timeout) dom = XML.fromstring(response.content) device = dom.find('{urn:schemas-upnp-org:device-1-0}device') if device is not None: self.speaker_info['zone_name'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}roomName') # no zone icon in device_description.xml -> player icon self.speaker_info['player_icon'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}iconList/' '{urn:schemas-upnp-org:device-1-0}icon/' '{urn:schemas-upnp-org:device-1-0}url' ) self.speaker_info['uid'] = self.uid self.speaker_info['serial_number'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}serialNum') self.speaker_info['software_version'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}softwareVersion') self.speaker_info['hardware_version'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}hardwareVersion') self.speaker_info['model_number'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}modelNumber') self.speaker_info['model_name'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}modelName') self.speaker_info['display_version'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}displayVersion') # no mac address - extract from serial number mac = self.speaker_info['serial_number'].split(':')[0] self.speaker_info['mac_address'] = mac return self.speaker_info return None
python
def get_speaker_info(self, refresh=False, timeout=None): """Get information about the Sonos speaker. Arguments: refresh(bool): Refresh the speaker info cache. timeout: How long to wait for the server to send data before giving up, as a float, or a `(connect timeout, read timeout)` tuple e.g. (3, 5). Default is no timeout. Returns: dict: 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.ip_address + ':1400/xml/device_description.xml', timeout=timeout) dom = XML.fromstring(response.content) device = dom.find('{urn:schemas-upnp-org:device-1-0}device') if device is not None: self.speaker_info['zone_name'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}roomName') # no zone icon in device_description.xml -> player icon self.speaker_info['player_icon'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}iconList/' '{urn:schemas-upnp-org:device-1-0}icon/' '{urn:schemas-upnp-org:device-1-0}url' ) self.speaker_info['uid'] = self.uid self.speaker_info['serial_number'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}serialNum') self.speaker_info['software_version'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}softwareVersion') self.speaker_info['hardware_version'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}hardwareVersion') self.speaker_info['model_number'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}modelNumber') self.speaker_info['model_name'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}modelName') self.speaker_info['display_version'] = device.findtext( '{urn:schemas-upnp-org:device-1-0}displayVersion') # no mac address - extract from serial number mac = self.speaker_info['serial_number'].split(':')[0] self.speaker_info['mac_address'] = mac return self.speaker_info return None
[ "def", "get_speaker_info", "(", "self", ",", "refresh", "=", "False", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "speaker_info", "and", "refresh", "is", "False", ":", "return", "self", ".", "speaker_info", "else", ":", "response", "=", "re...
Get information about the Sonos speaker. Arguments: refresh(bool): Refresh the speaker info cache. timeout: How long to wait for the server to send data before giving up, as a float, or a `(connect timeout, read timeout)` tuple e.g. (3, 5). Default is no timeout. Returns: dict: Information about the Sonos speaker, such as the UID, MAC Address, and Zone Name.
[ "Get", "information", "about", "the", "Sonos", "speaker", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1229-L1282
train
214,774
SoCo/SoCo
soco/core.py
SoCo.get_current_transport_info
def get_current_transport_info(self): """Get the current playback state. Returns: dict: The following information about the speaker's playing state: * current_transport_state (``PLAYING``, ``TRANSITIONING``, ``PAUSED_PLAYBACK``, ``STOPPED``) * current_transport_status (OK, ?) * current_speed(1, ?) This allows us to know if speaker is playing or not. Don't know other states of CurrentTransportStatus and CurrentSpeed. """ response = self.avTransport.GetTransportInfo([ ('InstanceID', 0), ]) playstate = { 'current_transport_status': '', 'current_transport_state': '', 'current_transport_speed': '' } playstate['current_transport_state'] = \ response['CurrentTransportState'] playstate['current_transport_status'] = \ response['CurrentTransportStatus'] playstate['current_transport_speed'] = response['CurrentSpeed'] return playstate
python
def get_current_transport_info(self): """Get the current playback state. Returns: dict: The following information about the speaker's playing state: * current_transport_state (``PLAYING``, ``TRANSITIONING``, ``PAUSED_PLAYBACK``, ``STOPPED``) * current_transport_status (OK, ?) * current_speed(1, ?) This allows us to know if speaker is playing or not. Don't know other states of CurrentTransportStatus and CurrentSpeed. """ response = self.avTransport.GetTransportInfo([ ('InstanceID', 0), ]) playstate = { 'current_transport_status': '', 'current_transport_state': '', 'current_transport_speed': '' } playstate['current_transport_state'] = \ response['CurrentTransportState'] playstate['current_transport_status'] = \ response['CurrentTransportStatus'] playstate['current_transport_speed'] = response['CurrentSpeed'] return playstate
[ "def", "get_current_transport_info", "(", "self", ")", ":", "response", "=", "self", ".", "avTransport", ".", "GetTransportInfo", "(", "[", "(", "'InstanceID'", ",", "0", ")", ",", "]", ")", "playstate", "=", "{", "'current_transport_status'", ":", "''", ","...
Get the current playback state. Returns: dict: The following information about the speaker's playing state: * current_transport_state (``PLAYING``, ``TRANSITIONING``, ``PAUSED_PLAYBACK``, ``STOPPED``) * current_transport_status (OK, ?) * current_speed(1, ?) This allows us to know if speaker is playing or not. Don't know other states of CurrentTransportStatus and CurrentSpeed.
[ "Get", "the", "current", "playback", "state", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1284-L1315
train
214,775
SoCo/SoCo
soco/core.py
SoCo.get_queue
def get_queue(self, start=0, max_items=100, full_album_art_uri=False): """Get information about the queue. :param start: Starting number of returned matches :param max_items: Maximum number of returned matches :param full_album_art_uri: If the album art URI should include the IP address :returns: A :py:class:`~.soco.data_structures.Queue` object This method is heavly based on Sam Soffes (aka soffes) ruby implementation """ queue = [] response = self.contentDirectory.Browse([ ('ObjectID', 'Q:0'), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', start), ('RequestedCount', max_items), ('SortCriteria', '') ]) result = response['Result'] metadata = {} for tag in ['NumberReturned', 'TotalMatches', 'UpdateID']: metadata[camel_to_underscore(tag)] = int(response[tag]) # I'm not sure this necessary (any more). Even with an empty queue, # there is still a result object. This shoud be investigated. if not result: # pylint: disable=star-args return Queue(queue, **metadata) items = from_didl_string(result) for item in items: # Check if the album art URI should be fully qualified if full_album_art_uri: self.music_library._update_album_art_to_full_uri(item) queue.append(item) # pylint: disable=star-args return Queue(queue, **metadata)
python
def get_queue(self, start=0, max_items=100, full_album_art_uri=False): """Get information about the queue. :param start: Starting number of returned matches :param max_items: Maximum number of returned matches :param full_album_art_uri: If the album art URI should include the IP address :returns: A :py:class:`~.soco.data_structures.Queue` object This method is heavly based on Sam Soffes (aka soffes) ruby implementation """ queue = [] response = self.contentDirectory.Browse([ ('ObjectID', 'Q:0'), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', start), ('RequestedCount', max_items), ('SortCriteria', '') ]) result = response['Result'] metadata = {} for tag in ['NumberReturned', 'TotalMatches', 'UpdateID']: metadata[camel_to_underscore(tag)] = int(response[tag]) # I'm not sure this necessary (any more). Even with an empty queue, # there is still a result object. This shoud be investigated. if not result: # pylint: disable=star-args return Queue(queue, **metadata) items = from_didl_string(result) for item in items: # Check if the album art URI should be fully qualified if full_album_art_uri: self.music_library._update_album_art_to_full_uri(item) queue.append(item) # pylint: disable=star-args return Queue(queue, **metadata)
[ "def", "get_queue", "(", "self", ",", "start", "=", "0", ",", "max_items", "=", "100", ",", "full_album_art_uri", "=", "False", ")", ":", "queue", "=", "[", "]", "response", "=", "self", ".", "contentDirectory", ".", "Browse", "(", "[", "(", "'ObjectID...
Get information about the queue. :param start: Starting number of returned matches :param max_items: Maximum number of returned matches :param full_album_art_uri: If the album art URI should include the IP address :returns: A :py:class:`~.soco.data_structures.Queue` object This method is heavly based on Sam Soffes (aka soffes) ruby implementation
[ "Get", "information", "about", "the", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1317-L1358
train
214,776
SoCo/SoCo
soco/core.py
SoCo.add_uri_to_queue
def add_uri_to_queue(self, uri, position=0, as_next=False): """Add the URI to the queue. For arguments and return value see `add_to_queue`. """ # FIXME: The res.protocol_info should probably represent the mime type # etc of the uri. But this seems OK. res = [DidlResource(uri=uri, protocol_info="x-rincon-playlist:*:*:*")] item = DidlObject(resources=res, title='', parent_id='', item_id='') return self.add_to_queue(item, position, as_next)
python
def add_uri_to_queue(self, uri, position=0, as_next=False): """Add the URI to the queue. For arguments and return value see `add_to_queue`. """ # FIXME: The res.protocol_info should probably represent the mime type # etc of the uri. But this seems OK. res = [DidlResource(uri=uri, protocol_info="x-rincon-playlist:*:*:*")] item = DidlObject(resources=res, title='', parent_id='', item_id='') return self.add_to_queue(item, position, as_next)
[ "def", "add_uri_to_queue", "(", "self", ",", "uri", ",", "position", "=", "0", ",", "as_next", "=", "False", ")", ":", "# FIXME: The res.protocol_info should probably represent the mime type", "# etc of the uri. But this seems OK.", "res", "=", "[", "DidlResource", "(", ...
Add the URI to the queue. For arguments and return value see `add_to_queue`.
[ "Add", "the", "URI", "to", "the", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1395-L1404
train
214,777
SoCo/SoCo
soco/core.py
SoCo.add_to_queue
def add_to_queue(self, queueable_item, position=0, as_next=False): """Add a queueable item to the queue. Args: queueable_item (DidlObject or MusicServiceItem): The item to be added to the queue position (int): The index (1-based) at which the URI should be added. Default is 0 (add URI at the end of the queue). as_next (bool): Whether this URI should be played as the next track in shuffle mode. This only works if `play_mode=SHUFFLE`. Returns: int: The index of the new item in the queue. """ metadata = to_didl_string(queueable_item) response = self.avTransport.AddURIToQueue([ ('InstanceID', 0), ('EnqueuedURI', queueable_item.resources[0].uri), ('EnqueuedURIMetaData', metadata), ('DesiredFirstTrackNumberEnqueued', position), ('EnqueueAsNext', int(as_next)) ]) qnumber = response['FirstTrackNumberEnqueued'] return int(qnumber)
python
def add_to_queue(self, queueable_item, position=0, as_next=False): """Add a queueable item to the queue. Args: queueable_item (DidlObject or MusicServiceItem): The item to be added to the queue position (int): The index (1-based) at which the URI should be added. Default is 0 (add URI at the end of the queue). as_next (bool): Whether this URI should be played as the next track in shuffle mode. This only works if `play_mode=SHUFFLE`. Returns: int: The index of the new item in the queue. """ metadata = to_didl_string(queueable_item) response = self.avTransport.AddURIToQueue([ ('InstanceID', 0), ('EnqueuedURI', queueable_item.resources[0].uri), ('EnqueuedURIMetaData', metadata), ('DesiredFirstTrackNumberEnqueued', position), ('EnqueueAsNext', int(as_next)) ]) qnumber = response['FirstTrackNumberEnqueued'] return int(qnumber)
[ "def", "add_to_queue", "(", "self", ",", "queueable_item", ",", "position", "=", "0", ",", "as_next", "=", "False", ")", ":", "metadata", "=", "to_didl_string", "(", "queueable_item", ")", "response", "=", "self", ".", "avTransport", ".", "AddURIToQueue", "(...
Add a queueable item to the queue. Args: queueable_item (DidlObject or MusicServiceItem): The item to be added to the queue position (int): The index (1-based) at which the URI should be added. Default is 0 (add URI at the end of the queue). as_next (bool): Whether this URI should be played as the next track in shuffle mode. This only works if `play_mode=SHUFFLE`. Returns: int: The index of the new item in the queue.
[ "Add", "a", "queueable", "item", "to", "the", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1407-L1430
train
214,778
SoCo/SoCo
soco/core.py
SoCo.add_multiple_to_queue
def add_multiple_to_queue(self, items, container=None): """Add a sequence of items to the queue. Args: items (list): A sequence of items to the be added to the queue container (DidlObject, optional): A container object which includes the items. """ if container is not None: container_uri = container.resources[0].uri container_metadata = to_didl_string(container) else: container_uri = '' # Sonos seems to accept this as well container_metadata = '' # pylint: disable=redefined-variable-type chunk_size = 16 # With each request, we can only add 16 items item_list = list(items) # List for slicing for index in range(0, len(item_list), chunk_size): chunk = item_list[index:index + chunk_size] uris = ' '.join([item.resources[0].uri for item in chunk]) uri_metadata = ' '.join([to_didl_string(item) for item in chunk]) self.avTransport.AddMultipleURIsToQueue([ ('InstanceID', 0), ('UpdateID', 0), ('NumberOfURIs', len(chunk)), ('EnqueuedURIs', uris), ('EnqueuedURIsMetaData', uri_metadata), ('ContainerURI', container_uri), ('ContainerMetaData', container_metadata), ('DesiredFirstTrackNumberEnqueued', 0), ('EnqueueAsNext', 0) ])
python
def add_multiple_to_queue(self, items, container=None): """Add a sequence of items to the queue. Args: items (list): A sequence of items to the be added to the queue container (DidlObject, optional): A container object which includes the items. """ if container is not None: container_uri = container.resources[0].uri container_metadata = to_didl_string(container) else: container_uri = '' # Sonos seems to accept this as well container_metadata = '' # pylint: disable=redefined-variable-type chunk_size = 16 # With each request, we can only add 16 items item_list = list(items) # List for slicing for index in range(0, len(item_list), chunk_size): chunk = item_list[index:index + chunk_size] uris = ' '.join([item.resources[0].uri for item in chunk]) uri_metadata = ' '.join([to_didl_string(item) for item in chunk]) self.avTransport.AddMultipleURIsToQueue([ ('InstanceID', 0), ('UpdateID', 0), ('NumberOfURIs', len(chunk)), ('EnqueuedURIs', uris), ('EnqueuedURIsMetaData', uri_metadata), ('ContainerURI', container_uri), ('ContainerMetaData', container_metadata), ('DesiredFirstTrackNumberEnqueued', 0), ('EnqueueAsNext', 0) ])
[ "def", "add_multiple_to_queue", "(", "self", ",", "items", ",", "container", "=", "None", ")", ":", "if", "container", "is", "not", "None", ":", "container_uri", "=", "container", ".", "resources", "[", "0", "]", ".", "uri", "container_metadata", "=", "to_...
Add a sequence of items to the queue. Args: items (list): A sequence of items to the be added to the queue container (DidlObject, optional): A container object which includes the items.
[ "Add", "a", "sequence", "of", "items", "to", "the", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1432-L1463
train
214,779
SoCo/SoCo
soco/core.py
SoCo.remove_from_queue
def remove_from_queue(self, index): """Remove a track from the queue by index. The index number is required as an argument, where the first index is 0. Args: index (int): The (0-based) index of the track to remove """ # TODO: what do these parameters actually do? updid = '0' objid = 'Q:0/' + str(index + 1) self.avTransport.RemoveTrackFromQueue([ ('InstanceID', 0), ('ObjectID', objid), ('UpdateID', updid), ])
python
def remove_from_queue(self, index): """Remove a track from the queue by index. The index number is required as an argument, where the first index is 0. Args: index (int): The (0-based) index of the track to remove """ # TODO: what do these parameters actually do? updid = '0' objid = 'Q:0/' + str(index + 1) self.avTransport.RemoveTrackFromQueue([ ('InstanceID', 0), ('ObjectID', objid), ('UpdateID', updid), ])
[ "def", "remove_from_queue", "(", "self", ",", "index", ")", ":", "# TODO: what do these parameters actually do?", "updid", "=", "'0'", "objid", "=", "'Q:0/'", "+", "str", "(", "index", "+", "1", ")", "self", ".", "avTransport", ".", "RemoveTrackFromQueue", "(", ...
Remove a track from the queue by index. The index number is required as an argument, where the first index is 0. Args: index (int): The (0-based) index of the track to remove
[ "Remove", "a", "track", "from", "the", "queue", "by", "index", ".", "The", "index", "number", "is", "required", "as", "an", "argument", "where", "the", "first", "index", "is", "0", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1466-L1480
train
214,780
SoCo/SoCo
soco/core.py
SoCo.get_favorite_radio_shows
def get_favorite_radio_shows(self, start=0, max_items=100): """Get favorite radio shows from Sonos' Radio app. Returns: dict: A dictionary containing the total number of favorites, the number of favorites returned, and the actual list of favorite radio shows, represented as a dictionary with `title` and `uri` keys. Depending on what you're building, you'll want to check to see if the total number of favorites is greater than the amount you requested (`max_items`), if it is, use `start` to page through and get the entire list of favorites. """ message = 'The output type of this method will probably change in '\ 'the future to use SoCo data structures' warnings.warn(message, stacklevel=2) return self.__get_favorites(RADIO_SHOWS, start, max_items)
python
def get_favorite_radio_shows(self, start=0, max_items=100): """Get favorite radio shows from Sonos' Radio app. Returns: dict: A dictionary containing the total number of favorites, the number of favorites returned, and the actual list of favorite radio shows, represented as a dictionary with `title` and `uri` keys. Depending on what you're building, you'll want to check to see if the total number of favorites is greater than the amount you requested (`max_items`), if it is, use `start` to page through and get the entire list of favorites. """ message = 'The output type of this method will probably change in '\ 'the future to use SoCo data structures' warnings.warn(message, stacklevel=2) return self.__get_favorites(RADIO_SHOWS, start, max_items)
[ "def", "get_favorite_radio_shows", "(", "self", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "message", "=", "'The output type of this method will probably change in '", "'the future to use SoCo data structures'", "warnings", ".", "warn", "(", "message"...
Get favorite radio shows from Sonos' Radio app. Returns: dict: A dictionary containing the total number of favorites, the number of favorites returned, and the actual list of favorite radio shows, represented as a dictionary with `title` and `uri` keys. Depending on what you're building, you'll want to check to see if the total number of favorites is greater than the amount you requested (`max_items`), if it is, use `start` to page through and get the entire list of favorites.
[ "Get", "favorite", "radio", "shows", "from", "Sonos", "Radio", "app", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1490-L1506
train
214,781
SoCo/SoCo
soco/core.py
SoCo.get_favorite_radio_stations
def get_favorite_radio_stations(self, start=0, max_items=100): """Get favorite radio stations from Sonos' Radio app. See :meth:`get_favorite_radio_shows` for return type and remarks. """ message = 'The output type of this method will probably change in '\ 'the future to use SoCo data structures' warnings.warn(message, stacklevel=2) return self.__get_favorites(RADIO_STATIONS, start, max_items)
python
def get_favorite_radio_stations(self, start=0, max_items=100): """Get favorite radio stations from Sonos' Radio app. See :meth:`get_favorite_radio_shows` for return type and remarks. """ message = 'The output type of this method will probably change in '\ 'the future to use SoCo data structures' warnings.warn(message, stacklevel=2) return self.__get_favorites(RADIO_STATIONS, start, max_items)
[ "def", "get_favorite_radio_stations", "(", "self", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "message", "=", "'The output type of this method will probably change in '", "'the future to use SoCo data structures'", "warnings", ".", "warn", "(", "messa...
Get favorite radio stations from Sonos' Radio app. See :meth:`get_favorite_radio_shows` for return type and remarks.
[ "Get", "favorite", "radio", "stations", "from", "Sonos", "Radio", "app", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1510-L1518
train
214,782
SoCo/SoCo
soco/core.py
SoCo.get_sonos_favorites
def get_sonos_favorites(self, start=0, max_items=100): """Get Sonos favorites. See :meth:`get_favorite_radio_shows` for return type and remarks. """ message = 'The output type of this method will probably change in '\ 'the future to use SoCo data structures' warnings.warn(message, stacklevel=2) return self.__get_favorites(SONOS_FAVORITES, start, max_items)
python
def get_sonos_favorites(self, start=0, max_items=100): """Get Sonos favorites. See :meth:`get_favorite_radio_shows` for return type and remarks. """ message = 'The output type of this method will probably change in '\ 'the future to use SoCo data structures' warnings.warn(message, stacklevel=2) return self.__get_favorites(SONOS_FAVORITES, start, max_items)
[ "def", "get_sonos_favorites", "(", "self", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "message", "=", "'The output type of this method will probably change in '", "'the future to use SoCo data structures'", "warnings", ".", "warn", "(", "message", "...
Get Sonos favorites. See :meth:`get_favorite_radio_shows` for return type and remarks.
[ "Get", "Sonos", "favorites", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1521-L1529
train
214,783
SoCo/SoCo
soco/core.py
SoCo.create_sonos_playlist
def create_sonos_playlist(self, title): """Create a new empty Sonos playlist. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer` """ response = self.avTransport.CreateSavedQueue([ ('InstanceID', 0), ('Title', title), ('EnqueuedURI', ''), ('EnqueuedURIMetaData', ''), ]) item_id = response['AssignedObjectID'] obj_id = item_id.split(':', 2)[1] uri = "file:///jffs/settings/savedqueues.rsq#{0}".format(obj_id) res = [DidlResource(uri=uri, protocol_info="x-rincon-playlist:*:*:*")] return DidlPlaylistContainer( resources=res, title=title, parent_id='SQ:', item_id=item_id)
python
def create_sonos_playlist(self, title): """Create a new empty Sonos playlist. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer` """ response = self.avTransport.CreateSavedQueue([ ('InstanceID', 0), ('Title', title), ('EnqueuedURI', ''), ('EnqueuedURIMetaData', ''), ]) item_id = response['AssignedObjectID'] obj_id = item_id.split(':', 2)[1] uri = "file:///jffs/settings/savedqueues.rsq#{0}".format(obj_id) res = [DidlResource(uri=uri, protocol_info="x-rincon-playlist:*:*:*")] return DidlPlaylistContainer( resources=res, title=title, parent_id='SQ:', item_id=item_id)
[ "def", "create_sonos_playlist", "(", "self", ",", "title", ")", ":", "response", "=", "self", ".", "avTransport", ".", "CreateSavedQueue", "(", "[", "(", "'InstanceID'", ",", "0", ")", ",", "(", "'Title'", ",", "title", ")", ",", "(", "'EnqueuedURI'", ",...
Create a new empty Sonos playlist. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer`
[ "Create", "a", "new", "empty", "Sonos", "playlist", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1583-L1604
train
214,784
SoCo/SoCo
soco/core.py
SoCo.create_sonos_playlist_from_queue
def create_sonos_playlist_from_queue(self, title): """Create a new Sonos playlist from the current queue. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer` """ # Note: probably same as Queue service method SaveAsSonosPlaylist # but this has not been tested. This method is what the # controller uses. response = self.avTransport.SaveQueue([ ('InstanceID', 0), ('Title', title), ('ObjectID', '') ]) item_id = response['AssignedObjectID'] obj_id = item_id.split(':', 2)[1] uri = "file:///jffs/settings/savedqueues.rsq#{0}".format(obj_id) res = [DidlResource(uri=uri, protocol_info="x-rincon-playlist:*:*:*")] return DidlPlaylistContainer( resources=res, title=title, parent_id='SQ:', item_id=item_id)
python
def create_sonos_playlist_from_queue(self, title): """Create a new Sonos playlist from the current queue. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer` """ # Note: probably same as Queue service method SaveAsSonosPlaylist # but this has not been tested. This method is what the # controller uses. response = self.avTransport.SaveQueue([ ('InstanceID', 0), ('Title', title), ('ObjectID', '') ]) item_id = response['AssignedObjectID'] obj_id = item_id.split(':', 2)[1] uri = "file:///jffs/settings/savedqueues.rsq#{0}".format(obj_id) res = [DidlResource(uri=uri, protocol_info="x-rincon-playlist:*:*:*")] return DidlPlaylistContainer( resources=res, title=title, parent_id='SQ:', item_id=item_id)
[ "def", "create_sonos_playlist_from_queue", "(", "self", ",", "title", ")", ":", "# Note: probably same as Queue service method SaveAsSonosPlaylist", "# but this has not been tested. This method is what the", "# controller uses.", "response", "=", "self", ".", "avTransport", ".", "...
Create a new Sonos playlist from the current queue. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer`
[ "Create", "a", "new", "Sonos", "playlist", "from", "the", "current", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1608-L1629
train
214,785
SoCo/SoCo
soco/core.py
SoCo.remove_sonos_playlist
def remove_sonos_playlist(self, sonos_playlist): """Remove a Sonos playlist. Args: sonos_playlist (DidlPlaylistContainer): Sonos playlist to remove or the item_id (str). Returns: bool: True if succesful, False otherwise Raises: SoCoUPnPException: If sonos_playlist does not point to a valid object. """ object_id = getattr(sonos_playlist, 'item_id', sonos_playlist) return self.contentDirectory.DestroyObject([('ObjectID', object_id)])
python
def remove_sonos_playlist(self, sonos_playlist): """Remove a Sonos playlist. Args: sonos_playlist (DidlPlaylistContainer): Sonos playlist to remove or the item_id (str). Returns: bool: True if succesful, False otherwise Raises: SoCoUPnPException: If sonos_playlist does not point to a valid object. """ object_id = getattr(sonos_playlist, 'item_id', sonos_playlist) return self.contentDirectory.DestroyObject([('ObjectID', object_id)])
[ "def", "remove_sonos_playlist", "(", "self", ",", "sonos_playlist", ")", ":", "object_id", "=", "getattr", "(", "sonos_playlist", ",", "'item_id'", ",", "sonos_playlist", ")", "return", "self", ".", "contentDirectory", ".", "DestroyObject", "(", "[", "(", "'Obje...
Remove a Sonos playlist. Args: sonos_playlist (DidlPlaylistContainer): Sonos playlist to remove or the item_id (str). Returns: bool: True if succesful, False otherwise Raises: SoCoUPnPException: If sonos_playlist does not point to a valid object.
[ "Remove", "a", "Sonos", "playlist", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1632-L1648
train
214,786
SoCo/SoCo
soco/core.py
SoCo.add_item_to_sonos_playlist
def add_item_to_sonos_playlist(self, queueable_item, sonos_playlist): """Adds a queueable item to a Sonos' playlist. Args: queueable_item (DidlObject): the item to add to the Sonos' playlist sonos_playlist (DidlPlaylistContainer): the Sonos' playlist to which the item should be added """ # Get the update_id for the playlist response, _ = self.music_library._music_lib_search( sonos_playlist.item_id, 0, 1) update_id = response['UpdateID'] # Form the metadata for queueable_item metadata = to_didl_string(queueable_item) # Make the request self.avTransport.AddURIToSavedQueue([ ('InstanceID', 0), ('UpdateID', update_id), ('ObjectID', sonos_playlist.item_id), ('EnqueuedURI', queueable_item.resources[0].uri), ('EnqueuedURIMetaData', metadata), # 2 ** 32 - 1 = 4294967295, this field has always this value. Most # likely, playlist positions are represented as a 32 bit uint and # this is therefore the largest index possible. Asking to add at # this index therefore probably amounts to adding it "at the end" ('AddAtIndex', 4294967295) ])
python
def add_item_to_sonos_playlist(self, queueable_item, sonos_playlist): """Adds a queueable item to a Sonos' playlist. Args: queueable_item (DidlObject): the item to add to the Sonos' playlist sonos_playlist (DidlPlaylistContainer): the Sonos' playlist to which the item should be added """ # Get the update_id for the playlist response, _ = self.music_library._music_lib_search( sonos_playlist.item_id, 0, 1) update_id = response['UpdateID'] # Form the metadata for queueable_item metadata = to_didl_string(queueable_item) # Make the request self.avTransport.AddURIToSavedQueue([ ('InstanceID', 0), ('UpdateID', update_id), ('ObjectID', sonos_playlist.item_id), ('EnqueuedURI', queueable_item.resources[0].uri), ('EnqueuedURIMetaData', metadata), # 2 ** 32 - 1 = 4294967295, this field has always this value. Most # likely, playlist positions are represented as a 32 bit uint and # this is therefore the largest index possible. Asking to add at # this index therefore probably amounts to adding it "at the end" ('AddAtIndex', 4294967295) ])
[ "def", "add_item_to_sonos_playlist", "(", "self", ",", "queueable_item", ",", "sonos_playlist", ")", ":", "# Get the update_id for the playlist", "response", ",", "_", "=", "self", ".", "music_library", ".", "_music_lib_search", "(", "sonos_playlist", ".", "item_id", ...
Adds a queueable item to a Sonos' playlist. Args: queueable_item (DidlObject): the item to add to the Sonos' playlist sonos_playlist (DidlPlaylistContainer): the Sonos' playlist to which the item should be added
[ "Adds", "a", "queueable", "item", "to", "a", "Sonos", "playlist", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1650-L1678
train
214,787
SoCo/SoCo
soco/core.py
SoCo.get_sleep_timer
def get_sleep_timer(self): """Retrieves remaining sleep time, if any Returns: int or NoneType: Number of seconds left in timer. If there is no sleep timer currently set it will return None. """ resp = self.avTransport.GetRemainingSleepTimerDuration([ ('InstanceID', 0), ]) if resp['RemainingSleepTimerDuration']: times = resp['RemainingSleepTimerDuration'].split(':') return (int(times[0]) * 3600 + int(times[1]) * 60 + int(times[2])) else: return None
python
def get_sleep_timer(self): """Retrieves remaining sleep time, if any Returns: int or NoneType: Number of seconds left in timer. If there is no sleep timer currently set it will return None. """ resp = self.avTransport.GetRemainingSleepTimerDuration([ ('InstanceID', 0), ]) if resp['RemainingSleepTimerDuration']: times = resp['RemainingSleepTimerDuration'].split(':') return (int(times[0]) * 3600 + int(times[1]) * 60 + int(times[2])) else: return None
[ "def", "get_sleep_timer", "(", "self", ")", ":", "resp", "=", "self", ".", "avTransport", ".", "GetRemainingSleepTimerDuration", "(", "[", "(", "'InstanceID'", ",", "0", ")", ",", "]", ")", "if", "resp", "[", "'RemainingSleepTimerDuration'", "]", ":", "times...
Retrieves remaining sleep time, if any Returns: int or NoneType: Number of seconds left in timer. If there is no sleep timer currently set it will return None.
[ "Retrieves", "remaining", "sleep", "time", "if", "any" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1720-L1736
train
214,788
SoCo/SoCo
soco/core.py
SoCo.get_sonos_playlist_by_attr
def get_sonos_playlist_by_attr(self, attr_name, match): """Return the first Sonos Playlist DidlPlaylistContainer that matches the attribute specified. Args: attr_name (str): DidlPlaylistContainer attribute to compare. The most useful being: 'title' and 'item_id'. match (str): Value to match. Returns: (:class:`~.soco.data_structures.DidlPlaylistContainer`): The first matching playlist object. Raises: (AttributeError): If indicated attribute name does not exist. (ValueError): If a match can not be found. Example:: device.get_sonos_playlist_by_attr('title', 'Foo') device.get_sonos_playlist_by_attr('item_id', 'SQ:3') """ for sonos_playlist in self.get_sonos_playlists(): if getattr(sonos_playlist, attr_name) == match: return sonos_playlist raise ValueError('No match on "{0}" for value "{1}"'.format(attr_name, match))
python
def get_sonos_playlist_by_attr(self, attr_name, match): """Return the first Sonos Playlist DidlPlaylistContainer that matches the attribute specified. Args: attr_name (str): DidlPlaylistContainer attribute to compare. The most useful being: 'title' and 'item_id'. match (str): Value to match. Returns: (:class:`~.soco.data_structures.DidlPlaylistContainer`): The first matching playlist object. Raises: (AttributeError): If indicated attribute name does not exist. (ValueError): If a match can not be found. Example:: device.get_sonos_playlist_by_attr('title', 'Foo') device.get_sonos_playlist_by_attr('item_id', 'SQ:3') """ for sonos_playlist in self.get_sonos_playlists(): if getattr(sonos_playlist, attr_name) == match: return sonos_playlist raise ValueError('No match on "{0}" for value "{1}"'.format(attr_name, match))
[ "def", "get_sonos_playlist_by_attr", "(", "self", ",", "attr_name", ",", "match", ")", ":", "for", "sonos_playlist", "in", "self", ".", "get_sonos_playlists", "(", ")", ":", "if", "getattr", "(", "sonos_playlist", ",", "attr_name", ")", "==", "match", ":", "...
Return the first Sonos Playlist DidlPlaylistContainer that matches the attribute specified. Args: attr_name (str): DidlPlaylistContainer attribute to compare. The most useful being: 'title' and 'item_id'. match (str): Value to match. Returns: (:class:`~.soco.data_structures.DidlPlaylistContainer`): The first matching playlist object. Raises: (AttributeError): If indicated attribute name does not exist. (ValueError): If a match can not be found. Example:: device.get_sonos_playlist_by_attr('title', 'Foo') device.get_sonos_playlist_by_attr('item_id', 'SQ:3')
[ "Return", "the", "first", "Sonos", "Playlist", "DidlPlaylistContainer", "that", "matches", "the", "attribute", "specified", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1950-L1977
train
214,789
SoCo/SoCo
soco/utils.py
really_unicode
def really_unicode(in_string): """Make a string unicode. Really. Ensure ``in_string`` is returned as unicode through a series of progressively relaxed decodings. Args: in_string (str): The string to convert. Returns: str: Unicode. Raises: ValueError """ if isinstance(in_string, StringType): for args in (('utf-8',), ('latin-1',), ('ascii', 'replace')): try: # pylint: disable=star-args in_string = in_string.decode(*args) break except UnicodeDecodeError: continue if not isinstance(in_string, UnicodeType): raise ValueError('%s is not a string at all.' % in_string) return in_string
python
def really_unicode(in_string): """Make a string unicode. Really. Ensure ``in_string`` is returned as unicode through a series of progressively relaxed decodings. Args: in_string (str): The string to convert. Returns: str: Unicode. Raises: ValueError """ if isinstance(in_string, StringType): for args in (('utf-8',), ('latin-1',), ('ascii', 'replace')): try: # pylint: disable=star-args in_string = in_string.decode(*args) break except UnicodeDecodeError: continue if not isinstance(in_string, UnicodeType): raise ValueError('%s is not a string at all.' % in_string) return in_string
[ "def", "really_unicode", "(", "in_string", ")", ":", "if", "isinstance", "(", "in_string", ",", "StringType", ")", ":", "for", "args", "in", "(", "(", "'utf-8'", ",", ")", ",", "(", "'latin-1'", ",", ")", ",", "(", "'ascii'", ",", "'replace'", ")", "...
Make a string unicode. Really. Ensure ``in_string`` is returned as unicode through a series of progressively relaxed decodings. Args: in_string (str): The string to convert. Returns: str: Unicode. Raises: ValueError
[ "Make", "a", "string", "unicode", ".", "Really", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/utils.py#L22-L47
train
214,790
SoCo/SoCo
soco/utils.py
camel_to_underscore
def camel_to_underscore(string): """Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string. """ string = FIRST_CAP_RE.sub(r'\1_\2', string) return ALL_CAP_RE.sub(r'\1_\2', string).lower()
python
def camel_to_underscore(string): """Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string. """ string = FIRST_CAP_RE.sub(r'\1_\2', string) return ALL_CAP_RE.sub(r'\1_\2', string).lower()
[ "def", "camel_to_underscore", "(", "string", ")", ":", "string", "=", "FIRST_CAP_RE", ".", "sub", "(", "r'\\1_\\2'", ",", "string", ")", "return", "ALL_CAP_RE", ".", "sub", "(", "r'\\1_\\2'", ",", "string", ")", ".", "lower", "(", ")" ]
Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string.
[ "Convert", "camelcase", "to", "lowercase", "and", "underscore", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/utils.py#L73-L85
train
214,791
SoCo/SoCo
soco/utils.py
prettify
def prettify(unicode_text): """Return a pretty-printed version of a unicode XML string. Useful for debugging. Args: unicode_text (str): A text representation of XML (unicode, *not* utf-8). Returns: str: A pretty-printed version of the input. """ import xml.dom.minidom reparsed = xml.dom.minidom.parseString(unicode_text.encode('utf-8')) return reparsed.toprettyxml(indent=" ", newl="\n")
python
def prettify(unicode_text): """Return a pretty-printed version of a unicode XML string. Useful for debugging. Args: unicode_text (str): A text representation of XML (unicode, *not* utf-8). Returns: str: A pretty-printed version of the input. """ import xml.dom.minidom reparsed = xml.dom.minidom.parseString(unicode_text.encode('utf-8')) return reparsed.toprettyxml(indent=" ", newl="\n")
[ "def", "prettify", "(", "unicode_text", ")", ":", "import", "xml", ".", "dom", ".", "minidom", "reparsed", "=", "xml", ".", "dom", ".", "minidom", ".", "parseString", "(", "unicode_text", ".", "encode", "(", "'utf-8'", ")", ")", "return", "reparsed", "."...
Return a pretty-printed version of a unicode XML string. Useful for debugging. Args: unicode_text (str): A text representation of XML (unicode, *not* utf-8). Returns: str: A pretty-printed version of the input.
[ "Return", "a", "pretty", "-", "printed", "version", "of", "a", "unicode", "XML", "string", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/utils.py#L88-L103
train
214,792
SoCo/SoCo
soco/soap.py
SoapMessage.prepare_headers
def prepare_headers(self, http_headers, soap_action): """Prepare the http headers for sending. Add the SOAPACTION header to the others. Args: http_headers (dict): A dict in the form {'Header': 'Value,..} containing http headers to use for the http request. soap_action (str): The value of the SOAPACTION header. Returns: dict: headers including the SOAPACTION header. """ headers = {'Content-Type': 'text/xml; charset="utf-8"'} if soap_action is not None: headers.update({'SOAPACTION': '"{}"'.format(soap_action)}) if http_headers is not None: headers.update(http_headers) return headers
python
def prepare_headers(self, http_headers, soap_action): """Prepare the http headers for sending. Add the SOAPACTION header to the others. Args: http_headers (dict): A dict in the form {'Header': 'Value,..} containing http headers to use for the http request. soap_action (str): The value of the SOAPACTION header. Returns: dict: headers including the SOAPACTION header. """ headers = {'Content-Type': 'text/xml; charset="utf-8"'} if soap_action is not None: headers.update({'SOAPACTION': '"{}"'.format(soap_action)}) if http_headers is not None: headers.update(http_headers) return headers
[ "def", "prepare_headers", "(", "self", ",", "http_headers", ",", "soap_action", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'text/xml; charset=\"utf-8\"'", "}", "if", "soap_action", "is", "not", "None", ":", "headers", ".", "update", "(", "{", "'SOA...
Prepare the http headers for sending. Add the SOAPACTION header to the others. Args: http_headers (dict): A dict in the form {'Header': 'Value,..} containing http headers to use for the http request. soap_action (str): The value of the SOAPACTION header. Returns: dict: headers including the SOAPACTION header.
[ "Prepare", "the", "http", "headers", "for", "sending", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/soap.py#L147-L166
train
214,793
SoCo/SoCo
soco/soap.py
SoapMessage.prepare_soap_body
def prepare_soap_body(self, method, parameters, namespace): """Prepare the SOAP message body for sending. Args: method (str): The name of the method to call. parameters (list): A list of (name, value) tuples containing the parameters to pass to the method. namespace (str): tThe XML namespace to use for the method. Returns: str: A properly formatted SOAP Body. """ tags = [] for name, value in parameters: tag = "<{name}>{value}</{name}>".format( name=name, value=escape("%s" % value, {'"': "&quot;"})) # % converts to unicode because we are using unicode literals. # Avoids use of 'unicode' function which does not exist in python 3 tags.append(tag) wrapped_params = "".join(tags) # Prepare the SOAP Body if namespace is not None: soap_body = ( '<{method} xmlns="{namespace}">' '{params}' '</{method}>'.format( method=method, params=wrapped_params, namespace=namespace )) else: soap_body = ( '<{method}>' '{params}' '</{method}>'.format( method=method, params=wrapped_params )) return soap_body
python
def prepare_soap_body(self, method, parameters, namespace): """Prepare the SOAP message body for sending. Args: method (str): The name of the method to call. parameters (list): A list of (name, value) tuples containing the parameters to pass to the method. namespace (str): tThe XML namespace to use for the method. Returns: str: A properly formatted SOAP Body. """ tags = [] for name, value in parameters: tag = "<{name}>{value}</{name}>".format( name=name, value=escape("%s" % value, {'"': "&quot;"})) # % converts to unicode because we are using unicode literals. # Avoids use of 'unicode' function which does not exist in python 3 tags.append(tag) wrapped_params = "".join(tags) # Prepare the SOAP Body if namespace is not None: soap_body = ( '<{method} xmlns="{namespace}">' '{params}' '</{method}>'.format( method=method, params=wrapped_params, namespace=namespace )) else: soap_body = ( '<{method}>' '{params}' '</{method}>'.format( method=method, params=wrapped_params )) return soap_body
[ "def", "prepare_soap_body", "(", "self", ",", "method", ",", "parameters", ",", "namespace", ")", ":", "tags", "=", "[", "]", "for", "name", ",", "value", "in", "parameters", ":", "tag", "=", "\"<{name}>{value}</{name}>\"", ".", "format", "(", "name", "=",...
Prepare the SOAP message body for sending. Args: method (str): The name of the method to call. parameters (list): A list of (name, value) tuples containing the parameters to pass to the method. namespace (str): tThe XML namespace to use for the method. Returns: str: A properly formatted SOAP Body.
[ "Prepare", "the", "SOAP", "message", "body", "for", "sending", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/soap.py#L186-L225
train
214,794
SoCo/SoCo
soco/soap.py
SoapMessage.prepare_soap_envelope
def prepare_soap_envelope(self, prepared_soap_header, prepared_soap_body): """Prepare the SOAP Envelope for sending. Args: prepared_soap_header (str): A SOAP Header prepared by `prepare_soap_header` prepared_soap_body (str): A SOAP Body prepared by `prepare_soap_body` Returns: str: A prepared SOAP Envelope """ # pylint: disable=bad-continuation soap_env_template = ( '<?xml version="1.0"?>' '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' ' s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' '{soap_header}' '<s:Body>' '{soap_body}' '</s:Body>' '</s:Envelope>') # noqa PEP8 return soap_env_template.format( soap_header=prepared_soap_header, soap_body=prepared_soap_body)
python
def prepare_soap_envelope(self, prepared_soap_header, prepared_soap_body): """Prepare the SOAP Envelope for sending. Args: prepared_soap_header (str): A SOAP Header prepared by `prepare_soap_header` prepared_soap_body (str): A SOAP Body prepared by `prepare_soap_body` Returns: str: A prepared SOAP Envelope """ # pylint: disable=bad-continuation soap_env_template = ( '<?xml version="1.0"?>' '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' ' s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' '{soap_header}' '<s:Body>' '{soap_body}' '</s:Body>' '</s:Envelope>') # noqa PEP8 return soap_env_template.format( soap_header=prepared_soap_header, soap_body=prepared_soap_body)
[ "def", "prepare_soap_envelope", "(", "self", ",", "prepared_soap_header", ",", "prepared_soap_body", ")", ":", "# pylint: disable=bad-continuation", "soap_env_template", "=", "(", "'<?xml version=\"1.0\"?>'", "'<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"'", "' s...
Prepare the SOAP Envelope for sending. Args: prepared_soap_header (str): A SOAP Header prepared by `prepare_soap_header` prepared_soap_body (str): A SOAP Body prepared by `prepare_soap_body` Returns: str: A prepared SOAP Envelope
[ "Prepare", "the", "SOAP", "Envelope", "for", "sending", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/soap.py#L227-L252
train
214,795
SoCo/SoCo
soco/soap.py
SoapMessage.prepare
def prepare(self): """Prepare the SOAP message for sending to the server.""" headers = self.prepare_headers(self.http_headers, self.soap_action) soap_header = self.prepare_soap_header(self.soap_header) soap_body = self.prepare_soap_body( self.method, self.parameters, self.namespace ) data = self.prepare_soap_envelope(soap_header, soap_body) return (headers, data)
python
def prepare(self): """Prepare the SOAP message for sending to the server.""" headers = self.prepare_headers(self.http_headers, self.soap_action) soap_header = self.prepare_soap_header(self.soap_header) soap_body = self.prepare_soap_body( self.method, self.parameters, self.namespace ) data = self.prepare_soap_envelope(soap_header, soap_body) return (headers, data)
[ "def", "prepare", "(", "self", ")", ":", "headers", "=", "self", ".", "prepare_headers", "(", "self", ".", "http_headers", ",", "self", ".", "soap_action", ")", "soap_header", "=", "self", ".", "prepare_soap_header", "(", "self", ".", "soap_header", ")", "...
Prepare the SOAP message for sending to the server.
[ "Prepare", "the", "SOAP", "message", "for", "sending", "to", "the", "server", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/soap.py#L254-L263
train
214,796
SoCo/SoCo
soco/soap.py
SoapMessage.call
def call(self): """Call the SOAP method on the server. Returns: str: the decapusulated SOAP response from the server, still encoded as utf-8. Raises: SoapFault: if a SOAP error occurs. ~requests.exceptions.HTTPError: if an http error occurs. """ headers, data = self.prepare() # Check log level before logging XML, since prettifying it is # expensive if _LOG.isEnabledFor(logging.DEBUG): _LOG.debug("Sending %s, %s", headers, prettify(data)) response = requests.post( self.endpoint, headers=headers, data=data.encode('utf-8'), **self.request_args ) _LOG.debug("Received %s, %s", response.headers, response.text) status = response.status_code if status == 200: # The response is good. Extract the Body tree = XML.fromstring(response.content) # Get the first child of the <Body> tag. NB There should only be # one if the RPC standard is followed. body = tree.find( "{http://schemas.xmlsoap.org/soap/envelope/}Body")[0] return body elif status == 500: # We probably have a SOAP Fault tree = XML.fromstring(response.content) fault = tree.find( './/{http://schemas.xmlsoap.org/soap/envelope/}Fault' ) if fault is None: # Not a SOAP fault. Must be something else. response.raise_for_status() faultcode = fault.findtext("faultcode") faultstring = fault.findtext("faultstring") faultdetail = fault.find("detail") raise SoapFault(faultcode, faultstring, faultdetail) else: # Something else has gone wrong. Probably a network error. Let # Requests handle it response.raise_for_status() return None
python
def call(self): """Call the SOAP method on the server. Returns: str: the decapusulated SOAP response from the server, still encoded as utf-8. Raises: SoapFault: if a SOAP error occurs. ~requests.exceptions.HTTPError: if an http error occurs. """ headers, data = self.prepare() # Check log level before logging XML, since prettifying it is # expensive if _LOG.isEnabledFor(logging.DEBUG): _LOG.debug("Sending %s, %s", headers, prettify(data)) response = requests.post( self.endpoint, headers=headers, data=data.encode('utf-8'), **self.request_args ) _LOG.debug("Received %s, %s", response.headers, response.text) status = response.status_code if status == 200: # The response is good. Extract the Body tree = XML.fromstring(response.content) # Get the first child of the <Body> tag. NB There should only be # one if the RPC standard is followed. body = tree.find( "{http://schemas.xmlsoap.org/soap/envelope/}Body")[0] return body elif status == 500: # We probably have a SOAP Fault tree = XML.fromstring(response.content) fault = tree.find( './/{http://schemas.xmlsoap.org/soap/envelope/}Fault' ) if fault is None: # Not a SOAP fault. Must be something else. response.raise_for_status() faultcode = fault.findtext("faultcode") faultstring = fault.findtext("faultstring") faultdetail = fault.find("detail") raise SoapFault(faultcode, faultstring, faultdetail) else: # Something else has gone wrong. Probably a network error. Let # Requests handle it response.raise_for_status() return None
[ "def", "call", "(", "self", ")", ":", "headers", ",", "data", "=", "self", ".", "prepare", "(", ")", "# Check log level before logging XML, since prettifying it is", "# expensive", "if", "_LOG", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "_LOG"...
Call the SOAP method on the server. Returns: str: the decapusulated SOAP response from the server, still encoded as utf-8. Raises: SoapFault: if a SOAP error occurs. ~requests.exceptions.HTTPError: if an http error occurs.
[ "Call", "the", "SOAP", "method", "on", "the", "server", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/soap.py#L265-L319
train
214,797
SoCo/SoCo
dev_tools/analyse_ws.py
__build_option_parser
def __build_option_parser(): """ Build the option parser for this script """ description = """ Tool to analyze Wireshark dumps of Sonos traffic. The files that are input to this script must be in the "Wireshark/tcpdump/...-libpcap" format, which can be exported from Wireshark. To use the open in browser function, a configuration file must be written. It should be in the same directory as this script and have the name "analyse_ws.ini". An example of such a file is given below ({0} indicates the file): [General] browser_command: epiphany {0} The browser command should be any command that opens a new tab in the program you wish to read the Wireshark dumps in. Separating Sonos traffic out from the rest of the network traffic is tricky. Therefore, it will in all likelyhood increase the succes of this tool, if the traffic is filtered in Wireshark to only show traffic to and from the Sonos unit. Still, if the analysis fails, then use the debug mode. This will show you the analysis of the traffic packet by packet and give you packet numbers so you can find and analyze problematic packets in Wireshark. """ description = textwrap.dedent(description).strip() parser = \ argparse.ArgumentParser(description=description, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('file_', metavar='FILE', type=str, nargs=1, help='the file to analyze') parser.add_argument('-o', '--output-prefix', type=str, help='the output filename prefix to use') parser.add_argument('-f', '--to-file', action='store_const', const=True, help='output xml to files', default=False) parser.add_argument('-d', '--debug-analysis', action='store_const', const=True, help='writes debug information to file.debug', default=False) parser.add_argument('-m', '--disable-color', action='store_const', const=False, help='disable color in interactive mode', default=COLOR, dest='color') parser.add_argument('-c', '--enable-color', action='store_const', const=True, help='disable color in interactive mode', default=COLOR, dest='color') parser.add_argument('-b', '--to-browser', action='store_const', const=True, help='output xml to browser, implies --to-file', default=False) parser.add_argument('-e', '--external-inner-xml', action='store_const', const=True, help='show the internal separately ' 'encoded xml externally instead of re-integrating it', default=False) return parser
python
def __build_option_parser(): """ Build the option parser for this script """ description = """ Tool to analyze Wireshark dumps of Sonos traffic. The files that are input to this script must be in the "Wireshark/tcpdump/...-libpcap" format, which can be exported from Wireshark. To use the open in browser function, a configuration file must be written. It should be in the same directory as this script and have the name "analyse_ws.ini". An example of such a file is given below ({0} indicates the file): [General] browser_command: epiphany {0} The browser command should be any command that opens a new tab in the program you wish to read the Wireshark dumps in. Separating Sonos traffic out from the rest of the network traffic is tricky. Therefore, it will in all likelyhood increase the succes of this tool, if the traffic is filtered in Wireshark to only show traffic to and from the Sonos unit. Still, if the analysis fails, then use the debug mode. This will show you the analysis of the traffic packet by packet and give you packet numbers so you can find and analyze problematic packets in Wireshark. """ description = textwrap.dedent(description).strip() parser = \ argparse.ArgumentParser(description=description, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('file_', metavar='FILE', type=str, nargs=1, help='the file to analyze') parser.add_argument('-o', '--output-prefix', type=str, help='the output filename prefix to use') parser.add_argument('-f', '--to-file', action='store_const', const=True, help='output xml to files', default=False) parser.add_argument('-d', '--debug-analysis', action='store_const', const=True, help='writes debug information to file.debug', default=False) parser.add_argument('-m', '--disable-color', action='store_const', const=False, help='disable color in interactive mode', default=COLOR, dest='color') parser.add_argument('-c', '--enable-color', action='store_const', const=True, help='disable color in interactive mode', default=COLOR, dest='color') parser.add_argument('-b', '--to-browser', action='store_const', const=True, help='output xml to browser, implies --to-file', default=False) parser.add_argument('-e', '--external-inner-xml', action='store_const', const=True, help='show the internal separately ' 'encoded xml externally instead of re-integrating it', default=False) return parser
[ "def", "__build_option_parser", "(", ")", ":", "description", "=", "\"\"\"\n Tool to analyze Wireshark dumps of Sonos traffic.\n\n The files that are input to this script must be in the\n \"Wireshark/tcpdump/...-libpcap\" format, which can be exported from\n Wireshark.\n\n To use the op...
Build the option parser for this script
[ "Build", "the", "option", "parser", "for", "this", "script" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L434-L489
train
214,798
SoCo/SoCo
dev_tools/analyse_ws.py
main
def main(): """ Main method of the script """ parser = __build_option_parser() args = parser.parse_args() analyze_ws = AnalyzeWS(args) try: analyze_ws.set_file(args.file_[0]) except IOError: print 'IOError raised while reading file. Exiting!' sys.exit(3) # Start the chosen mode if args.to_file or args.to_browser: analyze_ws.to_file_mode() if args.to_browser: analyze_ws.to_browser_mode() else: analyze_ws.interactive_mode()
python
def main(): """ Main method of the script """ parser = __build_option_parser() args = parser.parse_args() analyze_ws = AnalyzeWS(args) try: analyze_ws.set_file(args.file_[0]) except IOError: print 'IOError raised while reading file. Exiting!' sys.exit(3) # Start the chosen mode if args.to_file or args.to_browser: analyze_ws.to_file_mode() if args.to_browser: analyze_ws.to_browser_mode() else: analyze_ws.interactive_mode()
[ "def", "main", "(", ")", ":", "parser", "=", "__build_option_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "analyze_ws", "=", "AnalyzeWS", "(", "args", ")", "try", ":", "analyze_ws", ".", "set_file", "(", "args", ".", "file_", ...
Main method of the script
[ "Main", "method", "of", "the", "script" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L510-L527
train
214,799