id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
233,700
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): 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
233,701
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): 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
233,702
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(): 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
233,703
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): 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
233,704
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): # 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
233,705
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): 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
233,706
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): # 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
233,707
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): 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
233,708
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): # 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
233,709
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): 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
233,710
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): 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
233,711
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): 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
233,712
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): # 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
233,713
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): 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
233,714
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): # 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
233,715
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): 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
233,716
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): 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
233,717
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 # 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
233,718
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): 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
233,719
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): 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
233,720
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): # 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
233,721
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 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
233,722
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): # 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
233,723
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): 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
233,724
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): # 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
233,725
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): @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
233,726
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'): 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
233,727
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): # 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
233,728
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): 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
233,729
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): 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
233,730
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): 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
233,731
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): 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
233,732
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): # 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
233,733
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): # 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
233,734
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): 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
233,735
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): 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
233,736
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): 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
233,737
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): 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
233,738
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): 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
233,739
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): # 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
233,740
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): 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
233,741
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): 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
233,742
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): # 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
233,743
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): 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
233,744
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): 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
233,745
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): 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
233,746
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): 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
233,747
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): # 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
233,748
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): 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
233,749
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): # 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
233,750
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): 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
233,751
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): 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
233,752
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): 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
233,753
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): 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
233,754
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): 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
233,755
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): 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
233,756
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): 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
233,757
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): # 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
233,758
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): 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
233,759
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): 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
233,760
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(): 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
233,761
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(): 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
233,762
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.set_file
def set_file(self, filename): """ Analyse the file with the captured content """ # Use the file name as prefix if none is given if self.output_prefix is None: _, self.output_prefix = os.path.split(filename) # Check if the file is present, since rdpcap will not do that if not (os.path.isfile(filename) and os.access(filename, os.R_OK)): print 'The file \'{0}\' is either not present or not readable. '\ 'Exiting!'.format(filename) sys.exit(1) try: packets = rdpcap(filename) except NameError: # Due probably to a bug in rdpcap, this kind of error raises a # NameError, because the exception that is tried to raise, is not # defined print 'The file \'{}\' is not a pcap capture file. Exiting!'\ .format(filename) sys.exit(2) for number, packet in enumerate(packets): # See if there is a field called load self._debug('\nNUMBER {0}'.format(number), no_prefix=True) try: # Will cause AttributeError if there is no load packet.getfieldval('load') # Get the full load load = packet.sprintf('%TCP.payload%') self._debug('PAYLOAD LENGTH {0}'.format(len(load)), no_prefix=True) self._debug(load, load=True) self._parse_load(load) except AttributeError: self._debug('LOAD EXCEPTION', no_prefix=True) if len(self.messages) > 0 and not self.messages[-1].write_closed: self._debug('DELETE LAST OPEN FILE') del self.messages[-1] if self.args.debug_analysis: sys.exit(0)
python
def set_file(self, filename): # Use the file name as prefix if none is given if self.output_prefix is None: _, self.output_prefix = os.path.split(filename) # Check if the file is present, since rdpcap will not do that if not (os.path.isfile(filename) and os.access(filename, os.R_OK)): print 'The file \'{0}\' is either not present or not readable. '\ 'Exiting!'.format(filename) sys.exit(1) try: packets = rdpcap(filename) except NameError: # Due probably to a bug in rdpcap, this kind of error raises a # NameError, because the exception that is tried to raise, is not # defined print 'The file \'{}\' is not a pcap capture file. Exiting!'\ .format(filename) sys.exit(2) for number, packet in enumerate(packets): # See if there is a field called load self._debug('\nNUMBER {0}'.format(number), no_prefix=True) try: # Will cause AttributeError if there is no load packet.getfieldval('load') # Get the full load load = packet.sprintf('%TCP.payload%') self._debug('PAYLOAD LENGTH {0}'.format(len(load)), no_prefix=True) self._debug(load, load=True) self._parse_load(load) except AttributeError: self._debug('LOAD EXCEPTION', no_prefix=True) if len(self.messages) > 0 and not self.messages[-1].write_closed: self._debug('DELETE LAST OPEN FILE') del self.messages[-1] if self.args.debug_analysis: sys.exit(0)
[ "def", "set_file", "(", "self", ",", "filename", ")", ":", "# Use the file name as prefix if none is given", "if", "self", ".", "output_prefix", "is", "None", ":", "_", ",", "self", ".", "output_prefix", "=", "os", ".", "path", ".", "split", "(", "filename", ...
Analyse the file with the captured content
[ "Analyse", "the", "file", "with", "the", "captured", "content" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L86-L125
233,763
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS._parse_load
def _parse_load(self, load): """ Parse the load from a single packet """ # If the load is ?? if load in ['??']: self._debug('IGNORING') # If there is a start in load elif any([start in load for start in STARTS]): self._debug('START') self.messages.append(WSPart(load, self.args)) # and there is also an end if any([end in load for end in ENDS]): self.messages[-1].finalize_content() self._debug('AND END') # If there is an end in load elif any([end in load for end in ENDS]): # If there is an open WSPart if len(self.messages) > 0 and not\ self.messages[-1].write_closed: self._debug('END ON OPEN FILE') self.messages[-1].add_content(load) self.messages[-1].finalize_content() # Ignore ends before start else: self._debug('END BUT NO OPEN FILE') else: # If there is an open WSPart if len(self.messages) > 0 and not\ self.messages[-1].write_closed: self._debug('ADD TO OPEN FILE') self.messages[-1].add_content(load) # else ignore else: self._debug('NOTHING TO DO')
python
def _parse_load(self, load): # If the load is ?? if load in ['??']: self._debug('IGNORING') # If there is a start in load elif any([start in load for start in STARTS]): self._debug('START') self.messages.append(WSPart(load, self.args)) # and there is also an end if any([end in load for end in ENDS]): self.messages[-1].finalize_content() self._debug('AND END') # If there is an end in load elif any([end in load for end in ENDS]): # If there is an open WSPart if len(self.messages) > 0 and not\ self.messages[-1].write_closed: self._debug('END ON OPEN FILE') self.messages[-1].add_content(load) self.messages[-1].finalize_content() # Ignore ends before start else: self._debug('END BUT NO OPEN FILE') else: # If there is an open WSPart if len(self.messages) > 0 and not\ self.messages[-1].write_closed: self._debug('ADD TO OPEN FILE') self.messages[-1].add_content(load) # else ignore else: self._debug('NOTHING TO DO')
[ "def", "_parse_load", "(", "self", ",", "load", ")", ":", "# If the load is ??", "if", "load", "in", "[", "'??'", "]", ":", "self", ".", "_debug", "(", "'IGNORING'", ")", "# If there is a start in load", "elif", "any", "(", "[", "start", "in", "load", "for...
Parse the load from a single packet
[ "Parse", "the", "load", "from", "a", "single", "packet" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L127-L159
233,764
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS._debug
def _debug(self, message, load=False, no_prefix=False): """ Output debug information """ if self.args.debug_analysis: if load: message = '\r\n'.join( ['# ' + line for line in message.strip().split('\r\n')] ) print '{0}\n{1}\n{0}'.format('#' * 78, message) else: # If open message and no_prefix is False if (len(self.messages) > 0 and not self.messages[-1].write_closed) and not no_prefix: print '--OPEN--> {0}'.format(message) else: print message
python
def _debug(self, message, load=False, no_prefix=False): if self.args.debug_analysis: if load: message = '\r\n'.join( ['# ' + line for line in message.strip().split('\r\n')] ) print '{0}\n{1}\n{0}'.format('#' * 78, message) else: # If open message and no_prefix is False if (len(self.messages) > 0 and not self.messages[-1].write_closed) and not no_prefix: print '--OPEN--> {0}'.format(message) else: print message
[ "def", "_debug", "(", "self", ",", "message", ",", "load", "=", "False", ",", "no_prefix", "=", "False", ")", ":", "if", "self", ".", "args", ".", "debug_analysis", ":", "if", "load", ":", "message", "=", "'\\r\\n'", ".", "join", "(", "[", "'# '", ...
Output debug information
[ "Output", "debug", "information" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L161-L175
233,765
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.to_file_mode
def to_file_mode(self): """ Write all the messages to files """ for message_no in range(len(self.messages)): self.__to_file(message_no)
python
def to_file_mode(self): for message_no in range(len(self.messages)): self.__to_file(message_no)
[ "def", "to_file_mode", "(", "self", ")", ":", "for", "message_no", "in", "range", "(", "len", "(", "self", ".", "messages", ")", ")", ":", "self", ".", "__to_file", "(", "message_no", ")" ]
Write all the messages to files
[ "Write", "all", "the", "messages", "to", "files" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L177-L180
233,766
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.__to_file
def __to_file(self, message_no): """ Write a single message to file """ filename = self.__create_file_name(message_no) try: with codecs.open(filename, mode='w', encoding=self.messages[message_no].encoding)\ as file__: file__.write(self.messages[message_no].output) except IOError as excep: print 'Unable for open the file \'{0}\' for writing. The '\ 'following exception was raised:'.format(filename) print excep print 'Exiting!' sys.exit(2) return filename
python
def __to_file(self, message_no): filename = self.__create_file_name(message_no) try: with codecs.open(filename, mode='w', encoding=self.messages[message_no].encoding)\ as file__: file__.write(self.messages[message_no].output) except IOError as excep: print 'Unable for open the file \'{0}\' for writing. The '\ 'following exception was raised:'.format(filename) print excep print 'Exiting!' sys.exit(2) return filename
[ "def", "__to_file", "(", "self", ",", "message_no", ")", ":", "filename", "=", "self", ".", "__create_file_name", "(", "message_no", ")", "try", ":", "with", "codecs", ".", "open", "(", "filename", ",", "mode", "=", "'w'", ",", "encoding", "=", "self", ...
Write a single message to file
[ "Write", "a", "single", "message", "to", "file" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L182-L196
233,767
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.__create_file_name
def __create_file_name(self, message_no): """ Create the filename to save to """ cwd = os.getcwd() filename = '{0}_{1}.xml'.format(self.output_prefix, message_no) return os.path.join(cwd, filename)
python
def __create_file_name(self, message_no): cwd = os.getcwd() filename = '{0}_{1}.xml'.format(self.output_prefix, message_no) return os.path.join(cwd, filename)
[ "def", "__create_file_name", "(", "self", ",", "message_no", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "filename", "=", "'{0}_{1}.xml'", ".", "format", "(", "self", ".", "output_prefix", ",", "message_no", ")", "return", "os", ".", "path", "."...
Create the filename to save to
[ "Create", "the", "filename", "to", "save", "to" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L198-L202
233,768
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.to_browser_mode
def to_browser_mode(self): """ Write all the messages to files and open them in the browser """ for message_no in range(len(self.messages)): self.__to_browser(message_no)
python
def to_browser_mode(self): for message_no in range(len(self.messages)): self.__to_browser(message_no)
[ "def", "to_browser_mode", "(", "self", ")", ":", "for", "message_no", "in", "range", "(", "len", "(", "self", ".", "messages", ")", ")", ":", "self", ".", "__to_browser", "(", "message_no", ")" ]
Write all the messages to files and open them in the browser
[ "Write", "all", "the", "messages", "to", "files", "and", "open", "them", "in", "the", "browser" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L204-L207
233,769
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.__to_browser
def __to_browser(self, message_no): """ Write a single message to file and open the file in a browser """ filename = self.__to_file(message_no) try: command = self.config.get('General', 'browser_command') except (ConfigParser.NoOptionError, AttributeError): print 'Incorrect or missing .ini file. See --help.' sys.exit(5) command = str(command).format(filename) command_list = command.split(' ') try: subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: print 'Unable to execute the browsercommand:' print command print 'Exiting!' sys.exit(21)
python
def __to_browser(self, message_no): filename = self.__to_file(message_no) try: command = self.config.get('General', 'browser_command') except (ConfigParser.NoOptionError, AttributeError): print 'Incorrect or missing .ini file. See --help.' sys.exit(5) command = str(command).format(filename) command_list = command.split(' ') try: subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: print 'Unable to execute the browsercommand:' print command print 'Exiting!' sys.exit(21)
[ "def", "__to_browser", "(", "self", ",", "message_no", ")", ":", "filename", "=", "self", ".", "__to_file", "(", "message_no", ")", "try", ":", "command", "=", "self", ".", "config", ".", "get", "(", "'General'", ",", "'browser_command'", ")", "except", ...
Write a single message to file and open the file in a browser
[ "Write", "a", "single", "message", "to", "file", "and", "open", "the", "file", "in", "a", "browser" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L209-L229
233,770
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.__update_window
def __update_window(self, width, height, message_no, page_no): """ Update the window with the menu and the new text """ file_exists_label = '-F-ILE' if not os.path.exists(self.__create_file_name(message_no)): file_exists_label = '(f)ile' # Clear the screen if PLATFORM == 'win32': # Ugly hack until someone figures out a better way for Windows # probably something with a cls command, but I cannot test it for _ in range(50): print else: sys.stdout.write('\x1b[2J\x1b[H') # Clear screen # Content content = self.messages[message_no].output.rstrip('\n') out = content if self.args.color: out = pygments.highlight(content, XmlLexer(), TerminalFormatter()) # Paging functionality if message_no not in self.pages: self._form_pages(message_no, content, out, height, width) # Coerce in range page_no = max(min(len(self.pages[message_no]) - 1, page_no), 0) page_content = self.pages[message_no][page_no] # Menu max_message = str(len(self.messages) - 1) position_string = u'{{0: >{0}}}/{{1: <{0}}}'.format(len(max_message)) position_string = position_string.format(message_no, max_message) # Assume less than 100 pages current_max_page = len(self.pages[message_no]) - 1 pages_string = u'{0: >2}/{1: <2}'.format(page_no, current_max_page) menu = (u'(b)rowser | {0} | Message {1} \u2193 (s)\u2191 (w) | ' u'Page {2} \u2190 (a)\u2192 (d) | (q)uit\n{3}').\ format(file_exists_label, position_string, pages_string, '-' * width) print menu print page_content return page_no
python
def __update_window(self, width, height, message_no, page_no): file_exists_label = '-F-ILE' if not os.path.exists(self.__create_file_name(message_no)): file_exists_label = '(f)ile' # Clear the screen if PLATFORM == 'win32': # Ugly hack until someone figures out a better way for Windows # probably something with a cls command, but I cannot test it for _ in range(50): print else: sys.stdout.write('\x1b[2J\x1b[H') # Clear screen # Content content = self.messages[message_no].output.rstrip('\n') out = content if self.args.color: out = pygments.highlight(content, XmlLexer(), TerminalFormatter()) # Paging functionality if message_no not in self.pages: self._form_pages(message_no, content, out, height, width) # Coerce in range page_no = max(min(len(self.pages[message_no]) - 1, page_no), 0) page_content = self.pages[message_no][page_no] # Menu max_message = str(len(self.messages) - 1) position_string = u'{{0: >{0}}}/{{1: <{0}}}'.format(len(max_message)) position_string = position_string.format(message_no, max_message) # Assume less than 100 pages current_max_page = len(self.pages[message_no]) - 1 pages_string = u'{0: >2}/{1: <2}'.format(page_no, current_max_page) menu = (u'(b)rowser | {0} | Message {1} \u2193 (s)\u2191 (w) | ' u'Page {2} \u2190 (a)\u2192 (d) | (q)uit\n{3}').\ format(file_exists_label, position_string, pages_string, '-' * width) print menu print page_content return page_no
[ "def", "__update_window", "(", "self", ",", "width", ",", "height", ",", "message_no", ",", "page_no", ")", ":", "file_exists_label", "=", "'-F-ILE'", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "__create_file_name", "(", "message_no", ...
Update the window with the menu and the new text
[ "Update", "the", "window", "with", "the", "menu", "and", "the", "new", "text" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L268-L310
233,771
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS._form_pages
def _form_pages(self, message_no, content, out, height, width): """ Form the pages """ self.pages[message_no] = [] page_height = height - 4 # 2-3 for menu, 1 for cursor outline = u'' no_lines_page = 0 for original, formatted in zip(content.split('\n'), out.split('\n')): no_lines_original = int(math.ceil(len(original) / float(width))) # Blank line if len(original) == 0: if no_lines_page + 1 <= page_height: outline += u'\n' no_lines_page += 1 else: self.pages[message_no].append(outline) outline = u'\n' no_lines_page = 1 original = formatted = u'\n' # Too large line elif no_lines_original > page_height: if len(outline) > 0: self.pages[message_no].append(outline) outline = u'' no_lines_page = 0 self.pages[message_no].append(formatted) # The line(s) can be added to the current page elif no_lines_page + no_lines_original <= page_height: if len(outline) > 0: outline += u'\n' outline += formatted no_lines_page += no_lines_original # End the page and start a new else: self.pages[message_no].append(outline) outline = formatted no_lines_page = no_lines_original # Add the remainder if len(outline) > 0: self.pages[message_no].append(outline) if len(self.pages[message_no]) == 0: self.pages[message_no].append(u'')
python
def _form_pages(self, message_no, content, out, height, width): self.pages[message_no] = [] page_height = height - 4 # 2-3 for menu, 1 for cursor outline = u'' no_lines_page = 0 for original, formatted in zip(content.split('\n'), out.split('\n')): no_lines_original = int(math.ceil(len(original) / float(width))) # Blank line if len(original) == 0: if no_lines_page + 1 <= page_height: outline += u'\n' no_lines_page += 1 else: self.pages[message_no].append(outline) outline = u'\n' no_lines_page = 1 original = formatted = u'\n' # Too large line elif no_lines_original > page_height: if len(outline) > 0: self.pages[message_no].append(outline) outline = u'' no_lines_page = 0 self.pages[message_no].append(formatted) # The line(s) can be added to the current page elif no_lines_page + no_lines_original <= page_height: if len(outline) > 0: outline += u'\n' outline += formatted no_lines_page += no_lines_original # End the page and start a new else: self.pages[message_no].append(outline) outline = formatted no_lines_page = no_lines_original # Add the remainder if len(outline) > 0: self.pages[message_no].append(outline) if len(self.pages[message_no]) == 0: self.pages[message_no].append(u'')
[ "def", "_form_pages", "(", "self", ",", "message_no", ",", "content", ",", "out", ",", "height", ",", "width", ")", ":", "self", ".", "pages", "[", "message_no", "]", "=", "[", "]", "page_height", "=", "height", "-", "4", "# 2-3 for menu, 1 for cursor", ...
Form the pages
[ "Form", "the", "pages" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L312-L353
233,772
SoCo/SoCo
dev_tools/analyse_ws.py
WSPart.finalize_content
def finalize_content(self): """ Finalize the additons """ self.write_closed = True body = self.raw_body.decode(self.encoding) self._init_xml(body) self._form_output()
python
def finalize_content(self): self.write_closed = True body = self.raw_body.decode(self.encoding) self._init_xml(body) self._form_output()
[ "def", "finalize_content", "(", "self", ")", ":", "self", ".", "write_closed", "=", "True", "body", "=", "self", ".", "raw_body", ".", "decode", "(", "self", ".", "encoding", ")", "self", ".", "_init_xml", "(", "body", ")", "self", ".", "_form_output", ...
Finalize the additons
[ "Finalize", "the", "additons" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L382-L387
233,773
SoCo/SoCo
dev_tools/analyse_ws.py
WSPart._init_xml
def _init_xml(self, body): """ Parse the present body as xml """ tree = etree.fromstring(body.encode(self.encoding), PARSER) # Extract and replace inner DIDL xml in tags for text in tree.xpath('.//text()[contains(., "DIDL")]'): item = text.getparent() didl_tree = etree.fromstring(item.text) if self.external_inner_xml: item.text = 'DIDL_REPLACEMENT_{0}'.format(len(self.inner_xml)) self.inner_xml.append(didl_tree) else: item.text = None item.append(didl_tree) # Extract and replace inner DIDL xml in properties in inner xml for inner_tree in self.inner_xml: for item in inner_tree.xpath('//*[contains(@val, "DIDL")]'): if self.external_inner_xml: didl_tree = etree.fromstring(item.attrib['val']) item.attrib['val'] = 'DIDL_REPLACEMENT_{0}'.\ format(len(self.inner_xml)) self.inner_xml.append(didl_tree) self.body_formatted = etree.tostring(tree, pretty_print=True).decode( self.encoding)
python
def _init_xml(self, body): tree = etree.fromstring(body.encode(self.encoding), PARSER) # Extract and replace inner DIDL xml in tags for text in tree.xpath('.//text()[contains(., "DIDL")]'): item = text.getparent() didl_tree = etree.fromstring(item.text) if self.external_inner_xml: item.text = 'DIDL_REPLACEMENT_{0}'.format(len(self.inner_xml)) self.inner_xml.append(didl_tree) else: item.text = None item.append(didl_tree) # Extract and replace inner DIDL xml in properties in inner xml for inner_tree in self.inner_xml: for item in inner_tree.xpath('//*[contains(@val, "DIDL")]'): if self.external_inner_xml: didl_tree = etree.fromstring(item.attrib['val']) item.attrib['val'] = 'DIDL_REPLACEMENT_{0}'.\ format(len(self.inner_xml)) self.inner_xml.append(didl_tree) self.body_formatted = etree.tostring(tree, pretty_print=True).decode( self.encoding)
[ "def", "_init_xml", "(", "self", ",", "body", ")", ":", "tree", "=", "etree", ".", "fromstring", "(", "body", ".", "encode", "(", "self", ".", "encoding", ")", ",", "PARSER", ")", "# Extract and replace inner DIDL xml in tags", "for", "text", "in", "tree", ...
Parse the present body as xml
[ "Parse", "the", "present", "body", "as", "xml" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L389-L413
233,774
SoCo/SoCo
dev_tools/analyse_ws.py
WSPart._form_output
def _form_output(self): """ Form the output """ self.output = u'' if self.external_inner_xml: self.output += u'<Dummy_tag_to_create_valid_xml_on_external_inner'\ '_xml>\n' self.output += u'<!-- BODY -->\n{0}'.format(self.body_formatted) if self.external_inner_xml: for number, didl in enumerate(self.inner_xml): self.output += u'\n<!-- DIDL_{0} -->\n{1}'.\ format(number, etree.tostring(didl, pretty_print=True)) self.output += u'</Dummy_tag_to_create_valid_xml_on_external_'\ 'inner_xml>'
python
def _form_output(self): self.output = u'' if self.external_inner_xml: self.output += u'<Dummy_tag_to_create_valid_xml_on_external_inner'\ '_xml>\n' self.output += u'<!-- BODY -->\n{0}'.format(self.body_formatted) if self.external_inner_xml: for number, didl in enumerate(self.inner_xml): self.output += u'\n<!-- DIDL_{0} -->\n{1}'.\ format(number, etree.tostring(didl, pretty_print=True)) self.output += u'</Dummy_tag_to_create_valid_xml_on_external_'\ 'inner_xml>'
[ "def", "_form_output", "(", "self", ")", ":", "self", ".", "output", "=", "u''", "if", "self", ".", "external_inner_xml", ":", "self", ".", "output", "+=", "u'<Dummy_tag_to_create_valid_xml_on_external_inner'", "'_xml>\\n'", "self", ".", "output", "+=", "u'<!-- BO...
Form the output
[ "Form", "the", "output" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L418-L431
233,775
SoCo/SoCo
soco/data_structures_entry.py
attempt_datastructure_upgrade
def attempt_datastructure_upgrade(didl_item): """Attempt to upgrade a didl_item to a music services data structure if it originates from a music services """ try: resource = didl_item.resources[0] except IndexError: _LOG.debug('Upgrade not possible, no resources') return didl_item if resource.uri.startswith('x-sonos-http'): # Get data uri = resource.uri # Now we need to create a DIDL item id. It seems to be based on the uri path = urlparse(uri).path # Strip any extensions, eg .mp3, from the end of the path path = path.rsplit('.', 1)[0] # The ID has an 8 (hex) digit prefix. But it doesn't seem to # matter what it is! item_id = '11111111{0}'.format(path) # Ignore other metadata for now, in future ask ms data # structure to upgrade metadata from the service metadata = {} try: metadata['title'] = didl_item.title except AttributeError: pass # Get class try: cls = get_class(DIDL_NAME_TO_QUALIFIED_MS_NAME[ didl_item.__class__.__name__ ]) except KeyError: # The data structure should be upgraded, but there is an entry # missing from DIDL_NAME_TO_QUALIFIED_MS_NAME. Log this as a # warning. _LOG.warning( 'DATA STRUCTURE UPGRADE FAIL. Unable to upgrade music library ' 'data structure to music service data structure because an ' 'entry is missing for %s in DIDL_NAME_TO_QUALIFIED_MS_NAME. ' 'This should be reported as a bug.', didl_item.__class__.__name__, ) return didl_item upgraded_item = cls( item_id=item_id, desc=desc_from_uri(resource.uri), resources=didl_item.resources, uri=uri, metadata_dict=metadata, ) _LOG.debug("Item %s upgraded to %s", didl_item, upgraded_item) return upgraded_item _LOG.debug('Upgrade not necessary') return didl_item
python
def attempt_datastructure_upgrade(didl_item): try: resource = didl_item.resources[0] except IndexError: _LOG.debug('Upgrade not possible, no resources') return didl_item if resource.uri.startswith('x-sonos-http'): # Get data uri = resource.uri # Now we need to create a DIDL item id. It seems to be based on the uri path = urlparse(uri).path # Strip any extensions, eg .mp3, from the end of the path path = path.rsplit('.', 1)[0] # The ID has an 8 (hex) digit prefix. But it doesn't seem to # matter what it is! item_id = '11111111{0}'.format(path) # Ignore other metadata for now, in future ask ms data # structure to upgrade metadata from the service metadata = {} try: metadata['title'] = didl_item.title except AttributeError: pass # Get class try: cls = get_class(DIDL_NAME_TO_QUALIFIED_MS_NAME[ didl_item.__class__.__name__ ]) except KeyError: # The data structure should be upgraded, but there is an entry # missing from DIDL_NAME_TO_QUALIFIED_MS_NAME. Log this as a # warning. _LOG.warning( 'DATA STRUCTURE UPGRADE FAIL. Unable to upgrade music library ' 'data structure to music service data structure because an ' 'entry is missing for %s in DIDL_NAME_TO_QUALIFIED_MS_NAME. ' 'This should be reported as a bug.', didl_item.__class__.__name__, ) return didl_item upgraded_item = cls( item_id=item_id, desc=desc_from_uri(resource.uri), resources=didl_item.resources, uri=uri, metadata_dict=metadata, ) _LOG.debug("Item %s upgraded to %s", didl_item, upgraded_item) return upgraded_item _LOG.debug('Upgrade not necessary') return didl_item
[ "def", "attempt_datastructure_upgrade", "(", "didl_item", ")", ":", "try", ":", "resource", "=", "didl_item", ".", "resources", "[", "0", "]", "except", "IndexError", ":", "_LOG", ".", "debug", "(", "'Upgrade not possible, no resources'", ")", "return", "didl_item...
Attempt to upgrade a didl_item to a music services data structure if it originates from a music services
[ "Attempt", "to", "upgrade", "a", "didl_item", "to", "a", "music", "services", "data", "structure", "if", "it", "originates", "from", "a", "music", "services" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures_entry.py#L76-L135
233,776
SoCo/SoCo
soco/plugins/__init__.py
SoCoPlugin.from_name
def from_name(cls, fullname, soco, *args, **kwargs): """Instantiate a plugin by its full name.""" _LOG.info('Loading plugin %s', fullname) parts = fullname.split('.') modname = '.'.join(parts[:-1]) clsname = parts[-1] mod = importlib.import_module(modname) class_ = getattr(mod, clsname) _LOG.info('Loaded class %s', class_) return class_(soco, *args, **kwargs)
python
def from_name(cls, fullname, soco, *args, **kwargs): _LOG.info('Loading plugin %s', fullname) parts = fullname.split('.') modname = '.'.join(parts[:-1]) clsname = parts[-1] mod = importlib.import_module(modname) class_ = getattr(mod, clsname) _LOG.info('Loaded class %s', class_) return class_(soco, *args, **kwargs)
[ "def", "from_name", "(", "cls", ",", "fullname", ",", "soco", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_LOG", ".", "info", "(", "'Loading plugin %s'", ",", "fullname", ")", "parts", "=", "fullname", ".", "split", "(", "'.'", ")", "modnam...
Instantiate a plugin by its full name.
[ "Instantiate", "a", "plugin", "by", "its", "full", "name", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/__init__.py#L34-L48
233,777
SoCo/SoCo
soco/ms_data_structures.py
get_ms_item
def get_ms_item(xml, service, parent_id): """Return the music service item that corresponds to xml. The class is identified by getting the type from the 'itemType' tag """ cls = MS_TYPE_TO_CLASS.get(xml.findtext(ns_tag('ms', 'itemType'))) out = cls.from_xml(xml, service, parent_id) return out
python
def get_ms_item(xml, service, parent_id): cls = MS_TYPE_TO_CLASS.get(xml.findtext(ns_tag('ms', 'itemType'))) out = cls.from_xml(xml, service, parent_id) return out
[ "def", "get_ms_item", "(", "xml", ",", "service", ",", "parent_id", ")", ":", "cls", "=", "MS_TYPE_TO_CLASS", ".", "get", "(", "xml", ".", "findtext", "(", "ns_tag", "(", "'ms'", ",", "'itemType'", ")", ")", ")", "out", "=", "cls", ".", "from_xml", "...
Return the music service item that corresponds to xml. The class is identified by getting the type from the 'itemType' tag
[ "Return", "the", "music", "service", "item", "that", "corresponds", "to", "xml", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L21-L28
233,778
SoCo/SoCo
soco/ms_data_structures.py
tags_with_text
def tags_with_text(xml, tags=None): """Return a list of tags that contain text retrieved recursively from an XML tree.""" if tags is None: tags = [] for element in xml: if element.text is not None: tags.append(element) elif len(element) > 0: # pylint: disable=len-as-condition tags_with_text(element, tags) else: message = 'Unknown XML structure: {}'.format(element) raise ValueError(message) return tags
python
def tags_with_text(xml, tags=None): if tags is None: tags = [] for element in xml: if element.text is not None: tags.append(element) elif len(element) > 0: # pylint: disable=len-as-condition tags_with_text(element, tags) else: message = 'Unknown XML structure: {}'.format(element) raise ValueError(message) return tags
[ "def", "tags_with_text", "(", "xml", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "for", "element", "in", "xml", ":", "if", "element", ".", "text", "is", "not", "None", ":", "tags", ".", "append", "(...
Return a list of tags that contain text retrieved recursively from an XML tree.
[ "Return", "a", "list", "of", "tags", "that", "contain", "text", "retrieved", "recursively", "from", "an", "XML", "tree", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L31-L44
233,779
SoCo/SoCo
soco/ms_data_structures.py
MusicServiceItem.from_xml
def from_xml(cls, xml, service, parent_id): """Return a Music Service item generated from xml. :param xml: Object XML. All items containing text are added to the content of the item. The class variable ``valid_fields`` of each of the classes list the valid fields (after translating the camel case to underscore notation). Required fields are listed in the class variable by that name (where 'id' has been renamed to 'item_id'). :type xml: :py:class:`xml.etree.ElementTree.Element` :param service: The music service (plugin) instance that retrieved the element. This service must contain ``id_to_extended_id`` and ``form_uri`` methods and ``description`` and ``service_id`` attributes. :type service: Instance of sub-class of :class:`soco.plugins.SoCoPlugin` :param parent_id: The parent ID of the item, will either be the extended ID of another MusicServiceItem or of a search :type parent_id: str For a track the XML can e.g. be on the following form: .. code :: xml <mediaMetadata xmlns="http://www.sonos.com/Services/1.1"> <id>trackid_141359</id> <itemType>track</itemType> <mimeType>audio/aac</mimeType> <title>Teacher</title> <trackMetadata> <artistId>artistid_10597</artistId> <artist>Jethro Tull</artist> <composerId>artistid_10597</composerId> <composer>Jethro Tull</composer> <albumId>albumid_141358</albumId> <album>MU - The Best Of Jethro Tull</album> <albumArtistId>artistid_10597</albumArtistId> <albumArtist>Jethro Tull</albumArtist> <duration>229</duration> <albumArtURI>http://varnish01.music.aspiro.com/sca/ imscale?h=90&amp;w=90&amp;img=/content/music10/prod/wmg/ 1383757201/094639008452_20131105025504431/resources/094639008452. jpg</albumArtURI> <canPlay>true</canPlay> <canSkip>true</canSkip> <canAddToFavorites>true</canAddToFavorites> </trackMetadata> </mediaMetadata> """ # Add a few extra pieces of information content = {'description': service.description, 'service_id': service.service_id, 'parent_id': parent_id} # Extract values from the XML all_text_elements = tags_with_text(xml) for item in all_text_elements: tag = item.tag[len(NAMESPACES['ms']) + 2:] # Strip namespace tag = camel_to_underscore(tag) # Convert to nice names if tag not in cls.valid_fields: message = 'The info tag \'{}\' is not allowed for this item'.\ format(tag) raise ValueError(message) content[tag] = item.text # Convert values for known types for key, value in content.items(): if key == 'duration': content[key] = int(value) if key in ['can_play', 'can_skip', 'can_add_to_favorites', 'can_enumerate']: content[key] = True if value == 'true' else False # Rename a single item content['item_id'] = content.pop('id') # And get the extended id content['extended_id'] = service.id_to_extended_id(content['item_id'], cls) # Add URI if there is one for the relevant class uri = service.form_uri(content, cls) if uri: content['uri'] = uri # Check for all required values for key in cls.required_fields: if key not in content: message = 'An XML field that correspond to the key \'{}\' '\ 'is required. See the docstring for help.'.format(key) return cls.from_dict(content)
python
def from_xml(cls, xml, service, parent_id): # Add a few extra pieces of information content = {'description': service.description, 'service_id': service.service_id, 'parent_id': parent_id} # Extract values from the XML all_text_elements = tags_with_text(xml) for item in all_text_elements: tag = item.tag[len(NAMESPACES['ms']) + 2:] # Strip namespace tag = camel_to_underscore(tag) # Convert to nice names if tag not in cls.valid_fields: message = 'The info tag \'{}\' is not allowed for this item'.\ format(tag) raise ValueError(message) content[tag] = item.text # Convert values for known types for key, value in content.items(): if key == 'duration': content[key] = int(value) if key in ['can_play', 'can_skip', 'can_add_to_favorites', 'can_enumerate']: content[key] = True if value == 'true' else False # Rename a single item content['item_id'] = content.pop('id') # And get the extended id content['extended_id'] = service.id_to_extended_id(content['item_id'], cls) # Add URI if there is one for the relevant class uri = service.form_uri(content, cls) if uri: content['uri'] = uri # Check for all required values for key in cls.required_fields: if key not in content: message = 'An XML field that correspond to the key \'{}\' '\ 'is required. See the docstring for help.'.format(key) return cls.from_dict(content)
[ "def", "from_xml", "(", "cls", ",", "xml", ",", "service", ",", "parent_id", ")", ":", "# Add a few extra pieces of information", "content", "=", "{", "'description'", ":", "service", ".", "description", ",", "'service_id'", ":", "service", ".", "service_id", ",...
Return a Music Service item generated from xml. :param xml: Object XML. All items containing text are added to the content of the item. The class variable ``valid_fields`` of each of the classes list the valid fields (after translating the camel case to underscore notation). Required fields are listed in the class variable by that name (where 'id' has been renamed to 'item_id'). :type xml: :py:class:`xml.etree.ElementTree.Element` :param service: The music service (plugin) instance that retrieved the element. This service must contain ``id_to_extended_id`` and ``form_uri`` methods and ``description`` and ``service_id`` attributes. :type service: Instance of sub-class of :class:`soco.plugins.SoCoPlugin` :param parent_id: The parent ID of the item, will either be the extended ID of another MusicServiceItem or of a search :type parent_id: str For a track the XML can e.g. be on the following form: .. code :: xml <mediaMetadata xmlns="http://www.sonos.com/Services/1.1"> <id>trackid_141359</id> <itemType>track</itemType> <mimeType>audio/aac</mimeType> <title>Teacher</title> <trackMetadata> <artistId>artistid_10597</artistId> <artist>Jethro Tull</artist> <composerId>artistid_10597</composerId> <composer>Jethro Tull</composer> <albumId>albumid_141358</albumId> <album>MU - The Best Of Jethro Tull</album> <albumArtistId>artistid_10597</albumArtistId> <albumArtist>Jethro Tull</albumArtist> <duration>229</duration> <albumArtURI>http://varnish01.music.aspiro.com/sca/ imscale?h=90&amp;w=90&amp;img=/content/music10/prod/wmg/ 1383757201/094639008452_20131105025504431/resources/094639008452. jpg</albumArtURI> <canPlay>true</canPlay> <canSkip>true</canSkip> <canAddToFavorites>true</canAddToFavorites> </trackMetadata> </mediaMetadata>
[ "Return", "a", "Music", "Service", "item", "generated", "from", "xml", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L61-L148
233,780
SoCo/SoCo
soco/ms_data_structures.py
MusicServiceItem.from_dict
def from_dict(cls, dict_in): """Initialize the class from a dict. :param dict_in: The dictionary that contains the item content. Required fields are listed class variable by that name :type dict_in: dict """ kwargs = dict_in.copy() args = [kwargs.pop(key) for key in cls.required_fields] return cls(*args, **kwargs)
python
def from_dict(cls, dict_in): kwargs = dict_in.copy() args = [kwargs.pop(key) for key in cls.required_fields] return cls(*args, **kwargs)
[ "def", "from_dict", "(", "cls", ",", "dict_in", ")", ":", "kwargs", "=", "dict_in", ".", "copy", "(", ")", "args", "=", "[", "kwargs", ".", "pop", "(", "key", ")", "for", "key", "in", "cls", ".", "required_fields", "]", "return", "cls", "(", "*", ...
Initialize the class from a dict. :param dict_in: The dictionary that contains the item content. Required fields are listed class variable by that name :type dict_in: dict
[ "Initialize", "the", "class", "from", "a", "dict", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L151-L160
233,781
SoCo/SoCo
soco/ms_data_structures.py
MusicServiceItem.didl_metadata
def didl_metadata(self): """Return the DIDL metadata for a Music Service Track. The metadata is on the form: .. code :: xml <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="...self.extended_id..." parentID="...self.parent_id..." restricted="true"> <dc:title>...self.title...</dc:title> <upnp:class>...self.item_class...</upnp:class> <desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/"> self.content['description'] </desc> </item> </DIDL-Lite> """ # Check if this item is meant to be played if not self.can_play: message = 'This item is not meant to be played and therefore '\ 'also not to create its own didl_metadata' raise DIDLMetadataError(message) # Check if we have the attributes to create the didl metadata: for key in ['extended_id', 'title', 'item_class']: if not hasattr(self, key): message = 'The property \'{}\' is not present on this item. '\ 'This indicates that this item was not meant to create '\ 'didl_metadata'.format(key) raise DIDLMetadataError(message) if 'description' not in self.content: message = 'The item for \'description\' is not present in '\ 'self.content. This indicates that this item was not meant '\ 'to create didl_metadata' raise DIDLMetadataError(message) # Main element, ugly? yes! but I have given up on using namespaces # with xml.etree.ElementTree item_attrib = { '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/' } xml = XML.Element('DIDL-Lite', item_attrib) # Item sub element item_attrib = { 'parentID': '', 'restricted': 'true', 'id': self.extended_id } # Only add the parent_id if we have it if self.parent_id: item_attrib['parentID'] = self.parent_id item = XML.SubElement(xml, 'item', item_attrib) # Add title and class XML.SubElement(item, 'dc:title').text = self.title XML.SubElement(item, 'upnp:class').text = self.item_class # Add the desc element desc_attrib = { 'id': 'cdudn', 'nameSpace': 'urn:schemas-rinconnetworks-com:metadata-1-0/' } desc = XML.SubElement(item, 'desc', desc_attrib) desc.text = self.content['description'] return xml
python
def didl_metadata(self): # Check if this item is meant to be played if not self.can_play: message = 'This item is not meant to be played and therefore '\ 'also not to create its own didl_metadata' raise DIDLMetadataError(message) # Check if we have the attributes to create the didl metadata: for key in ['extended_id', 'title', 'item_class']: if not hasattr(self, key): message = 'The property \'{}\' is not present on this item. '\ 'This indicates that this item was not meant to create '\ 'didl_metadata'.format(key) raise DIDLMetadataError(message) if 'description' not in self.content: message = 'The item for \'description\' is not present in '\ 'self.content. This indicates that this item was not meant '\ 'to create didl_metadata' raise DIDLMetadataError(message) # Main element, ugly? yes! but I have given up on using namespaces # with xml.etree.ElementTree item_attrib = { '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/' } xml = XML.Element('DIDL-Lite', item_attrib) # Item sub element item_attrib = { 'parentID': '', 'restricted': 'true', 'id': self.extended_id } # Only add the parent_id if we have it if self.parent_id: item_attrib['parentID'] = self.parent_id item = XML.SubElement(xml, 'item', item_attrib) # Add title and class XML.SubElement(item, 'dc:title').text = self.title XML.SubElement(item, 'upnp:class').text = self.item_class # Add the desc element desc_attrib = { 'id': 'cdudn', 'nameSpace': 'urn:schemas-rinconnetworks-com:metadata-1-0/' } desc = XML.SubElement(item, 'desc', desc_attrib) desc.text = self.content['description'] return xml
[ "def", "didl_metadata", "(", "self", ")", ":", "# Check if this item is meant to be played", "if", "not", "self", ".", "can_play", ":", "message", "=", "'This item is not meant to be played and therefore '", "'also not to create its own didl_metadata'", "raise", "DIDLMetadataErro...
Return the DIDL metadata for a Music Service Track. The metadata is on the form: .. code :: xml <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="...self.extended_id..." parentID="...self.parent_id..." restricted="true"> <dc:title>...self.title...</dc:title> <upnp:class>...self.item_class...</upnp:class> <desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/"> self.content['description'] </desc> </item> </DIDL-Lite>
[ "Return", "the", "DIDL", "metadata", "for", "a", "Music", "Service", "Track", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L213-L285
233,782
SoCo/SoCo
soco/alarms.py
get_alarms
def get_alarms(zone=None): """Get a set of all alarms known to the Sonos system. Args: zone (`SoCo`, optional): a SoCo instance to query. If None, a random instance is used. Defaults to `None`. Returns: set: A set of `Alarm` instances Note: Any existing `Alarm` instance will have its attributes updated to those currently stored on the Sonos system. """ # Get a soco instance to query. It doesn't matter which. if zone is None: zone = discovery.any_soco() response = zone.alarmClock.ListAlarms() alarm_list = response['CurrentAlarmList'] tree = XML.fromstring(alarm_list.encode('utf-8')) # An alarm list looks like this: # <Alarms> # <Alarm ID="14" StartTime="07:00:00" # Duration="02:00:00" Recurrence="DAILY" Enabled="1" # RoomUUID="RINCON_000ZZZZZZ1400" # ProgramURI="x-rincon-buzzer:0" ProgramMetaData="" # PlayMode="SHUFFLE_NOREPEAT" Volume="25" # IncludeLinkedZones="0"/> # <Alarm ID="15" StartTime="07:00:00" # Duration="02:00:00" Recurrence="DAILY" Enabled="1" # RoomUUID="RINCON_000ZZZZZZ01400" # ProgramURI="x-rincon-buzzer:0" ProgramMetaData="" # PlayMode="SHUFFLE_NOREPEAT" Volume="25" # IncludeLinkedZones="0"/> # </Alarms> # pylint: disable=protected-access alarms = tree.findall('Alarm') result = set() for alarm in alarms: values = alarm.attrib alarm_id = values['ID'] # If an instance already exists for this ID, update and return it. # Otherwise, create a new one and populate its values if Alarm._all_alarms.get(alarm_id): instance = Alarm._all_alarms.get(alarm_id) else: instance = Alarm(None) instance._alarm_id = alarm_id Alarm._all_alarms[instance._alarm_id] = instance instance.start_time = datetime.strptime( values['StartTime'], "%H:%M:%S").time() # NB StartTime, not # StartLocalTime, which is used by CreateAlarm instance.duration = None if values['Duration'] == '' else\ datetime.strptime(values['Duration'], "%H:%M:%S").time() instance.recurrence = values['Recurrence'] instance.enabled = values['Enabled'] == '1' instance.zone = next((z for z in zone.all_zones if z.uid == values['RoomUUID']), None) # some alarms are not associated to zones -> filter these out if instance.zone is None: continue instance.program_uri = None if values['ProgramURI'] ==\ "x-rincon-buzzer:0" else values['ProgramURI'] instance.program_metadata = values['ProgramMetaData'] instance.play_mode = values['PlayMode'] instance.volume = values['Volume'] instance.include_linked_zones = values['IncludeLinkedZones'] == '1' result.add(instance) return result
python
def get_alarms(zone=None): # Get a soco instance to query. It doesn't matter which. if zone is None: zone = discovery.any_soco() response = zone.alarmClock.ListAlarms() alarm_list = response['CurrentAlarmList'] tree = XML.fromstring(alarm_list.encode('utf-8')) # An alarm list looks like this: # <Alarms> # <Alarm ID="14" StartTime="07:00:00" # Duration="02:00:00" Recurrence="DAILY" Enabled="1" # RoomUUID="RINCON_000ZZZZZZ1400" # ProgramURI="x-rincon-buzzer:0" ProgramMetaData="" # PlayMode="SHUFFLE_NOREPEAT" Volume="25" # IncludeLinkedZones="0"/> # <Alarm ID="15" StartTime="07:00:00" # Duration="02:00:00" Recurrence="DAILY" Enabled="1" # RoomUUID="RINCON_000ZZZZZZ01400" # ProgramURI="x-rincon-buzzer:0" ProgramMetaData="" # PlayMode="SHUFFLE_NOREPEAT" Volume="25" # IncludeLinkedZones="0"/> # </Alarms> # pylint: disable=protected-access alarms = tree.findall('Alarm') result = set() for alarm in alarms: values = alarm.attrib alarm_id = values['ID'] # If an instance already exists for this ID, update and return it. # Otherwise, create a new one and populate its values if Alarm._all_alarms.get(alarm_id): instance = Alarm._all_alarms.get(alarm_id) else: instance = Alarm(None) instance._alarm_id = alarm_id Alarm._all_alarms[instance._alarm_id] = instance instance.start_time = datetime.strptime( values['StartTime'], "%H:%M:%S").time() # NB StartTime, not # StartLocalTime, which is used by CreateAlarm instance.duration = None if values['Duration'] == '' else\ datetime.strptime(values['Duration'], "%H:%M:%S").time() instance.recurrence = values['Recurrence'] instance.enabled = values['Enabled'] == '1' instance.zone = next((z for z in zone.all_zones if z.uid == values['RoomUUID']), None) # some alarms are not associated to zones -> filter these out if instance.zone is None: continue instance.program_uri = None if values['ProgramURI'] ==\ "x-rincon-buzzer:0" else values['ProgramURI'] instance.program_metadata = values['ProgramMetaData'] instance.play_mode = values['PlayMode'] instance.volume = values['Volume'] instance.include_linked_zones = values['IncludeLinkedZones'] == '1' result.add(instance) return result
[ "def", "get_alarms", "(", "zone", "=", "None", ")", ":", "# Get a soco instance to query. It doesn't matter which.", "if", "zone", "is", "None", ":", "zone", "=", "discovery", ".", "any_soco", "(", ")", "response", "=", "zone", ".", "alarmClock", ".", "ListAlarm...
Get a set of all alarms known to the Sonos system. Args: zone (`SoCo`, optional): a SoCo instance to query. If None, a random instance is used. Defaults to `None`. Returns: set: A set of `Alarm` instances Note: Any existing `Alarm` instance will have its attributes updated to those currently stored on the Sonos system.
[ "Get", "a", "set", "of", "all", "alarms", "known", "to", "the", "Sonos", "system", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L253-L325
233,783
SoCo/SoCo
soco/alarms.py
Alarm.play_mode
def play_mode(self, play_mode): """See `playmode`.""" play_mode = play_mode.upper() if play_mode not in PLAY_MODES: raise KeyError("'%s' is not a valid play mode" % play_mode) self._play_mode = play_mode
python
def play_mode(self, play_mode): play_mode = play_mode.upper() if play_mode not in PLAY_MODES: raise KeyError("'%s' is not a valid play mode" % play_mode) self._play_mode = play_mode
[ "def", "play_mode", "(", "self", ",", "play_mode", ")", ":", "play_mode", "=", "play_mode", ".", "upper", "(", ")", "if", "play_mode", "not", "in", "PLAY_MODES", ":", "raise", "KeyError", "(", "\"'%s' is not a valid play mode\"", "%", "play_mode", ")", "self",...
See `playmode`.
[ "See", "playmode", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L166-L171
233,784
SoCo/SoCo
soco/alarms.py
Alarm.volume
def volume(self, volume): """See `volume`.""" # max 100 volume = int(volume) self._volume = max(0, min(volume, 100))
python
def volume(self, volume): # max 100 volume = int(volume) self._volume = max(0, min(volume, 100))
[ "def", "volume", "(", "self", ",", "volume", ")", ":", "# max 100", "volume", "=", "int", "(", "volume", ")", "self", ".", "_volume", "=", "max", "(", "0", ",", "min", "(", "volume", ",", "100", ")", ")" ]
See `volume`.
[ "See", "volume", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L179-L183
233,785
SoCo/SoCo
soco/alarms.py
Alarm.recurrence
def recurrence(self, recurrence): """See `recurrence`.""" if not is_valid_recurrence(recurrence): raise KeyError("'%s' is not a valid recurrence value" % recurrence) self._recurrence = recurrence
python
def recurrence(self, recurrence): if not is_valid_recurrence(recurrence): raise KeyError("'%s' is not a valid recurrence value" % recurrence) self._recurrence = recurrence
[ "def", "recurrence", "(", "self", ",", "recurrence", ")", ":", "if", "not", "is_valid_recurrence", "(", "recurrence", ")", ":", "raise", "KeyError", "(", "\"'%s' is not a valid recurrence value\"", "%", "recurrence", ")", "self", ".", "_recurrence", "=", "recurren...
See `recurrence`.
[ "See", "recurrence", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L197-L202
233,786
SoCo/SoCo
soco/alarms.py
Alarm.save
def save(self): """Save the alarm to the Sonos system. Raises: ~soco.exceptions.SoCoUPnPException: if the alarm cannot be created because there is already an alarm for this room at the specified time. """ # pylint: disable=bad-continuation args = [ ('StartLocalTime', self.start_time.strftime(TIME_FORMAT)), ('Duration', '' if self.duration is None else self.duration.strftime(TIME_FORMAT)), ('Recurrence', self.recurrence), ('Enabled', '1' if self.enabled else '0'), ('RoomUUID', self.zone.uid), ('ProgramURI', "x-rincon-buzzer:0" if self.program_uri is None else self.program_uri), ('ProgramMetaData', self.program_metadata), ('PlayMode', self.play_mode), ('Volume', self.volume), ('IncludeLinkedZones', '1' if self.include_linked_zones else '0') ] if self._alarm_id is None: response = self.zone.alarmClock.CreateAlarm(args) self._alarm_id = response['AssignedID'] Alarm._all_alarms[self._alarm_id] = self else: # The alarm has been saved before. Update it instead. args.insert(0, ('ID', self._alarm_id)) self.zone.alarmClock.UpdateAlarm(args)
python
def save(self): # pylint: disable=bad-continuation args = [ ('StartLocalTime', self.start_time.strftime(TIME_FORMAT)), ('Duration', '' if self.duration is None else self.duration.strftime(TIME_FORMAT)), ('Recurrence', self.recurrence), ('Enabled', '1' if self.enabled else '0'), ('RoomUUID', self.zone.uid), ('ProgramURI', "x-rincon-buzzer:0" if self.program_uri is None else self.program_uri), ('ProgramMetaData', self.program_metadata), ('PlayMode', self.play_mode), ('Volume', self.volume), ('IncludeLinkedZones', '1' if self.include_linked_zones else '0') ] if self._alarm_id is None: response = self.zone.alarmClock.CreateAlarm(args) self._alarm_id = response['AssignedID'] Alarm._all_alarms[self._alarm_id] = self else: # The alarm has been saved before. Update it instead. args.insert(0, ('ID', self._alarm_id)) self.zone.alarmClock.UpdateAlarm(args)
[ "def", "save", "(", "self", ")", ":", "# pylint: disable=bad-continuation", "args", "=", "[", "(", "'StartLocalTime'", ",", "self", ".", "start_time", ".", "strftime", "(", "TIME_FORMAT", ")", ")", ",", "(", "'Duration'", ",", "''", "if", "self", ".", "dur...
Save the alarm to the Sonos system. Raises: ~soco.exceptions.SoCoUPnPException: if the alarm cannot be created because there is already an alarm for this room at the specified time.
[ "Save", "the", "alarm", "to", "the", "Sonos", "system", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L204-L234
233,787
SoCo/SoCo
soco/alarms.py
Alarm.remove
def remove(self): """Remove the alarm from the Sonos system. There is no need to call `save`. The Python instance is not deleted, and can be saved back to Sonos again if desired. """ self.zone.alarmClock.DestroyAlarm([ ('ID', self._alarm_id) ]) alarm_id = self._alarm_id try: del Alarm._all_alarms[alarm_id] except KeyError: pass self._alarm_id = None
python
def remove(self): self.zone.alarmClock.DestroyAlarm([ ('ID', self._alarm_id) ]) alarm_id = self._alarm_id try: del Alarm._all_alarms[alarm_id] except KeyError: pass self._alarm_id = None
[ "def", "remove", "(", "self", ")", ":", "self", ".", "zone", ".", "alarmClock", ".", "DestroyAlarm", "(", "[", "(", "'ID'", ",", "self", ".", "_alarm_id", ")", "]", ")", "alarm_id", "=", "self", ".", "_alarm_id", "try", ":", "del", "Alarm", ".", "_...
Remove the alarm from the Sonos system. There is no need to call `save`. The Python instance is not deleted, and can be saved back to Sonos again if desired.
[ "Remove", "the", "alarm", "from", "the", "Sonos", "system", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L236-L250
233,788
SoCo/SoCo
dev_tools/sonosdump.py
main
def main(): """ Run the main script """ parser = argparse.ArgumentParser( prog='', description='Dump data about Sonos services' ) parser.add_argument( '-d', '--device', default=None, help="The ip address of the device to query. " "If none is supplied, a random device will be used" ) parser.add_argument( '-s', '--service', default=None, help="Dump data relating to services matching this regexp " "only, e.g. %(prog)s -s GroupRenderingControl" ) args = parser.parse_args() # get a zone player - any one will do if args.device: device = soco.SoCo(args.device) else: device = soco.discovery.any_soco() print("Querying %s" % device.player_name) # loop over each of the available services # pylint: disable=no-member services = (srv(device) for srv in soco.services.Service.__subclasses__()) for srv in services: if args.service is None or re.search( args.service, srv.service_type): print_details(srv)
python
def main(): parser = argparse.ArgumentParser( prog='', description='Dump data about Sonos services' ) parser.add_argument( '-d', '--device', default=None, help="The ip address of the device to query. " "If none is supplied, a random device will be used" ) parser.add_argument( '-s', '--service', default=None, help="Dump data relating to services matching this regexp " "only, e.g. %(prog)s -s GroupRenderingControl" ) args = parser.parse_args() # get a zone player - any one will do if args.device: device = soco.SoCo(args.device) else: device = soco.discovery.any_soco() print("Querying %s" % device.player_name) # loop over each of the available services # pylint: disable=no-member services = (srv(device) for srv in soco.services.Service.__subclasses__()) for srv in services: if args.service is None or re.search( args.service, srv.service_type): print_details(srv)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "''", ",", "description", "=", "'Dump data about Sonos services'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--device'", ",", "default", "=", "Non...
Run the main script
[ "Run", "the", "main", "script" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/sonosdump.py#L15-L49
233,789
SoCo/SoCo
dev_tools/sonosdump.py
print_details
def print_details(srv): """ Print the details of a service """ name = srv.service_type box = "=" * 79 print("{0}\n|{1:^77}|\n{0}\n".format(box, name)) for action in srv.iter_actions(): print(action.name) print("~" * len(action.name)) print("\n Input") for arg in action.in_args: print(" ", arg) print("\n Output") for arg in action.out_args: print(" ", arg) print("\n\n")
python
def print_details(srv): name = srv.service_type box = "=" * 79 print("{0}\n|{1:^77}|\n{0}\n".format(box, name)) for action in srv.iter_actions(): print(action.name) print("~" * len(action.name)) print("\n Input") for arg in action.in_args: print(" ", arg) print("\n Output") for arg in action.out_args: print(" ", arg) print("\n\n")
[ "def", "print_details", "(", "srv", ")", ":", "name", "=", "srv", ".", "service_type", "box", "=", "\"=\"", "*", "79", "print", "(", "\"{0}\\n|{1:^77}|\\n{0}\\n\"", ".", "format", "(", "box", ",", "name", ")", ")", "for", "action", "in", "srv", ".", "i...
Print the details of a service
[ "Print", "the", "details", "of", "a", "service" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/sonosdump.py#L52-L68
233,790
SoCo/SoCo
soco/snapshot.py
Snapshot.snapshot
def snapshot(self): """Record and store the current state of a device. Returns: bool: `True` if the device is a coordinator, `False` otherwise. Useful for determining whether playing an alert on a device will ungroup it. """ # get if device coordinator (or slave) True (or False) self.is_coordinator = self.device.is_coordinator # Get information about the currently playing media media_info = self.device.avTransport.GetMediaInfo([('InstanceID', 0)]) self.media_uri = media_info['CurrentURI'] # Extract source from media uri - below some media URI value examples: # 'x-rincon-queue:RINCON_000E5859E49601400#0' # - playing a local queue always #0 for local queue) # # 'x-rincon-queue:RINCON_000E5859E49601400#6' # - playing a cloud queue where #x changes with each queue) # # -'x-rincon:RINCON_000E5859E49601400' # - a slave player pointing to coordinator player if self.media_uri.split(':')[0] == 'x-rincon-queue': # The pylint error below is a false positive, see about removing it # in the future # pylint: disable=simplifiable-if-statement if self.media_uri.split('#')[1] == '0': # playing local queue self.is_playing_queue = True else: # playing cloud queue - started from Alexa self.is_playing_cloud_queue = True # Save the volume, mute and other sound settings self.volume = self.device.volume self.mute = self.device.mute self.bass = self.device.bass self.treble = self.device.treble self.loudness = self.device.loudness # get details required for what's playing: if self.is_playing_queue: # playing from queue - save repeat, random, cross fade, track, etc. self.play_mode = self.device.play_mode self.cross_fade = self.device.cross_fade # Get information about the currently playing track track_info = self.device.get_current_track_info() if track_info is not None: position = track_info['playlist_position'] if position != "": # save as integer self.playlist_position = int(position) self.track_position = track_info['position'] else: # playing from a stream - save media metadata self.media_metadata = media_info['CurrentURIMetaData'] # Work out what the playing state is - if a coordinator if self.is_coordinator: transport_info = self.device.get_current_transport_info() if transport_info is not None: self.transport_state = transport_info[ 'current_transport_state'] # Save of the current queue if we need to self._save_queue() # return if device is a coordinator (helps usage) return self.is_coordinator
python
def snapshot(self): # get if device coordinator (or slave) True (or False) self.is_coordinator = self.device.is_coordinator # Get information about the currently playing media media_info = self.device.avTransport.GetMediaInfo([('InstanceID', 0)]) self.media_uri = media_info['CurrentURI'] # Extract source from media uri - below some media URI value examples: # 'x-rincon-queue:RINCON_000E5859E49601400#0' # - playing a local queue always #0 for local queue) # # 'x-rincon-queue:RINCON_000E5859E49601400#6' # - playing a cloud queue where #x changes with each queue) # # -'x-rincon:RINCON_000E5859E49601400' # - a slave player pointing to coordinator player if self.media_uri.split(':')[0] == 'x-rincon-queue': # The pylint error below is a false positive, see about removing it # in the future # pylint: disable=simplifiable-if-statement if self.media_uri.split('#')[1] == '0': # playing local queue self.is_playing_queue = True else: # playing cloud queue - started from Alexa self.is_playing_cloud_queue = True # Save the volume, mute and other sound settings self.volume = self.device.volume self.mute = self.device.mute self.bass = self.device.bass self.treble = self.device.treble self.loudness = self.device.loudness # get details required for what's playing: if self.is_playing_queue: # playing from queue - save repeat, random, cross fade, track, etc. self.play_mode = self.device.play_mode self.cross_fade = self.device.cross_fade # Get information about the currently playing track track_info = self.device.get_current_track_info() if track_info is not None: position = track_info['playlist_position'] if position != "": # save as integer self.playlist_position = int(position) self.track_position = track_info['position'] else: # playing from a stream - save media metadata self.media_metadata = media_info['CurrentURIMetaData'] # Work out what the playing state is - if a coordinator if self.is_coordinator: transport_info = self.device.get_current_transport_info() if transport_info is not None: self.transport_state = transport_info[ 'current_transport_state'] # Save of the current queue if we need to self._save_queue() # return if device is a coordinator (helps usage) return self.is_coordinator
[ "def", "snapshot", "(", "self", ")", ":", "# get if device coordinator (or slave) True (or False)", "self", ".", "is_coordinator", "=", "self", ".", "device", ".", "is_coordinator", "# Get information about the currently playing media", "media_info", "=", "self", ".", "devi...
Record and store the current state of a device. Returns: bool: `True` if the device is a coordinator, `False` otherwise. Useful for determining whether playing an alert on a device will ungroup it.
[ "Record", "and", "store", "the", "current", "state", "of", "a", "device", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L87-L158
233,791
SoCo/SoCo
soco/snapshot.py
Snapshot._save_queue
def _save_queue(self): """Save the current state of the queue.""" if self.queue is not None: # Maximum batch is 486, anything larger will still only # return 486 batch_size = 400 total = 0 num_return = batch_size # Need to get all the tracks in batches, but Only get the next # batch if all the items requested were in the last batch while num_return == batch_size: queue_items = self.device.get_queue(total, batch_size) # Check how many entries were returned num_return = len(queue_items) # Make sure the queue is not empty if num_return > 0: self.queue.append(queue_items) # Update the total that have been processed total = total + num_return
python
def _save_queue(self): if self.queue is not None: # Maximum batch is 486, anything larger will still only # return 486 batch_size = 400 total = 0 num_return = batch_size # Need to get all the tracks in batches, but Only get the next # batch if all the items requested were in the last batch while num_return == batch_size: queue_items = self.device.get_queue(total, batch_size) # Check how many entries were returned num_return = len(queue_items) # Make sure the queue is not empty if num_return > 0: self.queue.append(queue_items) # Update the total that have been processed total = total + num_return
[ "def", "_save_queue", "(", "self", ")", ":", "if", "self", ".", "queue", "is", "not", "None", ":", "# Maximum batch is 486, anything larger will still only", "# return 486", "batch_size", "=", "400", "total", "=", "0", "num_return", "=", "batch_size", "# Need to get...
Save the current state of the queue.
[ "Save", "the", "current", "state", "of", "the", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L255-L274
233,792
SoCo/SoCo
soco/snapshot.py
Snapshot._restore_queue
def _restore_queue(self): """Restore the previous state of the queue. Note: The restore currently adds the items back into the queue using the URI, for items the Sonos system already knows about this is OK, but for other items, they may be missing some of their metadata as it will not be automatically picked up. """ if self.queue is not None: # Clear the queue so that it can be reset self.device.clear_queue() # Now loop around all the queue entries adding them for queue_group in self.queue: for queue_item in queue_group: self.device.add_uri_to_queue(queue_item.uri)
python
def _restore_queue(self): if self.queue is not None: # Clear the queue so that it can be reset self.device.clear_queue() # Now loop around all the queue entries adding them for queue_group in self.queue: for queue_item in queue_group: self.device.add_uri_to_queue(queue_item.uri)
[ "def", "_restore_queue", "(", "self", ")", ":", "if", "self", ".", "queue", "is", "not", "None", ":", "# Clear the queue so that it can be reset", "self", ".", "device", ".", "clear_queue", "(", ")", "# Now loop around all the queue entries adding them", "for", "queue...
Restore the previous state of the queue. Note: The restore currently adds the items back into the queue using the URI, for items the Sonos system already knows about this is OK, but for other items, they may be missing some of their metadata as it will not be automatically picked up.
[ "Restore", "the", "previous", "state", "of", "the", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L276-L291
233,793
ContextLab/hypertools
hypertools/_shared/params.py
default_params
def default_params(model, update_dict=None): """ Loads and updates default model parameters Parameters ---------- model : str The name of a model update_dict : dict A dict to update default parameters Returns ---------- params : dict A dictionary of parameters """ if model in parameters: params = parameters[model].copy() else: params = None if update_dict: if params is None: params = {} params.update(update_dict) return params
python
def default_params(model, update_dict=None): if model in parameters: params = parameters[model].copy() else: params = None if update_dict: if params is None: params = {} params.update(update_dict) return params
[ "def", "default_params", "(", "model", ",", "update_dict", "=", "None", ")", ":", "if", "model", "in", "parameters", ":", "params", "=", "parameters", "[", "model", "]", ".", "copy", "(", ")", "else", ":", "params", "=", "None", "if", "update_dict", ":...
Loads and updates default model parameters Parameters ---------- model : str The name of a model update_dict : dict A dict to update default parameters Returns ---------- params : dict A dictionary of parameters
[ "Loads", "and", "updates", "default", "model", "parameters" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_shared/params.py#L18-L48
233,794
ContextLab/hypertools
hypertools/tools/describe.py
describe
def describe(x, reduce='IncrementalPCA', max_dims=None, show=True, format_data=True): """ Create plot describing covariance with as a function of number of dimensions This function correlates the raw data with reduced data to get a sense for how well the data can be summarized with n dimensions. Useful for evaluating quality of dimensionality reduced plots. Parameters ---------- x : Numpy array, DataFrame or list of arrays/dfs A list of Numpy arrays or Pandas Dataframes reduce : str or dict Decomposition/manifold learning model to use. Models supported: PCA, IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA, FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning, TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, and MDS. Can be passed as a string, but for finer control of the model parameters, pass as a dictionary, e.g. reduce={'model' : 'PCA', 'params' : {'whiten' : True}}. See scikit-learn specific model docs for details on parameters supported for each model. max_dims : int Maximum number of dimensions to consider show : bool Plot the result (default : true) format_data : bool Whether or not to first call the format_data function (default: True). Returns ---------- result : dict A dictionary with the analysis results. 'average' is the correlation by number of components for all data. 'individual' is a list of lists, where each list is a correlation by number of components vector (for each input list). """ warnings.warn('When input data is large, this computation can take a long time.') def summary(x, max_dims=None): # if data is a list, stack it if type(x) is list: x = np.vstack(x) # if max dims is not set, make it the length of the minimum number of columns if max_dims is None: if x.shape[1]>x.shape[0]: max_dims = x.shape[0] else: max_dims = x.shape[1] # correlation matrix for all dimensions alldims = get_cdist(x) corrs=[] for dims in range(2, max_dims): reduced = get_cdist(reducer(x, ndims=dims, reduce=reduce)) corrs.append(get_corr(alldims, reduced)) del reduced return corrs # common format if format_data: x = formatter(x, ppca=True) # a dictionary to store results result = {} result['average'] = summary(x, max_dims) result['individual'] = [summary(x_i, max_dims) for x_i in x] if max_dims is None: max_dims = len(result['average']) # if show, plot it if show: fig, ax = plt.subplots() ax = sns.tsplot(data=result['individual'], time=[i for i in range(2, max_dims+2)], err_style="unit_traces") ax.set_title('Correlation with raw data by number of components') ax.set_ylabel('Correlation') ax.set_xlabel('Number of components') plt.show() return result
python
def describe(x, reduce='IncrementalPCA', max_dims=None, show=True, format_data=True): warnings.warn('When input data is large, this computation can take a long time.') def summary(x, max_dims=None): # if data is a list, stack it if type(x) is list: x = np.vstack(x) # if max dims is not set, make it the length of the minimum number of columns if max_dims is None: if x.shape[1]>x.shape[0]: max_dims = x.shape[0] else: max_dims = x.shape[1] # correlation matrix for all dimensions alldims = get_cdist(x) corrs=[] for dims in range(2, max_dims): reduced = get_cdist(reducer(x, ndims=dims, reduce=reduce)) corrs.append(get_corr(alldims, reduced)) del reduced return corrs # common format if format_data: x = formatter(x, ppca=True) # a dictionary to store results result = {} result['average'] = summary(x, max_dims) result['individual'] = [summary(x_i, max_dims) for x_i in x] if max_dims is None: max_dims = len(result['average']) # if show, plot it if show: fig, ax = plt.subplots() ax = sns.tsplot(data=result['individual'], time=[i for i in range(2, max_dims+2)], err_style="unit_traces") ax.set_title('Correlation with raw data by number of components') ax.set_ylabel('Correlation') ax.set_xlabel('Number of components') plt.show() return result
[ "def", "describe", "(", "x", ",", "reduce", "=", "'IncrementalPCA'", ",", "max_dims", "=", "None", ",", "show", "=", "True", ",", "format_data", "=", "True", ")", ":", "warnings", ".", "warn", "(", "'When input data is large, this computation can take a long time....
Create plot describing covariance with as a function of number of dimensions This function correlates the raw data with reduced data to get a sense for how well the data can be summarized with n dimensions. Useful for evaluating quality of dimensionality reduced plots. Parameters ---------- x : Numpy array, DataFrame or list of arrays/dfs A list of Numpy arrays or Pandas Dataframes reduce : str or dict Decomposition/manifold learning model to use. Models supported: PCA, IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA, FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning, TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, and MDS. Can be passed as a string, but for finer control of the model parameters, pass as a dictionary, e.g. reduce={'model' : 'PCA', 'params' : {'whiten' : True}}. See scikit-learn specific model docs for details on parameters supported for each model. max_dims : int Maximum number of dimensions to consider show : bool Plot the result (default : true) format_data : bool Whether or not to first call the format_data function (default: True). Returns ---------- result : dict A dictionary with the analysis results. 'average' is the correlation by number of components for all data. 'individual' is a list of lists, where each list is a correlation by number of components vector (for each input list).
[ "Create", "plot", "describing", "covariance", "with", "as", "a", "function", "of", "number", "of", "dimensions" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/describe.py#L16-L106
233,795
ContextLab/hypertools
hypertools/tools/missing_inds.py
missing_inds
def missing_inds(x, format_data=True): """ Returns indices of missing data This function is useful to identify rows of your array that contain missing data or nans. The returned indices can be used to remove the rows with missing data, or label the missing data points that are interpolated using PPCA. Parameters ---------- x : array or list of arrays format_data : bool Whether or not to first call the format_data function (default: True). Returns ---------- inds : list, or list of lists A list of indices representing rows with missing data. If a list of numpy arrays is passed, a list of lists will be returned. """ if format_data: x = formatter(x, ppca=False) inds = [] for arr in x: if np.argwhere(np.isnan(arr)).size is 0: inds.append(None) else: inds.append(np.argwhere(np.isnan(arr))[:,0]) if len(inds) > 1: return inds else: return inds[0]
python
def missing_inds(x, format_data=True): if format_data: x = formatter(x, ppca=False) inds = [] for arr in x: if np.argwhere(np.isnan(arr)).size is 0: inds.append(None) else: inds.append(np.argwhere(np.isnan(arr))[:,0]) if len(inds) > 1: return inds else: return inds[0]
[ "def", "missing_inds", "(", "x", ",", "format_data", "=", "True", ")", ":", "if", "format_data", ":", "x", "=", "formatter", "(", "x", ",", "ppca", "=", "False", ")", "inds", "=", "[", "]", "for", "arr", "in", "x", ":", "if", "np", ".", "argwhere...
Returns indices of missing data This function is useful to identify rows of your array that contain missing data or nans. The returned indices can be used to remove the rows with missing data, or label the missing data points that are interpolated using PPCA. Parameters ---------- x : array or list of arrays format_data : bool Whether or not to first call the format_data function (default: True). Returns ---------- inds : list, or list of lists A list of indices representing rows with missing data. If a list of numpy arrays is passed, a list of lists will be returned.
[ "Returns", "indices", "of", "missing", "data" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/missing_inds.py#L7-L43
233,796
ContextLab/hypertools
hypertools/tools/normalize.py
normalize
def normalize(x, normalize='across', internal=False, format_data=True): """ Z-transform the columns or rows of an array, or list of arrays This function normalizes the rows or columns of the input array(s). This can be useful because data reduction and machine learning techniques are sensitive to scaling differences between features. By default, the function is set to normalize 'across' the columns of all lists, but it can also normalize the columns 'within' each individual list, or alternatively, for each row in the array. Parameters ---------- x : Numpy array or list of arrays This can either be a single array, or list of arrays normalize : str or False or None If set to 'across', the columns of the input data will be z-scored across lists (default). That is, the z-scores will be computed with with respect to column n across all arrays passed in the list. If set to 'within', the columns will be z-scored within each list that is passed. If set to 'row', each row of the input data will be z-scored. If set to False, the input data will be returned with no z-scoring. format_data : bool Whether or not to first call the format_data function (default: True). Returns ---------- normalized_x : Numpy array or list of arrays An array or list of arrays where the columns or rows are z-scored. If the input was a list, a list is returned. Otherwise, an array is returned. """ assert normalize in ['across','within','row', False, None], "scale_type must be across, within, row or none." if normalize in [False, None]: return x else: if format_data: x = formatter(x, ppca=True) zscore = lambda X, y: (y - np.mean(X)) / np.std(X) if len(set(y)) > 1 else np.zeros(y.shape) if normalize == 'across': x_stacked=np.vstack(x) normalized_x = [np.array([zscore(x_stacked[:,j], i[:,j]) for j in range(i.shape[1])]).T for i in x] elif normalize == 'within': normalized_x = [np.array([zscore(i[:,j], i[:,j]) for j in range(i.shape[1])]).T for i in x] elif normalize == 'row': normalized_x = [np.array([zscore(i[j,:], i[j,:]) for j in range(i.shape[0])]) for i in x] if internal or len(normalized_x)>1: return normalized_x else: return normalized_x[0]
python
def normalize(x, normalize='across', internal=False, format_data=True): assert normalize in ['across','within','row', False, None], "scale_type must be across, within, row or none." if normalize in [False, None]: return x else: if format_data: x = formatter(x, ppca=True) zscore = lambda X, y: (y - np.mean(X)) / np.std(X) if len(set(y)) > 1 else np.zeros(y.shape) if normalize == 'across': x_stacked=np.vstack(x) normalized_x = [np.array([zscore(x_stacked[:,j], i[:,j]) for j in range(i.shape[1])]).T for i in x] elif normalize == 'within': normalized_x = [np.array([zscore(i[:,j], i[:,j]) for j in range(i.shape[1])]).T for i in x] elif normalize == 'row': normalized_x = [np.array([zscore(i[j,:], i[j,:]) for j in range(i.shape[0])]) for i in x] if internal or len(normalized_x)>1: return normalized_x else: return normalized_x[0]
[ "def", "normalize", "(", "x", ",", "normalize", "=", "'across'", ",", "internal", "=", "False", ",", "format_data", "=", "True", ")", ":", "assert", "normalize", "in", "[", "'across'", ",", "'within'", ",", "'row'", ",", "False", ",", "None", "]", ",",...
Z-transform the columns or rows of an array, or list of arrays This function normalizes the rows or columns of the input array(s). This can be useful because data reduction and machine learning techniques are sensitive to scaling differences between features. By default, the function is set to normalize 'across' the columns of all lists, but it can also normalize the columns 'within' each individual list, or alternatively, for each row in the array. Parameters ---------- x : Numpy array or list of arrays This can either be a single array, or list of arrays normalize : str or False or None If set to 'across', the columns of the input data will be z-scored across lists (default). That is, the z-scores will be computed with with respect to column n across all arrays passed in the list. If set to 'within', the columns will be z-scored within each list that is passed. If set to 'row', each row of the input data will be z-scored. If set to False, the input data will be returned with no z-scoring. format_data : bool Whether or not to first call the format_data function (default: True). Returns ---------- normalized_x : Numpy array or list of arrays An array or list of arrays where the columns or rows are z-scored. If the input was a list, a list is returned. Otherwise, an array is returned.
[ "Z", "-", "transform", "the", "columns", "or", "rows", "of", "an", "array", "or", "list", "of", "arrays" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/normalize.py#L12-L72
233,797
ContextLab/hypertools
hypertools/_externals/srm.py
SRM._init_structures
def _init_structures(self, data, subjects): """Initializes data structures for SRM and preprocess the data. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. subjects : int The total number of subjects in `data`. Returns ------- x : list of array, element i has shape=[voxels_i, samples] Demeaned data for each subject. mu : list of array, element i has shape=[voxels_i] Voxel means over samples, per subject. rho2 : array, shape=[subjects] Noise variance :math:`\\rho^2` per subject. trace_xtx : array, shape=[subjects] The squared Frobenius norm of the demeaned data in `x`. """ x = [] mu = [] rho2 = np.zeros(subjects) trace_xtx = np.zeros(subjects) for subject in range(subjects): mu.append(np.mean(data[subject], 1)) rho2[subject] = 1 trace_xtx[subject] = np.sum(data[subject] ** 2) x.append(data[subject] - mu[subject][:, np.newaxis]) return x, mu, rho2, trace_xtx
python
def _init_structures(self, data, subjects): x = [] mu = [] rho2 = np.zeros(subjects) trace_xtx = np.zeros(subjects) for subject in range(subjects): mu.append(np.mean(data[subject], 1)) rho2[subject] = 1 trace_xtx[subject] = np.sum(data[subject] ** 2) x.append(data[subject] - mu[subject][:, np.newaxis]) return x, mu, rho2, trace_xtx
[ "def", "_init_structures", "(", "self", ",", "data", ",", "subjects", ")", ":", "x", "=", "[", "]", "mu", "=", "[", "]", "rho2", "=", "np", ".", "zeros", "(", "subjects", ")", "trace_xtx", "=", "np", ".", "zeros", "(", "subjects", ")", "for", "su...
Initializes data structures for SRM and preprocess the data. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. subjects : int The total number of subjects in `data`. Returns ------- x : list of array, element i has shape=[voxels_i, samples] Demeaned data for each subject. mu : list of array, element i has shape=[voxels_i] Voxel means over samples, per subject. rho2 : array, shape=[subjects] Noise variance :math:`\\rho^2` per subject. trace_xtx : array, shape=[subjects] The squared Frobenius norm of the demeaned data in `x`.
[ "Initializes", "data", "structures", "for", "SRM", "and", "preprocess", "the", "data", "." ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_externals/srm.py#L232-L270
233,798
ContextLab/hypertools
hypertools/_externals/srm.py
SRM._likelihood
def _likelihood(self, chol_sigma_s_rhos, log_det_psi, chol_sigma_s, trace_xt_invsigma2_x, inv_sigma_s_rhos, wt_invpsi_x, samples): """Calculate the log-likelihood function Parameters ---------- chol_sigma_s_rhos : array, shape=[features, features] Cholesky factorization of the matrix (Sigma_S + sum_i(1/rho_i^2) * I) log_det_psi : float Determinant of diagonal matrix Psi (containing the rho_i^2 value voxels_i times). chol_sigma_s : array, shape=[features, features] Cholesky factorization of the matrix Sigma_S trace_xt_invsigma2_x : float Trace of :math:`\\sum_i (||X_i||_F^2/\\rho_i^2)` inv_sigma_s_rhos : array, shape=[features, features] Inverse of :math:`(\\Sigma_S + \\sum_i(1/\\rho_i^2) * I)` wt_invpsi_x : array, shape=[features, samples] samples : int The total number of samples in the data. Returns ------- loglikehood : float The log-likelihood value. """ log_det = (np.log(np.diag(chol_sigma_s_rhos) ** 2).sum() + log_det_psi + np.log(np.diag(chol_sigma_s) ** 2).sum()) loglikehood = -0.5 * samples * log_det - 0.5 * trace_xt_invsigma2_x loglikehood += 0.5 * np.trace( wt_invpsi_x.T.dot(inv_sigma_s_rhos).dot(wt_invpsi_x)) # + const --> -0.5*nTR*nvoxel*subjects*math.log(2*math.pi) return loglikehood
python
def _likelihood(self, chol_sigma_s_rhos, log_det_psi, chol_sigma_s, trace_xt_invsigma2_x, inv_sigma_s_rhos, wt_invpsi_x, samples): log_det = (np.log(np.diag(chol_sigma_s_rhos) ** 2).sum() + log_det_psi + np.log(np.diag(chol_sigma_s) ** 2).sum()) loglikehood = -0.5 * samples * log_det - 0.5 * trace_xt_invsigma2_x loglikehood += 0.5 * np.trace( wt_invpsi_x.T.dot(inv_sigma_s_rhos).dot(wt_invpsi_x)) # + const --> -0.5*nTR*nvoxel*subjects*math.log(2*math.pi) return loglikehood
[ "def", "_likelihood", "(", "self", ",", "chol_sigma_s_rhos", ",", "log_det_psi", ",", "chol_sigma_s", ",", "trace_xt_invsigma2_x", ",", "inv_sigma_s_rhos", ",", "wt_invpsi_x", ",", "samples", ")", ":", "log_det", "=", "(", "np", ".", "log", "(", "np", ".", "...
Calculate the log-likelihood function Parameters ---------- chol_sigma_s_rhos : array, shape=[features, features] Cholesky factorization of the matrix (Sigma_S + sum_i(1/rho_i^2) * I) log_det_psi : float Determinant of diagonal matrix Psi (containing the rho_i^2 value voxels_i times). chol_sigma_s : array, shape=[features, features] Cholesky factorization of the matrix Sigma_S trace_xt_invsigma2_x : float Trace of :math:`\\sum_i (||X_i||_F^2/\\rho_i^2)` inv_sigma_s_rhos : array, shape=[features, features] Inverse of :math:`(\\Sigma_S + \\sum_i(1/\\rho_i^2) * I)` wt_invpsi_x : array, shape=[features, samples] samples : int The total number of samples in the data. Returns ------- loglikehood : float The log-likelihood value.
[ "Calculate", "the", "log", "-", "likelihood", "function" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_externals/srm.py#L272-L317
233,799
ContextLab/hypertools
hypertools/_externals/srm.py
DetSRM.fit
def fit(self, X, y=None): """Compute the Deterministic Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. y : not used """ logger.info('Starting Deterministic SRM') # Check the number of subjects if len(X) <= 1: raise ValueError("There are not enough subjects " "({0:d}) to train the model.".format(len(X))) # Check for input data sizes if X[0].shape[1] < self.features: raise ValueError( "There are not enough samples to train the model with " "{0:d} features.".format(self.features)) # Check if all subjects have same number of TRs number_trs = X[0].shape[1] number_subjects = len(X) for subject in range(number_subjects): assert_all_finite(X[subject]) if X[subject].shape[1] != number_trs: raise ValueError("Different number of samples between subjects" ".") # Run SRM self.w_, self.s_ = self._srm(X) return self
python
def fit(self, X, y=None): logger.info('Starting Deterministic SRM') # Check the number of subjects if len(X) <= 1: raise ValueError("There are not enough subjects " "({0:d}) to train the model.".format(len(X))) # Check for input data sizes if X[0].shape[1] < self.features: raise ValueError( "There are not enough samples to train the model with " "{0:d} features.".format(self.features)) # Check if all subjects have same number of TRs number_trs = X[0].shape[1] number_subjects = len(X) for subject in range(number_subjects): assert_all_finite(X[subject]) if X[subject].shape[1] != number_trs: raise ValueError("Different number of samples between subjects" ".") # Run SRM self.w_, self.s_ = self._srm(X) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "logger", ".", "info", "(", "'Starting Deterministic SRM'", ")", "# Check the number of subjects", "if", "len", "(", "X", ")", "<=", "1", ":", "raise", "ValueError", "(", "\"There are no...
Compute the Deterministic Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. y : not used
[ "Compute", "the", "Deterministic", "Shared", "Response", "Model" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_externals/srm.py#L488-L523