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,600
cloudtools/stacker
stacker/session_cache.py
get_session
def get_session(region, profile=None): """Creates a boto3 session with a cache Args: region (str): The region for the session profile (str): The profile for the session Returns: :class:`boto3.session.Session`: A boto3 session with credential caching """ if profile is None: logger.debug("No AWS profile explicitly provided. " "Falling back to default.") profile = default_profile logger.debug("Building session using profile \"%s\" in region \"%s\"" % (profile, region)) session = boto3.Session(region_name=region, profile_name=profile) c = session._session.get_component('credential_provider') provider = c.get_provider('assume-role') provider.cache = credential_cache provider._prompter = ui.getpass return session
python
def get_session(region, profile=None): if profile is None: logger.debug("No AWS profile explicitly provided. " "Falling back to default.") profile = default_profile logger.debug("Building session using profile \"%s\" in region \"%s\"" % (profile, region)) session = boto3.Session(region_name=region, profile_name=profile) c = session._session.get_component('credential_provider') provider = c.get_provider('assume-role') provider.cache = credential_cache provider._prompter = ui.getpass return session
[ "def", "get_session", "(", "region", ",", "profile", "=", "None", ")", ":", "if", "profile", "is", "None", ":", "logger", ".", "debug", "(", "\"No AWS profile explicitly provided. \"", "\"Falling back to default.\"", ")", "profile", "=", "default_profile", "logger",...
Creates a boto3 session with a cache Args: region (str): The region for the session profile (str): The profile for the session Returns: :class:`boto3.session.Session`: A boto3 session with credential caching
[ "Creates", "a", "boto3", "session", "with", "a", "cache" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/session_cache.py#L20-L44
233,601
cloudtools/stacker
stacker/lookups/registry.py
register_lookup_handler
def register_lookup_handler(lookup_type, handler_or_path): """Register a lookup handler. Args: lookup_type (str): Name to register the handler under handler_or_path (OneOf[func, str]): a function or a path to a handler """ handler = handler_or_path if isinstance(handler_or_path, basestring): handler = load_object_from_string(handler_or_path) LOOKUP_HANDLERS[lookup_type] = handler if type(handler) != type: # Hander is a not a new-style handler logger = logging.getLogger(__name__) logger.warning("Registering lookup `%s`: Please upgrade to use the " "new style of Lookups." % lookup_type) warnings.warn( # For some reason, this does not show up... # Leaving it in anyway "Lookup `%s`: Please upgrade to use the new style of Lookups" "." % lookup_type, DeprecationWarning, stacklevel=2, )
python
def register_lookup_handler(lookup_type, handler_or_path): handler = handler_or_path if isinstance(handler_or_path, basestring): handler = load_object_from_string(handler_or_path) LOOKUP_HANDLERS[lookup_type] = handler if type(handler) != type: # Hander is a not a new-style handler logger = logging.getLogger(__name__) logger.warning("Registering lookup `%s`: Please upgrade to use the " "new style of Lookups." % lookup_type) warnings.warn( # For some reason, this does not show up... # Leaving it in anyway "Lookup `%s`: Please upgrade to use the new style of Lookups" "." % lookup_type, DeprecationWarning, stacklevel=2, )
[ "def", "register_lookup_handler", "(", "lookup_type", ",", "handler_or_path", ")", ":", "handler", "=", "handler_or_path", "if", "isinstance", "(", "handler_or_path", ",", "basestring", ")", ":", "handler", "=", "load_object_from_string", "(", "handler_or_path", ")", ...
Register a lookup handler. Args: lookup_type (str): Name to register the handler under handler_or_path (OneOf[func, str]): a function or a path to a handler
[ "Register", "a", "lookup", "handler", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/registry.py#L29-L53
233,602
cloudtools/stacker
stacker/lookups/registry.py
resolve_lookups
def resolve_lookups(variable, context, provider): """Resolve a set of lookups. Args: variable (:class:`stacker.variables.Variable`): The variable resolving it's lookups. context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider Returns: dict: dict of Lookup -> resolved value """ resolved_lookups = {} for lookup in variable.lookups: try: handler = LOOKUP_HANDLERS[lookup.type] except KeyError: raise UnknownLookupType(lookup) try: resolved_lookups[lookup] = handler( value=lookup.input, context=context, provider=provider, ) except Exception as e: raise FailedVariableLookup(variable.name, lookup, e) return resolved_lookups
python
def resolve_lookups(variable, context, provider): resolved_lookups = {} for lookup in variable.lookups: try: handler = LOOKUP_HANDLERS[lookup.type] except KeyError: raise UnknownLookupType(lookup) try: resolved_lookups[lookup] = handler( value=lookup.input, context=context, provider=provider, ) except Exception as e: raise FailedVariableLookup(variable.name, lookup, e) return resolved_lookups
[ "def", "resolve_lookups", "(", "variable", ",", "context", ",", "provider", ")", ":", "resolved_lookups", "=", "{", "}", "for", "lookup", "in", "variable", ".", "lookups", ":", "try", ":", "handler", "=", "LOOKUP_HANDLERS", "[", "lookup", ".", "type", "]",...
Resolve a set of lookups. Args: variable (:class:`stacker.variables.Variable`): The variable resolving it's lookups. context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider Returns: dict: dict of Lookup -> resolved value
[ "Resolve", "a", "set", "of", "lookups", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/registry.py#L69-L97
233,603
cloudtools/stacker
stacker/lookups/handlers/default.py
DefaultLookup.handle
def handle(cls, value, **kwargs): """Use a value from the environment or fall back to a default if the environment doesn't contain the variable. Format of value: <env_var>::<default value> For example: Groups: ${default app_security_groups::sg-12345,sg-67890} If `app_security_groups` is defined in the environment, its defined value will be returned. Otherwise, `sg-12345,sg-67890` will be the returned value. This allows defaults to be set at the config file level. """ try: env_var_name, default_val = value.split("::", 1) except ValueError: raise ValueError("Invalid value for default: %s. Must be in " "<env_var>::<default value> format." % value) if env_var_name in kwargs['context'].environment: return kwargs['context'].environment[env_var_name] else: return default_val
python
def handle(cls, value, **kwargs): try: env_var_name, default_val = value.split("::", 1) except ValueError: raise ValueError("Invalid value for default: %s. Must be in " "<env_var>::<default value> format." % value) if env_var_name in kwargs['context'].environment: return kwargs['context'].environment[env_var_name] else: return default_val
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "try", ":", "env_var_name", ",", "default_val", "=", "value", ".", "split", "(", "\"::\"", ",", "1", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Invalid ...
Use a value from the environment or fall back to a default if the environment doesn't contain the variable. Format of value: <env_var>::<default value> For example: Groups: ${default app_security_groups::sg-12345,sg-67890} If `app_security_groups` is defined in the environment, its defined value will be returned. Otherwise, `sg-12345,sg-67890` will be the returned value. This allows defaults to be set at the config file level.
[ "Use", "a", "value", "from", "the", "environment", "or", "fall", "back", "to", "a", "default", "if", "the", "environment", "doesn", "t", "contain", "the", "variable", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/default.py#L13-L41
233,604
cloudtools/stacker
stacker/lookups/__init__.py
extract_lookups_from_string
def extract_lookups_from_string(value): """Extract any lookups within a string. Args: value (str): string value we're extracting lookups from Returns: list: list of :class:`stacker.lookups.Lookup` if any """ lookups = set() for match in LOOKUP_REGEX.finditer(value): groupdict = match.groupdict() raw = match.groups()[0] lookup_type = groupdict["type"] lookup_input = groupdict["input"] lookups.add(Lookup(lookup_type, lookup_input, raw)) return lookups
python
def extract_lookups_from_string(value): lookups = set() for match in LOOKUP_REGEX.finditer(value): groupdict = match.groupdict() raw = match.groups()[0] lookup_type = groupdict["type"] lookup_input = groupdict["input"] lookups.add(Lookup(lookup_type, lookup_input, raw)) return lookups
[ "def", "extract_lookups_from_string", "(", "value", ")", ":", "lookups", "=", "set", "(", ")", "for", "match", "in", "LOOKUP_REGEX", ".", "finditer", "(", "value", ")", ":", "groupdict", "=", "match", ".", "groupdict", "(", ")", "raw", "=", "match", ".",...
Extract any lookups within a string. Args: value (str): string value we're extracting lookups from Returns: list: list of :class:`stacker.lookups.Lookup` if any
[ "Extract", "any", "lookups", "within", "a", "string", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/__init__.py#L29-L46
233,605
cloudtools/stacker
stacker/lookups/__init__.py
extract_lookups
def extract_lookups(value): """Recursively extracts any stack lookups within the data structure. Args: value (one of str, list, dict): a structure that contains lookups to output values Returns: list: list of lookups if any """ lookups = set() if isinstance(value, basestring): lookups = lookups.union(extract_lookups_from_string(value)) elif isinstance(value, list): for v in value: lookups = lookups.union(extract_lookups(v)) elif isinstance(value, dict): for v in value.values(): lookups = lookups.union(extract_lookups(v)) return lookups
python
def extract_lookups(value): lookups = set() if isinstance(value, basestring): lookups = lookups.union(extract_lookups_from_string(value)) elif isinstance(value, list): for v in value: lookups = lookups.union(extract_lookups(v)) elif isinstance(value, dict): for v in value.values(): lookups = lookups.union(extract_lookups(v)) return lookups
[ "def", "extract_lookups", "(", "value", ")", ":", "lookups", "=", "set", "(", ")", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "lookups", "=", "lookups", ".", "union", "(", "extract_lookups_from_string", "(", "value", ")", ")", "elif", ...
Recursively extracts any stack lookups within the data structure. Args: value (one of str, list, dict): a structure that contains lookups to output values Returns: list: list of lookups if any
[ "Recursively", "extracts", "any", "stack", "lookups", "within", "the", "data", "structure", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/__init__.py#L49-L69
233,606
cloudtools/stacker
stacker/dag/__init__.py
DAG.add_node
def add_node(self, node_name): """ Add a node if it does not exist yet, or error out. Args: node_name (str): The unique name of the node to add. Raises: KeyError: Raised if a node with the same name already exist in the graph """ graph = self.graph if node_name in graph: raise KeyError('node %s already exists' % node_name) graph[node_name] = set()
python
def add_node(self, node_name): graph = self.graph if node_name in graph: raise KeyError('node %s already exists' % node_name) graph[node_name] = set()
[ "def", "add_node", "(", "self", ",", "node_name", ")", ":", "graph", "=", "self", ".", "graph", "if", "node_name", "in", "graph", ":", "raise", "KeyError", "(", "'node %s already exists'", "%", "node_name", ")", "graph", "[", "node_name", "]", "=", "set", ...
Add a node if it does not exist yet, or error out. Args: node_name (str): The unique name of the node to add. Raises: KeyError: Raised if a node with the same name already exist in the graph
[ "Add", "a", "node", "if", "it", "does", "not", "exist", "yet", "or", "error", "out", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L32-L45
233,607
cloudtools/stacker
stacker/dag/__init__.py
DAG.transpose
def transpose(self): """ Builds a new graph with the edges reversed. Returns: :class:`stacker.dag.DAG`: The transposed graph. """ graph = self.graph transposed = DAG() for node, edges in graph.items(): transposed.add_node(node) for node, edges in graph.items(): # for each edge A -> B, transpose it so that B -> A for edge in edges: transposed.add_edge(edge, node) return transposed
python
def transpose(self): graph = self.graph transposed = DAG() for node, edges in graph.items(): transposed.add_node(node) for node, edges in graph.items(): # for each edge A -> B, transpose it so that B -> A for edge in edges: transposed.add_edge(edge, node) return transposed
[ "def", "transpose", "(", "self", ")", ":", "graph", "=", "self", ".", "graph", "transposed", "=", "DAG", "(", ")", "for", "node", ",", "edges", "in", "graph", ".", "items", "(", ")", ":", "transposed", ".", "add_node", "(", "node", ")", "for", "nod...
Builds a new graph with the edges reversed. Returns: :class:`stacker.dag.DAG`: The transposed graph.
[ "Builds", "a", "new", "graph", "with", "the", "edges", "reversed", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L136-L150
233,608
cloudtools/stacker
stacker/dag/__init__.py
DAG.walk
def walk(self, walk_func): """ Walks each node of the graph in reverse topological order. This can be used to perform a set of operations, where the next operation depends on the previous operation. It's important to note that walking happens serially, and is not paralellized. Args: walk_func (:class:`types.FunctionType`): The function to be called on each node of the graph. """ nodes = self.topological_sort() # Reverse so we start with nodes that have no dependencies. nodes.reverse() for n in nodes: walk_func(n)
python
def walk(self, walk_func): nodes = self.topological_sort() # Reverse so we start with nodes that have no dependencies. nodes.reverse() for n in nodes: walk_func(n)
[ "def", "walk", "(", "self", ",", "walk_func", ")", ":", "nodes", "=", "self", ".", "topological_sort", "(", ")", "# Reverse so we start with nodes that have no dependencies.", "nodes", ".", "reverse", "(", ")", "for", "n", "in", "nodes", ":", "walk_func", "(", ...
Walks each node of the graph in reverse topological order. This can be used to perform a set of operations, where the next operation depends on the previous operation. It's important to note that walking happens serially, and is not paralellized. Args: walk_func (:class:`types.FunctionType`): The function to be called on each node of the graph.
[ "Walks", "each", "node", "of", "the", "graph", "in", "reverse", "topological", "order", ".", "This", "can", "be", "used", "to", "perform", "a", "set", "of", "operations", "where", "the", "next", "operation", "depends", "on", "the", "previous", "operation", ...
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L152-L167
233,609
cloudtools/stacker
stacker/dag/__init__.py
DAG.transitive_reduction
def transitive_reduction(self): """ Performs a transitive reduction on the DAG. The transitive reduction of a graph is a graph with as few edges as possible with the same reachability as the original graph. See https://en.wikipedia.org/wiki/Transitive_reduction """ combinations = [] for node, edges in self.graph.items(): combinations += [[node, edge] for edge in edges] while True: new_combinations = [] for comb1 in combinations: for comb2 in combinations: if not comb1[-1] == comb2[0]: continue new_entry = comb1 + comb2[1:] if new_entry not in combinations: new_combinations.append(new_entry) if not new_combinations: break combinations += new_combinations constructed = {(c[0], c[-1]) for c in combinations if len(c) != 2} for node, edges in self.graph.items(): bad_nodes = {e for n, e in constructed if node == n} self.graph[node] = edges - bad_nodes
python
def transitive_reduction(self): combinations = [] for node, edges in self.graph.items(): combinations += [[node, edge] for edge in edges] while True: new_combinations = [] for comb1 in combinations: for comb2 in combinations: if not comb1[-1] == comb2[0]: continue new_entry = comb1 + comb2[1:] if new_entry not in combinations: new_combinations.append(new_entry) if not new_combinations: break combinations += new_combinations constructed = {(c[0], c[-1]) for c in combinations if len(c) != 2} for node, edges in self.graph.items(): bad_nodes = {e for n, e in constructed if node == n} self.graph[node] = edges - bad_nodes
[ "def", "transitive_reduction", "(", "self", ")", ":", "combinations", "=", "[", "]", "for", "node", ",", "edges", "in", "self", ".", "graph", ".", "items", "(", ")", ":", "combinations", "+=", "[", "[", "node", ",", "edge", "]", "for", "edge", "in", ...
Performs a transitive reduction on the DAG. The transitive reduction of a graph is a graph with as few edges as possible with the same reachability as the original graph. See https://en.wikipedia.org/wiki/Transitive_reduction
[ "Performs", "a", "transitive", "reduction", "on", "the", "DAG", ".", "The", "transitive", "reduction", "of", "a", "graph", "is", "a", "graph", "with", "as", "few", "edges", "as", "possible", "with", "the", "same", "reachability", "as", "the", "original", "...
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L169-L196
233,610
cloudtools/stacker
stacker/dag/__init__.py
DAG.rename_edges
def rename_edges(self, old_node_name, new_node_name): """ Change references to a node in existing edges. Args: old_node_name (str): The old name for the node. new_node_name (str): The new name for the node. """ graph = self.graph for node, edges in graph.items(): if node == old_node_name: graph[new_node_name] = copy(edges) del graph[old_node_name] else: if old_node_name in edges: edges.remove(old_node_name) edges.add(new_node_name)
python
def rename_edges(self, old_node_name, new_node_name): graph = self.graph for node, edges in graph.items(): if node == old_node_name: graph[new_node_name] = copy(edges) del graph[old_node_name] else: if old_node_name in edges: edges.remove(old_node_name) edges.add(new_node_name)
[ "def", "rename_edges", "(", "self", ",", "old_node_name", ",", "new_node_name", ")", ":", "graph", "=", "self", ".", "graph", "for", "node", ",", "edges", "in", "graph", ".", "items", "(", ")", ":", "if", "node", "==", "old_node_name", ":", "graph", "[...
Change references to a node in existing edges. Args: old_node_name (str): The old name for the node. new_node_name (str): The new name for the node.
[ "Change", "references", "to", "a", "node", "in", "existing", "edges", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L198-L214
233,611
cloudtools/stacker
stacker/dag/__init__.py
DAG.downstream
def downstream(self, node): """ Returns a list of all nodes this node has edges towards. Args: node (str): The node whose downstream nodes you want to find. Returns: list: A list of nodes that are immediately downstream from the node. """ graph = self.graph if node not in graph: raise KeyError('node %s is not in graph' % node) return list(graph[node])
python
def downstream(self, node): graph = self.graph if node not in graph: raise KeyError('node %s is not in graph' % node) return list(graph[node])
[ "def", "downstream", "(", "self", ",", "node", ")", ":", "graph", "=", "self", ".", "graph", "if", "node", "not", "in", "graph", ":", "raise", "KeyError", "(", "'node %s is not in graph'", "%", "node", ")", "return", "list", "(", "graph", "[", "node", ...
Returns a list of all nodes this node has edges towards. Args: node (str): The node whose downstream nodes you want to find. Returns: list: A list of nodes that are immediately downstream from the node.
[ "Returns", "a", "list", "of", "all", "nodes", "this", "node", "has", "edges", "towards", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L228-L241
233,612
cloudtools/stacker
stacker/dag/__init__.py
DAG.filter
def filter(self, nodes): """ Returns a new DAG with only the given nodes and their dependencies. Args: nodes (list): The nodes you are interested in. Returns: :class:`stacker.dag.DAG`: The filtered graph. """ filtered_dag = DAG() # Add only the nodes we need. for node in nodes: filtered_dag.add_node_if_not_exists(node) for edge in self.all_downstreams(node): filtered_dag.add_node_if_not_exists(edge) # Now, rebuild the graph for each node that's present. for node, edges in self.graph.items(): if node in filtered_dag.graph: filtered_dag.graph[node] = edges return filtered_dag
python
def filter(self, nodes): filtered_dag = DAG() # Add only the nodes we need. for node in nodes: filtered_dag.add_node_if_not_exists(node) for edge in self.all_downstreams(node): filtered_dag.add_node_if_not_exists(edge) # Now, rebuild the graph for each node that's present. for node, edges in self.graph.items(): if node in filtered_dag.graph: filtered_dag.graph[node] = edges return filtered_dag
[ "def", "filter", "(", "self", ",", "nodes", ")", ":", "filtered_dag", "=", "DAG", "(", ")", "# Add only the nodes we need.", "for", "node", "in", "nodes", ":", "filtered_dag", ".", "add_node_if_not_exists", "(", "node", ")", "for", "edge", "in", "self", ".",...
Returns a new DAG with only the given nodes and their dependencies. Args: nodes (list): The nodes you are interested in. Returns: :class:`stacker.dag.DAG`: The filtered graph.
[ "Returns", "a", "new", "DAG", "with", "only", "the", "given", "nodes", "and", "their", "dependencies", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L268-L292
233,613
cloudtools/stacker
stacker/dag/__init__.py
DAG.topological_sort
def topological_sort(self): """ Returns a topological ordering of the DAG. Returns: list: A list of topologically sorted nodes in the graph. Raises: ValueError: Raised if the graph is not acyclic. """ graph = self.graph in_degree = {} for u in graph: in_degree[u] = 0 for u in graph: for v in graph[u]: in_degree[v] += 1 queue = deque() for u in in_degree: if in_degree[u] == 0: queue.appendleft(u) sorted_graph = [] while queue: u = queue.pop() sorted_graph.append(u) for v in sorted(graph[u]): in_degree[v] -= 1 if in_degree[v] == 0: queue.appendleft(v) if len(sorted_graph) == len(graph): return sorted_graph else: raise ValueError('graph is not acyclic')
python
def topological_sort(self): graph = self.graph in_degree = {} for u in graph: in_degree[u] = 0 for u in graph: for v in graph[u]: in_degree[v] += 1 queue = deque() for u in in_degree: if in_degree[u] == 0: queue.appendleft(u) sorted_graph = [] while queue: u = queue.pop() sorted_graph.append(u) for v in sorted(graph[u]): in_degree[v] -= 1 if in_degree[v] == 0: queue.appendleft(v) if len(sorted_graph) == len(graph): return sorted_graph else: raise ValueError('graph is not acyclic')
[ "def", "topological_sort", "(", "self", ")", ":", "graph", "=", "self", ".", "graph", "in_degree", "=", "{", "}", "for", "u", "in", "graph", ":", "in_degree", "[", "u", "]", "=", "0", "for", "u", "in", "graph", ":", "for", "v", "in", "graph", "["...
Returns a topological ordering of the DAG. Returns: list: A list of topologically sorted nodes in the graph. Raises: ValueError: Raised if the graph is not acyclic.
[ "Returns", "a", "topological", "ordering", "of", "the", "DAG", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L351-L387
233,614
cloudtools/stacker
stacker/dag/__init__.py
ThreadedWalker.walk
def walk(self, dag, walk_func): """ Walks each node of the graph, in parallel if it can. The walk_func is only called when the nodes dependencies have been satisfied """ # First, we'll topologically sort all of the nodes, with nodes that # have no dependencies first. We do this to ensure that we don't call # .join on a thread that hasn't yet been started. # # TODO(ejholmes): An alternative would be to ensure that Thread.join # blocks if the thread has not yet been started. nodes = dag.topological_sort() nodes.reverse() # This maps a node name to a thread of execution. threads = {} # Blocks until all of the given nodes have completed execution (whether # successfully, or errored). Returns True if all nodes returned True. def wait_for(nodes): for node in nodes: thread = threads[node] while thread.is_alive(): threads[node].join(0.5) # For each node in the graph, we're going to allocate a thread to # execute. The thread will block executing walk_func, until all of the # nodes dependencies have executed. for node in nodes: def fn(n, deps): if deps: logger.debug( "%s waiting for %s to complete", n, ", ".join(deps)) # Wait for all dependencies to complete. wait_for(deps) logger.debug("%s starting", n) self.semaphore.acquire() try: return walk_func(n) finally: self.semaphore.release() deps = dag.all_downstreams(node) threads[node] = Thread(target=fn, args=(node, deps), name=node) # Start up all of the threads. for node in nodes: threads[node].start() # Wait for all threads to complete executing. wait_for(nodes)
python
def walk(self, dag, walk_func): # First, we'll topologically sort all of the nodes, with nodes that # have no dependencies first. We do this to ensure that we don't call # .join on a thread that hasn't yet been started. # # TODO(ejholmes): An alternative would be to ensure that Thread.join # blocks if the thread has not yet been started. nodes = dag.topological_sort() nodes.reverse() # This maps a node name to a thread of execution. threads = {} # Blocks until all of the given nodes have completed execution (whether # successfully, or errored). Returns True if all nodes returned True. def wait_for(nodes): for node in nodes: thread = threads[node] while thread.is_alive(): threads[node].join(0.5) # For each node in the graph, we're going to allocate a thread to # execute. The thread will block executing walk_func, until all of the # nodes dependencies have executed. for node in nodes: def fn(n, deps): if deps: logger.debug( "%s waiting for %s to complete", n, ", ".join(deps)) # Wait for all dependencies to complete. wait_for(deps) logger.debug("%s starting", n) self.semaphore.acquire() try: return walk_func(n) finally: self.semaphore.release() deps = dag.all_downstreams(node) threads[node] = Thread(target=fn, args=(node, deps), name=node) # Start up all of the threads. for node in nodes: threads[node].start() # Wait for all threads to complete executing. wait_for(nodes)
[ "def", "walk", "(", "self", ",", "dag", ",", "walk_func", ")", ":", "# First, we'll topologically sort all of the nodes, with nodes that", "# have no dependencies first. We do this to ensure that we don't call", "# .join on a thread that hasn't yet been started.", "#", "# TODO(ejholmes):...
Walks each node of the graph, in parallel if it can. The walk_func is only called when the nodes dependencies have been satisfied
[ "Walks", "each", "node", "of", "the", "graph", "in", "parallel", "if", "it", "can", ".", "The", "walk_func", "is", "only", "called", "when", "the", "nodes", "dependencies", "have", "been", "satisfied" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L424-L480
233,615
cloudtools/stacker
stacker/tokenize_userdata.py
cf_tokenize
def cf_tokenize(s): """ Parses UserData for Cloudformation helper functions. http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#scenario-userdata-base64 It breaks apart the given string at each recognized function (see HELPERS) and instantiates the helper function objects in place of those. Returns a list of parts as a result. Useful when used with Join() and Base64() CloudFormation functions to produce user data. ie: Base64(Join('', cf_tokenize(userdata_string))) """ t = [] parts = split_re.split(s) for part in parts: cf_func = replace_re.search(part) if cf_func: args = [a.strip("'\" ") for a in cf_func.group("args").split(",")] t.append(HELPERS[cf_func.group("helper")](*args).data) else: t.append(part) return t
python
def cf_tokenize(s): t = [] parts = split_re.split(s) for part in parts: cf_func = replace_re.search(part) if cf_func: args = [a.strip("'\" ") for a in cf_func.group("args").split(",")] t.append(HELPERS[cf_func.group("helper")](*args).data) else: t.append(part) return t
[ "def", "cf_tokenize", "(", "s", ")", ":", "t", "=", "[", "]", "parts", "=", "split_re", ".", "split", "(", "s", ")", "for", "part", "in", "parts", ":", "cf_func", "=", "replace_re", ".", "search", "(", "part", ")", "if", "cf_func", ":", "args", "...
Parses UserData for Cloudformation helper functions. http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#scenario-userdata-base64 It breaks apart the given string at each recognized function (see HELPERS) and instantiates the helper function objects in place of those. Returns a list of parts as a result. Useful when used with Join() and Base64() CloudFormation functions to produce user data. ie: Base64(Join('', cf_tokenize(userdata_string)))
[ "Parses", "UserData", "for", "Cloudformation", "helper", "functions", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/tokenize_userdata.py#L22-L46
233,616
cloudtools/stacker
stacker/lookups/handlers/split.py
SplitLookup.handle
def handle(cls, value, **kwargs): """Split the supplied string on the given delimiter, providing a list. Format of value: <delimiter>::<value> For example: Subnets: ${split ,::subnet-1,subnet-2,subnet-3} Would result in the variable `Subnets` getting a list consisting of: ["subnet-1", "subnet-2", "subnet-3"] This is particularly useful when getting an output from another stack that contains a list. For example, the standard vpc blueprint outputs the list of Subnets it creates as a pair of Outputs (PublicSubnets, PrivateSubnets) that are comma separated, so you could use this in your config: Subnets: ${split ,::${output vpc::PrivateSubnets}} """ try: delimiter, text = value.split("::", 1) except ValueError: raise ValueError("Invalid value for split: %s. Must be in " "<delimiter>::<text> format." % value) return text.split(delimiter)
python
def handle(cls, value, **kwargs): try: delimiter, text = value.split("::", 1) except ValueError: raise ValueError("Invalid value for split: %s. Must be in " "<delimiter>::<text> format." % value) return text.split(delimiter)
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "try", ":", "delimiter", ",", "text", "=", "value", ".", "split", "(", "\"::\"", ",", "1", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Invalid value for ...
Split the supplied string on the given delimiter, providing a list. Format of value: <delimiter>::<value> For example: Subnets: ${split ,::subnet-1,subnet-2,subnet-3} Would result in the variable `Subnets` getting a list consisting of: ["subnet-1", "subnet-2", "subnet-3"] This is particularly useful when getting an output from another stack that contains a list. For example, the standard vpc blueprint outputs the list of Subnets it creates as a pair of Outputs (PublicSubnets, PrivateSubnets) that are comma separated, so you could use this in your config: Subnets: ${split ,::${output vpc::PrivateSubnets}}
[ "Split", "the", "supplied", "string", "on", "the", "given", "delimiter", "providing", "a", "list", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/split.py#L10-L40
233,617
cloudtools/stacker
stacker/actions/build.py
should_update
def should_update(stack): """Tests whether a stack should be submitted for updates to CF. Args: stack (:class:`stacker.stack.Stack`): The stack object to check. Returns: bool: If the stack should be updated, return True. """ if stack.locked: if not stack.force: logger.debug("Stack %s locked and not in --force list. " "Refusing to update.", stack.name) return False else: logger.debug("Stack %s locked, but is in --force " "list.", stack.name) return True
python
def should_update(stack): if stack.locked: if not stack.force: logger.debug("Stack %s locked and not in --force list. " "Refusing to update.", stack.name) return False else: logger.debug("Stack %s locked, but is in --force " "list.", stack.name) return True
[ "def", "should_update", "(", "stack", ")", ":", "if", "stack", ".", "locked", ":", "if", "not", "stack", ".", "force", ":", "logger", ".", "debug", "(", "\"Stack %s locked and not in --force list. \"", "\"Refusing to update.\"", ",", "stack", ".", "name", ")", ...
Tests whether a stack should be submitted for updates to CF. Args: stack (:class:`stacker.stack.Stack`): The stack object to check. Returns: bool: If the stack should be updated, return True.
[ "Tests", "whether", "a", "stack", "should", "be", "submitted", "for", "updates", "to", "CF", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L41-L59
233,618
cloudtools/stacker
stacker/actions/build.py
_resolve_parameters
def _resolve_parameters(parameters, blueprint): """Resolves CloudFormation Parameters for a given blueprint. Given a list of parameters, handles: - discard any parameters that the blueprint does not use - discard any empty values - convert booleans to strings suitable for CloudFormation Args: parameters (dict): A dictionary of parameters provided by the stack definition blueprint (:class:`stacker.blueprint.base.Blueprint`): A Blueprint object that is having the parameters applied to it. Returns: dict: The resolved parameters. """ params = {} param_defs = blueprint.get_parameter_definitions() for key, value in parameters.items(): if key not in param_defs: logger.debug("Blueprint %s does not use parameter %s.", blueprint.name, key) continue if value is None: logger.debug("Got None value for parameter %s, not submitting it " "to cloudformation, default value should be used.", key) continue if isinstance(value, bool): logger.debug("Converting parameter %s boolean \"%s\" to string.", key, value) value = str(value).lower() params[key] = value return params
python
def _resolve_parameters(parameters, blueprint): params = {} param_defs = blueprint.get_parameter_definitions() for key, value in parameters.items(): if key not in param_defs: logger.debug("Blueprint %s does not use parameter %s.", blueprint.name, key) continue if value is None: logger.debug("Got None value for parameter %s, not submitting it " "to cloudformation, default value should be used.", key) continue if isinstance(value, bool): logger.debug("Converting parameter %s boolean \"%s\" to string.", key, value) value = str(value).lower() params[key] = value return params
[ "def", "_resolve_parameters", "(", "parameters", ",", "blueprint", ")", ":", "params", "=", "{", "}", "param_defs", "=", "blueprint", ".", "get_parameter_definitions", "(", ")", "for", "key", ",", "value", "in", "parameters", ".", "items", "(", ")", ":", "...
Resolves CloudFormation Parameters for a given blueprint. Given a list of parameters, handles: - discard any parameters that the blueprint does not use - discard any empty values - convert booleans to strings suitable for CloudFormation Args: parameters (dict): A dictionary of parameters provided by the stack definition blueprint (:class:`stacker.blueprint.base.Blueprint`): A Blueprint object that is having the parameters applied to it. Returns: dict: The resolved parameters.
[ "Resolves", "CloudFormation", "Parameters", "for", "a", "given", "blueprint", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L93-L129
233,619
cloudtools/stacker
stacker/actions/build.py
_handle_missing_parameters
def _handle_missing_parameters(parameter_values, all_params, required_params, existing_stack=None): """Handles any missing parameters. If an existing_stack is provided, look up missing parameters there. Args: parameter_values (dict): key/value dictionary of stack definition parameters all_params (list): A list of all the parameters used by the template/blueprint. required_params (list): A list of all the parameters required by the template/blueprint. existing_stack (dict): A dict representation of the stack. If provided, will be searched for any missing parameters. Returns: list of tuples: The final list of key/value pairs returned as a list of tuples. Raises: MissingParameterException: Raised if a required parameter is still missing. """ missing_params = list(set(all_params) - set(parameter_values.keys())) if existing_stack and 'Parameters' in existing_stack: stack_parameters = [ p["ParameterKey"] for p in existing_stack["Parameters"] ] for p in missing_params: if p in stack_parameters: logger.debug( "Using previous value for parameter %s from existing " "stack", p ) parameter_values[p] = UsePreviousParameterValue final_missing = list(set(required_params) - set(parameter_values.keys())) if final_missing: raise MissingParameterException(final_missing) return list(parameter_values.items())
python
def _handle_missing_parameters(parameter_values, all_params, required_params, existing_stack=None): missing_params = list(set(all_params) - set(parameter_values.keys())) if existing_stack and 'Parameters' in existing_stack: stack_parameters = [ p["ParameterKey"] for p in existing_stack["Parameters"] ] for p in missing_params: if p in stack_parameters: logger.debug( "Using previous value for parameter %s from existing " "stack", p ) parameter_values[p] = UsePreviousParameterValue final_missing = list(set(required_params) - set(parameter_values.keys())) if final_missing: raise MissingParameterException(final_missing) return list(parameter_values.items())
[ "def", "_handle_missing_parameters", "(", "parameter_values", ",", "all_params", ",", "required_params", ",", "existing_stack", "=", "None", ")", ":", "missing_params", "=", "list", "(", "set", "(", "all_params", ")", "-", "set", "(", "parameter_values", ".", "k...
Handles any missing parameters. If an existing_stack is provided, look up missing parameters there. Args: parameter_values (dict): key/value dictionary of stack definition parameters all_params (list): A list of all the parameters used by the template/blueprint. required_params (list): A list of all the parameters required by the template/blueprint. existing_stack (dict): A dict representation of the stack. If provided, will be searched for any missing parameters. Returns: list of tuples: The final list of key/value pairs returned as a list of tuples. Raises: MissingParameterException: Raised if a required parameter is still missing.
[ "Handles", "any", "missing", "parameters", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L139-L181
233,620
cloudtools/stacker
stacker/actions/build.py
Action.build_parameters
def build_parameters(self, stack, provider_stack=None): """Builds the CloudFormation Parameters for our stack. Args: stack (:class:`stacker.stack.Stack`): A stacker stack provider_stack (dict): An optional Stacker provider object Returns: dict: The parameters for the given stack """ resolved = _resolve_parameters(stack.parameter_values, stack.blueprint) required_parameters = list(stack.required_parameter_definitions) all_parameters = list(stack.all_parameter_definitions) parameters = _handle_missing_parameters(resolved, all_parameters, required_parameters, provider_stack) param_list = [] for key, value in parameters: param_dict = {"ParameterKey": key} if value is UsePreviousParameterValue: param_dict["UsePreviousValue"] = True else: param_dict["ParameterValue"] = str(value) param_list.append(param_dict) return param_list
python
def build_parameters(self, stack, provider_stack=None): resolved = _resolve_parameters(stack.parameter_values, stack.blueprint) required_parameters = list(stack.required_parameter_definitions) all_parameters = list(stack.all_parameter_definitions) parameters = _handle_missing_parameters(resolved, all_parameters, required_parameters, provider_stack) param_list = [] for key, value in parameters: param_dict = {"ParameterKey": key} if value is UsePreviousParameterValue: param_dict["UsePreviousValue"] = True else: param_dict["ParameterValue"] = str(value) param_list.append(param_dict) return param_list
[ "def", "build_parameters", "(", "self", ",", "stack", ",", "provider_stack", "=", "None", ")", ":", "resolved", "=", "_resolve_parameters", "(", "stack", ".", "parameter_values", ",", "stack", ".", "blueprint", ")", "required_parameters", "=", "list", "(", "st...
Builds the CloudFormation Parameters for our stack. Args: stack (:class:`stacker.stack.Stack`): A stacker stack provider_stack (dict): An optional Stacker provider object Returns: dict: The parameters for the given stack
[ "Builds", "the", "CloudFormation", "Parameters", "for", "our", "stack", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L222-L251
233,621
cloudtools/stacker
stacker/actions/build.py
Action._template
def _template(self, blueprint): """Generates a suitable template based on whether or not an S3 bucket is set. If an S3 bucket is set, then the template will be uploaded to S3 first, and CreateStack/UpdateStack operations will use the uploaded template. If not bucket is set, then the template will be inlined. """ if self.bucket_name: return Template(url=self.s3_stack_push(blueprint)) else: return Template(body=blueprint.rendered)
python
def _template(self, blueprint): if self.bucket_name: return Template(url=self.s3_stack_push(blueprint)) else: return Template(body=blueprint.rendered)
[ "def", "_template", "(", "self", ",", "blueprint", ")", ":", "if", "self", ".", "bucket_name", ":", "return", "Template", "(", "url", "=", "self", ".", "s3_stack_push", "(", "blueprint", ")", ")", "else", ":", "return", "Template", "(", "body", "=", "b...
Generates a suitable template based on whether or not an S3 bucket is set. If an S3 bucket is set, then the template will be uploaded to S3 first, and CreateStack/UpdateStack operations will use the uploaded template. If not bucket is set, then the template will be inlined.
[ "Generates", "a", "suitable", "template", "based", "on", "whether", "or", "not", "an", "S3", "bucket", "is", "set", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/build.py#L375-L386
233,622
cloudtools/stacker
stacker/hooks/route53.py
create_domain
def create_domain(provider, context, **kwargs): """Create a domain within route53. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Returns: boolean for whether or not the hook succeeded. """ session = get_session(provider.region) client = session.client("route53") domain = kwargs.get("domain") if not domain: logger.error("domain argument or BaseDomain variable not provided.") return False zone_id = create_route53_zone(client, domain) return {"domain": domain, "zone_id": zone_id}
python
def create_domain(provider, context, **kwargs): session = get_session(provider.region) client = session.client("route53") domain = kwargs.get("domain") if not domain: logger.error("domain argument or BaseDomain variable not provided.") return False zone_id = create_route53_zone(client, domain) return {"domain": domain, "zone_id": zone_id}
[ "def", "create_domain", "(", "provider", ",", "context", ",", "*", "*", "kwargs", ")", ":", "session", "=", "get_session", "(", "provider", ".", "region", ")", "client", "=", "session", ".", "client", "(", "\"route53\"", ")", "domain", "=", "kwargs", "."...
Create a domain within route53. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Returns: boolean for whether or not the hook succeeded.
[ "Create", "a", "domain", "within", "route53", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/route53.py#L13-L31
233,623
cloudtools/stacker
stacker/ui.py
UI.info
def info(self, *args, **kwargs): """Logs the line of the current thread owns the underlying lock, or blocks.""" self.lock() try: return logger.info(*args, **kwargs) finally: self.unlock()
python
def info(self, *args, **kwargs): self.lock() try: return logger.info(*args, **kwargs) finally: self.unlock()
[ "def", "info", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "lock", "(", ")", "try", ":", "return", "logger", ".", "info", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "self", ".", "unlock", ...
Logs the line of the current thread owns the underlying lock, or blocks.
[ "Logs", "the", "line", "of", "the", "current", "thread", "owns", "the", "underlying", "lock", "or", "blocks", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/ui.py#L37-L44
233,624
cloudtools/stacker
stacker/util.py
camel_to_snake
def camel_to_snake(name): """Converts CamelCase to snake_case. Args: name (string): The name to convert from CamelCase to snake_case. Returns: string: Converted string. """ s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
python
def camel_to_snake(name): s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
[ "def", "camel_to_snake", "(", "name", ")", ":", "s1", "=", "re", ".", "sub", "(", "\"(.)([A-Z][a-z]+)\"", ",", "r\"\\1_\\2\"", ",", "name", ")", "return", "re", ".", "sub", "(", "\"([a-z0-9])([A-Z])\"", ",", "r\"\\1_\\2\"", ",", "s1", ")", ".", "lower", ...
Converts CamelCase to snake_case. Args: name (string): The name to convert from CamelCase to snake_case. Returns: string: Converted string.
[ "Converts", "CamelCase", "to", "snake_case", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L34-L44
233,625
cloudtools/stacker
stacker/util.py
get_hosted_zone_by_name
def get_hosted_zone_by_name(client, zone_name): """Get the zone id of an existing zone by name. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: string: The Id of the Hosted Zone. """ p = client.get_paginator("list_hosted_zones") for i in p.paginate(): for zone in i["HostedZones"]: if zone["Name"] == zone_name: return parse_zone_id(zone["Id"]) return None
python
def get_hosted_zone_by_name(client, zone_name): p = client.get_paginator("list_hosted_zones") for i in p.paginate(): for zone in i["HostedZones"]: if zone["Name"] == zone_name: return parse_zone_id(zone["Id"]) return None
[ "def", "get_hosted_zone_by_name", "(", "client", ",", "zone_name", ")", ":", "p", "=", "client", ".", "get_paginator", "(", "\"list_hosted_zones\"", ")", "for", "i", "in", "p", ".", "paginate", "(", ")", ":", "for", "zone", "in", "i", "[", "\"HostedZones\"...
Get the zone id of an existing zone by name. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: string: The Id of the Hosted Zone.
[ "Get", "the", "zone", "id", "of", "an", "existing", "zone", "by", "name", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L64-L81
233,626
cloudtools/stacker
stacker/util.py
get_or_create_hosted_zone
def get_or_create_hosted_zone(client, zone_name): """Get the Id of an existing zone, or create it. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: string: The Id of the Hosted Zone. """ zone_id = get_hosted_zone_by_name(client, zone_name) if zone_id: return zone_id logger.debug("Zone %s does not exist, creating.", zone_name) reference = uuid.uuid4().hex response = client.create_hosted_zone(Name=zone_name, CallerReference=reference) return parse_zone_id(response["HostedZone"]["Id"])
python
def get_or_create_hosted_zone(client, zone_name): zone_id = get_hosted_zone_by_name(client, zone_name) if zone_id: return zone_id logger.debug("Zone %s does not exist, creating.", zone_name) reference = uuid.uuid4().hex response = client.create_hosted_zone(Name=zone_name, CallerReference=reference) return parse_zone_id(response["HostedZone"]["Id"])
[ "def", "get_or_create_hosted_zone", "(", "client", ",", "zone_name", ")", ":", "zone_id", "=", "get_hosted_zone_by_name", "(", "client", ",", "zone_name", ")", "if", "zone_id", ":", "return", "zone_id", "logger", ".", "debug", "(", "\"Zone %s does not exist, creatin...
Get the Id of an existing zone, or create it. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: string: The Id of the Hosted Zone.
[ "Get", "the", "Id", "of", "an", "existing", "zone", "or", "create", "it", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L84-L106
233,627
cloudtools/stacker
stacker/util.py
get_soa_record
def get_soa_record(client, zone_id, zone_name): """Gets the SOA record for zone_name from zone_id. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_id (string): The AWS Route53 zone id of the hosted zone to query. zone_name (string): The name of the DNS hosted zone to create. Returns: :class:`stacker.util.SOARecord`: An object representing the parsed SOA record returned from AWS Route53. """ response = client.list_resource_record_sets(HostedZoneId=zone_id, StartRecordName=zone_name, StartRecordType="SOA", MaxItems="1") return SOARecord(response["ResourceRecordSets"][0])
python
def get_soa_record(client, zone_id, zone_name): response = client.list_resource_record_sets(HostedZoneId=zone_id, StartRecordName=zone_name, StartRecordType="SOA", MaxItems="1") return SOARecord(response["ResourceRecordSets"][0])
[ "def", "get_soa_record", "(", "client", ",", "zone_id", ",", "zone_name", ")", ":", "response", "=", "client", ".", "list_resource_record_sets", "(", "HostedZoneId", "=", "zone_id", ",", "StartRecordName", "=", "zone_name", ",", "StartRecordType", "=", "\"SOA\"", ...
Gets the SOA record for zone_name from zone_id. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_id (string): The AWS Route53 zone id of the hosted zone to query. zone_name (string): The name of the DNS hosted zone to create. Returns: :class:`stacker.util.SOARecord`: An object representing the parsed SOA record returned from AWS Route53.
[ "Gets", "the", "SOA", "record", "for", "zone_name", "from", "zone_id", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L130-L148
233,628
cloudtools/stacker
stacker/util.py
create_route53_zone
def create_route53_zone(client, zone_name): """Creates the given zone_name if it doesn't already exists. Also sets the SOA negative caching TTL to something short (300 seconds). Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: string: The zone id returned from AWS for the existing, or newly created zone. """ if not zone_name.endswith("."): zone_name += "." zone_id = get_or_create_hosted_zone(client, zone_name) old_soa = get_soa_record(client, zone_id, zone_name) # If the negative cache value is already 300, don't update it. if old_soa.text.min_ttl == "300": return zone_id new_soa = copy.deepcopy(old_soa) logger.debug("Updating negative caching value on zone %s to 300.", zone_name) new_soa.text.min_ttl = "300" client.change_resource_record_sets( HostedZoneId=zone_id, ChangeBatch={ "Comment": "Update SOA min_ttl to 300.", "Changes": [ { "Action": "UPSERT", "ResourceRecordSet": { "Name": zone_name, "Type": "SOA", "TTL": old_soa.ttl, "ResourceRecords": [ { "Value": str(new_soa.text) } ] } }, ] } ) return zone_id
python
def create_route53_zone(client, zone_name): if not zone_name.endswith("."): zone_name += "." zone_id = get_or_create_hosted_zone(client, zone_name) old_soa = get_soa_record(client, zone_id, zone_name) # If the negative cache value is already 300, don't update it. if old_soa.text.min_ttl == "300": return zone_id new_soa = copy.deepcopy(old_soa) logger.debug("Updating negative caching value on zone %s to 300.", zone_name) new_soa.text.min_ttl = "300" client.change_resource_record_sets( HostedZoneId=zone_id, ChangeBatch={ "Comment": "Update SOA min_ttl to 300.", "Changes": [ { "Action": "UPSERT", "ResourceRecordSet": { "Name": zone_name, "Type": "SOA", "TTL": old_soa.ttl, "ResourceRecords": [ { "Value": str(new_soa.text) } ] } }, ] } ) return zone_id
[ "def", "create_route53_zone", "(", "client", ",", "zone_name", ")", ":", "if", "not", "zone_name", ".", "endswith", "(", "\".\"", ")", ":", "zone_name", "+=", "\".\"", "zone_id", "=", "get_or_create_hosted_zone", "(", "client", ",", "zone_name", ")", "old_soa"...
Creates the given zone_name if it doesn't already exists. Also sets the SOA negative caching TTL to something short (300 seconds). Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: string: The zone id returned from AWS for the existing, or newly created zone.
[ "Creates", "the", "given", "zone_name", "if", "it", "doesn", "t", "already", "exists", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L151-L199
233,629
cloudtools/stacker
stacker/util.py
load_object_from_string
def load_object_from_string(fqcn): """Converts "." delimited strings to a python object. Given a "." delimited string representing the full path to an object (function, class, variable) inside a module, return that object. Example: load_object_from_string("os.path.basename") load_object_from_string("logging.Logger") load_object_from_string("LocalClassName") """ module_path = "__main__" object_name = fqcn if "." in fqcn: module_path, object_name = fqcn.rsplit(".", 1) importlib.import_module(module_path) return getattr(sys.modules[module_path], object_name)
python
def load_object_from_string(fqcn): module_path = "__main__" object_name = fqcn if "." in fqcn: module_path, object_name = fqcn.rsplit(".", 1) importlib.import_module(module_path) return getattr(sys.modules[module_path], object_name)
[ "def", "load_object_from_string", "(", "fqcn", ")", ":", "module_path", "=", "\"__main__\"", "object_name", "=", "fqcn", "if", "\".\"", "in", "fqcn", ":", "module_path", ",", "object_name", "=", "fqcn", ".", "rsplit", "(", "\".\"", ",", "1", ")", "importlib"...
Converts "." delimited strings to a python object. Given a "." delimited string representing the full path to an object (function, class, variable) inside a module, return that object. Example: load_object_from_string("os.path.basename") load_object_from_string("logging.Logger") load_object_from_string("LocalClassName")
[ "Converts", ".", "delimited", "strings", "to", "a", "python", "object", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L202-L217
233,630
cloudtools/stacker
stacker/util.py
merge_map
def merge_map(a, b): """Recursively merge elements of argument b into argument a. Primarly used for merging two dictionaries together, where dict b takes precedence over dict a. If 2 lists are provided, they are concatenated. """ if isinstance(a, list) and isinstance(b, list): return a + b if not isinstance(a, dict) or not isinstance(b, dict): return b for key in b: a[key] = merge_map(a[key], b[key]) if key in a else b[key] return a
python
def merge_map(a, b): if isinstance(a, list) and isinstance(b, list): return a + b if not isinstance(a, dict) or not isinstance(b, dict): return b for key in b: a[key] = merge_map(a[key], b[key]) if key in a else b[key] return a
[ "def", "merge_map", "(", "a", ",", "b", ")", ":", "if", "isinstance", "(", "a", ",", "list", ")", "and", "isinstance", "(", "b", ",", "list", ")", ":", "return", "a", "+", "b", "if", "not", "isinstance", "(", "a", ",", "dict", ")", "or", "not",...
Recursively merge elements of argument b into argument a. Primarly used for merging two dictionaries together, where dict b takes precedence over dict a. If 2 lists are provided, they are concatenated.
[ "Recursively", "merge", "elements", "of", "argument", "b", "into", "argument", "a", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L220-L234
233,631
cloudtools/stacker
stacker/util.py
yaml_to_ordered_dict
def yaml_to_ordered_dict(stream, loader=yaml.SafeLoader): """Provides yaml.load alternative with preserved dictionary order. Args: stream (string): YAML string to load. loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe load. Returns: OrderedDict: Parsed YAML. """ class OrderedUniqueLoader(loader): """ Subclasses the given pyYAML `loader` class. Validates all sibling keys to insure no duplicates. Returns an OrderedDict instead of a Dict. """ # keys which require no duplicate siblings. NO_DUPE_SIBLINGS = ["stacks", "class_path"] # keys which require no duplicate children keys. NO_DUPE_CHILDREN = ["stacks"] def _error_mapping_on_dupe(self, node, node_name): """check mapping node for dupe children keys.""" if isinstance(node, MappingNode): mapping = {} for n in node.value: a = n[0] b = mapping.get(a.value, None) if b: msg = "{} mapping cannot have duplicate keys {} {}" raise ConstructorError( msg.format(node_name, b.start_mark, a.start_mark) ) mapping[a.value] = a def _validate_mapping(self, node, deep=False): if not isinstance(node, MappingNode): raise ConstructorError( None, None, "expected a mapping node, but found %s" % node.id, node.start_mark) mapping = OrderedDict() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: raise ConstructorError( "while constructing a mapping", node.start_mark, "found unhashable key (%s)" % exc, key_node.start_mark ) # prevent duplicate sibling keys for certain "keywords". if key in mapping and key in self.NO_DUPE_SIBLINGS: msg = "{} key cannot have duplicate siblings {} {}" raise ConstructorError( msg.format(key, node.start_mark, key_node.start_mark) ) if key in self.NO_DUPE_CHILDREN: # prevent duplicate children keys for this mapping. self._error_mapping_on_dupe(value_node, key_node.value) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping def construct_mapping(self, node, deep=False): """Override parent method to use OrderedDict.""" if isinstance(node, MappingNode): self.flatten_mapping(node) return self._validate_mapping(node, deep=deep) def construct_yaml_map(self, node): data = OrderedDict() yield data value = self.construct_mapping(node) data.update(value) OrderedUniqueLoader.add_constructor( u'tag:yaml.org,2002:map', OrderedUniqueLoader.construct_yaml_map, ) return yaml.load(stream, OrderedUniqueLoader)
python
def yaml_to_ordered_dict(stream, loader=yaml.SafeLoader): class OrderedUniqueLoader(loader): """ Subclasses the given pyYAML `loader` class. Validates all sibling keys to insure no duplicates. Returns an OrderedDict instead of a Dict. """ # keys which require no duplicate siblings. NO_DUPE_SIBLINGS = ["stacks", "class_path"] # keys which require no duplicate children keys. NO_DUPE_CHILDREN = ["stacks"] def _error_mapping_on_dupe(self, node, node_name): """check mapping node for dupe children keys.""" if isinstance(node, MappingNode): mapping = {} for n in node.value: a = n[0] b = mapping.get(a.value, None) if b: msg = "{} mapping cannot have duplicate keys {} {}" raise ConstructorError( msg.format(node_name, b.start_mark, a.start_mark) ) mapping[a.value] = a def _validate_mapping(self, node, deep=False): if not isinstance(node, MappingNode): raise ConstructorError( None, None, "expected a mapping node, but found %s" % node.id, node.start_mark) mapping = OrderedDict() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: raise ConstructorError( "while constructing a mapping", node.start_mark, "found unhashable key (%s)" % exc, key_node.start_mark ) # prevent duplicate sibling keys for certain "keywords". if key in mapping and key in self.NO_DUPE_SIBLINGS: msg = "{} key cannot have duplicate siblings {} {}" raise ConstructorError( msg.format(key, node.start_mark, key_node.start_mark) ) if key in self.NO_DUPE_CHILDREN: # prevent duplicate children keys for this mapping. self._error_mapping_on_dupe(value_node, key_node.value) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping def construct_mapping(self, node, deep=False): """Override parent method to use OrderedDict.""" if isinstance(node, MappingNode): self.flatten_mapping(node) return self._validate_mapping(node, deep=deep) def construct_yaml_map(self, node): data = OrderedDict() yield data value = self.construct_mapping(node) data.update(value) OrderedUniqueLoader.add_constructor( u'tag:yaml.org,2002:map', OrderedUniqueLoader.construct_yaml_map, ) return yaml.load(stream, OrderedUniqueLoader)
[ "def", "yaml_to_ordered_dict", "(", "stream", ",", "loader", "=", "yaml", ".", "SafeLoader", ")", ":", "class", "OrderedUniqueLoader", "(", "loader", ")", ":", "\"\"\"\n Subclasses the given pyYAML `loader` class.\n\n Validates all sibling keys to insure no duplicat...
Provides yaml.load alternative with preserved dictionary order. Args: stream (string): YAML string to load. loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe load. Returns: OrderedDict: Parsed YAML.
[ "Provides", "yaml", ".", "load", "alternative", "with", "preserved", "dictionary", "order", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L237-L320
233,632
cloudtools/stacker
stacker/util.py
cf_safe_name
def cf_safe_name(name): """Converts a name to a safe string for a Cloudformation resource. Given a string, returns a name that is safe for use as a CloudFormation Resource. (ie: Only alphanumeric characters) """ alphanumeric = r"[a-zA-Z0-9]+" parts = re.findall(alphanumeric, name) return "".join([uppercase_first_letter(part) for part in parts])
python
def cf_safe_name(name): alphanumeric = r"[a-zA-Z0-9]+" parts = re.findall(alphanumeric, name) return "".join([uppercase_first_letter(part) for part in parts])
[ "def", "cf_safe_name", "(", "name", ")", ":", "alphanumeric", "=", "r\"[a-zA-Z0-9]+\"", "parts", "=", "re", ".", "findall", "(", "alphanumeric", ",", "name", ")", "return", "\"\"", ".", "join", "(", "[", "uppercase_first_letter", "(", "part", ")", "for", "...
Converts a name to a safe string for a Cloudformation resource. Given a string, returns a name that is safe for use as a CloudFormation Resource. (ie: Only alphanumeric characters)
[ "Converts", "a", "name", "to", "a", "safe", "string", "for", "a", "Cloudformation", "resource", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L328-L336
233,633
cloudtools/stacker
stacker/util.py
get_config_directory
def get_config_directory(): """Return the directory the config file is located in. This enables us to use relative paths in config values. """ # avoid circular import from .commands.stacker import Stacker command = Stacker() namespace = command.parse_args() return os.path.dirname(namespace.config.name)
python
def get_config_directory(): # avoid circular import from .commands.stacker import Stacker command = Stacker() namespace = command.parse_args() return os.path.dirname(namespace.config.name)
[ "def", "get_config_directory", "(", ")", ":", "# avoid circular import", "from", ".", "commands", ".", "stacker", "import", "Stacker", "command", "=", "Stacker", "(", ")", "namespace", "=", "command", ".", "parse_args", "(", ")", "return", "os", ".", "path", ...
Return the directory the config file is located in. This enables us to use relative paths in config values.
[ "Return", "the", "directory", "the", "config", "file", "is", "located", "in", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L339-L349
233,634
cloudtools/stacker
stacker/util.py
read_value_from_path
def read_value_from_path(value): """Enables translators to read values from files. The value can be referred to with the `file://` prefix. ie: conf_key: ${kms file://kms_value.txt} """ if value.startswith('file://'): path = value.split('file://', 1)[1] config_directory = get_config_directory() relative_path = os.path.join(config_directory, path) with open(relative_path) as read_file: value = read_file.read() return value
python
def read_value_from_path(value): if value.startswith('file://'): path = value.split('file://', 1)[1] config_directory = get_config_directory() relative_path = os.path.join(config_directory, path) with open(relative_path) as read_file: value = read_file.read() return value
[ "def", "read_value_from_path", "(", "value", ")", ":", "if", "value", ".", "startswith", "(", "'file://'", ")", ":", "path", "=", "value", ".", "split", "(", "'file://'", ",", "1", ")", "[", "1", "]", "config_directory", "=", "get_config_directory", "(", ...
Enables translators to read values from files. The value can be referred to with the `file://` prefix. ie: conf_key: ${kms file://kms_value.txt}
[ "Enables", "translators", "to", "read", "values", "from", "files", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L352-L366
233,635
cloudtools/stacker
stacker/util.py
ensure_s3_bucket
def ensure_s3_bucket(s3_client, bucket_name, bucket_region): """Ensure an s3 bucket exists, if it does not then create it. Args: s3_client (:class:`botocore.client.Client`): An s3 client used to verify and create the bucket. bucket_name (str): The bucket being checked/created. bucket_region (str, optional): The region to create the bucket in. If not provided, will be determined by s3_client's region. """ try: s3_client.head_bucket(Bucket=bucket_name) except botocore.exceptions.ClientError as e: if e.response['Error']['Message'] == "Not Found": logger.debug("Creating bucket %s.", bucket_name) create_args = {"Bucket": bucket_name} location_constraint = s3_bucket_location_constraint( bucket_region ) if location_constraint: create_args["CreateBucketConfiguration"] = { "LocationConstraint": location_constraint } s3_client.create_bucket(**create_args) elif e.response['Error']['Message'] == "Forbidden": logger.exception("Access denied for bucket %s. Did " + "you remember to use a globally unique name?", bucket_name) raise else: logger.exception("Error creating bucket %s. Error %s", bucket_name, e.response) raise
python
def ensure_s3_bucket(s3_client, bucket_name, bucket_region): try: s3_client.head_bucket(Bucket=bucket_name) except botocore.exceptions.ClientError as e: if e.response['Error']['Message'] == "Not Found": logger.debug("Creating bucket %s.", bucket_name) create_args = {"Bucket": bucket_name} location_constraint = s3_bucket_location_constraint( bucket_region ) if location_constraint: create_args["CreateBucketConfiguration"] = { "LocationConstraint": location_constraint } s3_client.create_bucket(**create_args) elif e.response['Error']['Message'] == "Forbidden": logger.exception("Access denied for bucket %s. Did " + "you remember to use a globally unique name?", bucket_name) raise else: logger.exception("Error creating bucket %s. Error %s", bucket_name, e.response) raise
[ "def", "ensure_s3_bucket", "(", "s3_client", ",", "bucket_name", ",", "bucket_region", ")", ":", "try", ":", "s3_client", ".", "head_bucket", "(", "Bucket", "=", "bucket_name", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "e", ":", ...
Ensure an s3 bucket exists, if it does not then create it. Args: s3_client (:class:`botocore.client.Client`): An s3 client used to verify and create the bucket. bucket_name (str): The bucket being checked/created. bucket_region (str, optional): The region to create the bucket in. If not provided, will be determined by s3_client's region.
[ "Ensure", "an", "s3", "bucket", "exists", "if", "it", "does", "not", "then", "create", "it", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L415-L447
233,636
cloudtools/stacker
stacker/util.py
SourceProcessor.create_cache_directories
def create_cache_directories(self): """Ensure that SourceProcessor cache directories exist.""" if not os.path.isdir(self.package_cache_dir): if not os.path.isdir(self.stacker_cache_dir): os.mkdir(self.stacker_cache_dir) os.mkdir(self.package_cache_dir)
python
def create_cache_directories(self): if not os.path.isdir(self.package_cache_dir): if not os.path.isdir(self.stacker_cache_dir): os.mkdir(self.stacker_cache_dir) os.mkdir(self.package_cache_dir)
[ "def", "create_cache_directories", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "package_cache_dir", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "stacker_cache_dir", ")", ":", "os"...
Ensure that SourceProcessor cache directories exist.
[ "Ensure", "that", "SourceProcessor", "cache", "directories", "exist", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L553-L558
233,637
cloudtools/stacker
stacker/util.py
SourceProcessor.get_package_sources
def get_package_sources(self): """Make remote python packages available for local use.""" # Checkout local modules for config in self.sources.get('local', []): self.fetch_local_package(config=config) # Checkout S3 repositories specified in config for config in self.sources.get('s3', []): self.fetch_s3_package(config=config) # Checkout git repositories specified in config for config in self.sources.get('git', []): self.fetch_git_package(config=config)
python
def get_package_sources(self): # Checkout local modules for config in self.sources.get('local', []): self.fetch_local_package(config=config) # Checkout S3 repositories specified in config for config in self.sources.get('s3', []): self.fetch_s3_package(config=config) # Checkout git repositories specified in config for config in self.sources.get('git', []): self.fetch_git_package(config=config)
[ "def", "get_package_sources", "(", "self", ")", ":", "# Checkout local modules", "for", "config", "in", "self", ".", "sources", ".", "get", "(", "'local'", ",", "[", "]", ")", ":", "self", ".", "fetch_local_package", "(", "config", "=", "config", ")", "# C...
Make remote python packages available for local use.
[ "Make", "remote", "python", "packages", "available", "for", "local", "use", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L560-L570
233,638
cloudtools/stacker
stacker/util.py
SourceProcessor.fetch_local_package
def fetch_local_package(self, config): """Make a local path available to current stacker config. Args: config (dict): 'local' path config dictionary """ # Update sys.path & merge in remote configs (if necessary) self.update_paths_and_config(config=config, pkg_dir_name=config['source'], pkg_cache_dir=os.getcwd())
python
def fetch_local_package(self, config): # Update sys.path & merge in remote configs (if necessary) self.update_paths_and_config(config=config, pkg_dir_name=config['source'], pkg_cache_dir=os.getcwd())
[ "def", "fetch_local_package", "(", "self", ",", "config", ")", ":", "# Update sys.path & merge in remote configs (if necessary)", "self", ".", "update_paths_and_config", "(", "config", "=", "config", ",", "pkg_dir_name", "=", "config", "[", "'source'", "]", ",", "pkg_...
Make a local path available to current stacker config. Args: config (dict): 'local' path config dictionary
[ "Make", "a", "local", "path", "available", "to", "current", "stacker", "config", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L572-L582
233,639
cloudtools/stacker
stacker/util.py
SourceProcessor.fetch_git_package
def fetch_git_package(self, config): """Make a remote git repository available for local use. Args: config (dict): git config dictionary """ # only loading git here when needed to avoid load errors on systems # without git installed from git import Repo ref = self.determine_git_ref(config) dir_name = self.sanitize_git_path(uri=config['uri'], ref=ref) cached_dir_path = os.path.join(self.package_cache_dir, dir_name) # We can skip cloning the repo if it's already been cached if not os.path.isdir(cached_dir_path): logger.debug("Remote repo %s does not appear to have been " "previously downloaded - starting clone to %s", config['uri'], cached_dir_path) tmp_dir = tempfile.mkdtemp(prefix='stacker') try: tmp_repo_path = os.path.join(tmp_dir, dir_name) with Repo.clone_from(config['uri'], tmp_repo_path) as repo: repo.head.reference = ref repo.head.reset(index=True, working_tree=True) shutil.move(tmp_repo_path, self.package_cache_dir) finally: shutil.rmtree(tmp_dir) else: logger.debug("Remote repo %s appears to have been previously " "cloned to %s -- bypassing download", config['uri'], cached_dir_path) # Update sys.path & merge in remote configs (if necessary) self.update_paths_and_config(config=config, pkg_dir_name=dir_name)
python
def fetch_git_package(self, config): # only loading git here when needed to avoid load errors on systems # without git installed from git import Repo ref = self.determine_git_ref(config) dir_name = self.sanitize_git_path(uri=config['uri'], ref=ref) cached_dir_path = os.path.join(self.package_cache_dir, dir_name) # We can skip cloning the repo if it's already been cached if not os.path.isdir(cached_dir_path): logger.debug("Remote repo %s does not appear to have been " "previously downloaded - starting clone to %s", config['uri'], cached_dir_path) tmp_dir = tempfile.mkdtemp(prefix='stacker') try: tmp_repo_path = os.path.join(tmp_dir, dir_name) with Repo.clone_from(config['uri'], tmp_repo_path) as repo: repo.head.reference = ref repo.head.reset(index=True, working_tree=True) shutil.move(tmp_repo_path, self.package_cache_dir) finally: shutil.rmtree(tmp_dir) else: logger.debug("Remote repo %s appears to have been previously " "cloned to %s -- bypassing download", config['uri'], cached_dir_path) # Update sys.path & merge in remote configs (if necessary) self.update_paths_and_config(config=config, pkg_dir_name=dir_name)
[ "def", "fetch_git_package", "(", "self", ",", "config", ")", ":", "# only loading git here when needed to avoid load errors on systems", "# without git installed", "from", "git", "import", "Repo", "ref", "=", "self", ".", "determine_git_ref", "(", "config", ")", "dir_name...
Make a remote git repository available for local use. Args: config (dict): git config dictionary
[ "Make", "a", "remote", "git", "repository", "available", "for", "local", "use", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L682-L720
233,640
cloudtools/stacker
stacker/util.py
SourceProcessor.update_paths_and_config
def update_paths_and_config(self, config, pkg_dir_name, pkg_cache_dir=None): """Handle remote source defined sys.paths & configs. Args: config (dict): git config dictionary pkg_dir_name (string): directory name of the stacker archive pkg_cache_dir (string): fully qualified path to stacker cache cache directory """ if pkg_cache_dir is None: pkg_cache_dir = self.package_cache_dir cached_dir_path = os.path.join(pkg_cache_dir, pkg_dir_name) # Add the appropriate directory (or directories) to sys.path if config.get('paths'): for path in config['paths']: path_to_append = os.path.join(cached_dir_path, path) logger.debug("Appending \"%s\" to python sys.path", path_to_append) sys.path.append(path_to_append) else: sys.path.append(cached_dir_path) # If the configuration defines a set of remote config yamls to # include, add them to the list for merging if config.get('configs'): for config_filename in config['configs']: self.configs_to_merge.append(os.path.join(cached_dir_path, config_filename))
python
def update_paths_and_config(self, config, pkg_dir_name, pkg_cache_dir=None): if pkg_cache_dir is None: pkg_cache_dir = self.package_cache_dir cached_dir_path = os.path.join(pkg_cache_dir, pkg_dir_name) # Add the appropriate directory (or directories) to sys.path if config.get('paths'): for path in config['paths']: path_to_append = os.path.join(cached_dir_path, path) logger.debug("Appending \"%s\" to python sys.path", path_to_append) sys.path.append(path_to_append) else: sys.path.append(cached_dir_path) # If the configuration defines a set of remote config yamls to # include, add them to the list for merging if config.get('configs'): for config_filename in config['configs']: self.configs_to_merge.append(os.path.join(cached_dir_path, config_filename))
[ "def", "update_paths_and_config", "(", "self", ",", "config", ",", "pkg_dir_name", ",", "pkg_cache_dir", "=", "None", ")", ":", "if", "pkg_cache_dir", "is", "None", ":", "pkg_cache_dir", "=", "self", ".", "package_cache_dir", "cached_dir_path", "=", "os", ".", ...
Handle remote source defined sys.paths & configs. Args: config (dict): git config dictionary pkg_dir_name (string): directory name of the stacker archive pkg_cache_dir (string): fully qualified path to stacker cache cache directory
[ "Handle", "remote", "source", "defined", "sys", ".", "paths", "&", "configs", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L722-L753
233,641
cloudtools/stacker
stacker/util.py
SourceProcessor.git_ls_remote
def git_ls_remote(self, uri, ref): """Determine the latest commit id for a given ref. Args: uri (string): git URI ref (string): git ref Returns: str: A commit id """ logger.debug("Invoking git to retrieve commit id for repo %s...", uri) lsremote_output = subprocess.check_output(['git', 'ls-remote', uri, ref]) if b"\t" in lsremote_output: commit_id = lsremote_output.split(b"\t")[0] logger.debug("Matching commit id found: %s", commit_id) return commit_id else: raise ValueError("Ref \"%s\" not found for repo %s." % (ref, uri))
python
def git_ls_remote(self, uri, ref): logger.debug("Invoking git to retrieve commit id for repo %s...", uri) lsremote_output = subprocess.check_output(['git', 'ls-remote', uri, ref]) if b"\t" in lsremote_output: commit_id = lsremote_output.split(b"\t")[0] logger.debug("Matching commit id found: %s", commit_id) return commit_id else: raise ValueError("Ref \"%s\" not found for repo %s." % (ref, uri))
[ "def", "git_ls_remote", "(", "self", ",", "uri", ",", "ref", ")", ":", "logger", ".", "debug", "(", "\"Invoking git to retrieve commit id for repo %s...\"", ",", "uri", ")", "lsremote_output", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'ls-...
Determine the latest commit id for a given ref. Args: uri (string): git URI ref (string): git ref Returns: str: A commit id
[ "Determine", "the", "latest", "commit", "id", "for", "a", "given", "ref", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L755-L776
233,642
cloudtools/stacker
stacker/util.py
SourceProcessor.determine_git_ref
def determine_git_ref(self, config): """Determine the ref to be used for 'git checkout'. Args: config (dict): git config dictionary Returns: str: A commit id or tag name """ # First ensure redundant config keys aren't specified (which could # cause confusion as to which take precedence) ref_config_keys = 0 for i in ['commit', 'tag', 'branch']: if config.get(i): ref_config_keys += 1 if ref_config_keys > 1: raise ImportError("Fetching remote git sources failed: " "conflicting revisions (e.g. 'commit', 'tag', " "'branch') specified for a package source") # Now check for a specific point in time referenced and return it if # present if config.get('commit'): ref = config['commit'] elif config.get('tag'): ref = config['tag'] else: # Since a specific commit/tag point in time has not been specified, # check the remote repo for the commit id to use ref = self.git_ls_remote( config['uri'], self.determine_git_ls_remote_ref(config) ) if sys.version_info[0] > 2 and isinstance(ref, bytes): return ref.decode() return ref
python
def determine_git_ref(self, config): # First ensure redundant config keys aren't specified (which could # cause confusion as to which take precedence) ref_config_keys = 0 for i in ['commit', 'tag', 'branch']: if config.get(i): ref_config_keys += 1 if ref_config_keys > 1: raise ImportError("Fetching remote git sources failed: " "conflicting revisions (e.g. 'commit', 'tag', " "'branch') specified for a package source") # Now check for a specific point in time referenced and return it if # present if config.get('commit'): ref = config['commit'] elif config.get('tag'): ref = config['tag'] else: # Since a specific commit/tag point in time has not been specified, # check the remote repo for the commit id to use ref = self.git_ls_remote( config['uri'], self.determine_git_ls_remote_ref(config) ) if sys.version_info[0] > 2 and isinstance(ref, bytes): return ref.decode() return ref
[ "def", "determine_git_ref", "(", "self", ",", "config", ")", ":", "# First ensure redundant config keys aren't specified (which could", "# cause confusion as to which take precedence)", "ref_config_keys", "=", "0", "for", "i", "in", "[", "'commit'", ",", "'tag'", ",", "'bra...
Determine the ref to be used for 'git checkout'. Args: config (dict): git config dictionary Returns: str: A commit id or tag name
[ "Determine", "the", "ref", "to", "be", "used", "for", "git", "checkout", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L796-L832
233,643
cloudtools/stacker
stacker/util.py
SourceProcessor.sanitize_git_path
def sanitize_git_path(self, uri, ref=None): """Take a git URI and ref and converts it to a directory safe path. Args: uri (string): git URI (e.g. git@github.com:foo/bar.git) ref (string): optional git ref to be appended to the path Returns: str: Directory name for the supplied uri """ if uri.endswith('.git'): dir_name = uri[:-4] # drop .git else: dir_name = uri dir_name = self.sanitize_uri_path(dir_name) if ref is not None: dir_name += "-%s" % ref return dir_name
python
def sanitize_git_path(self, uri, ref=None): if uri.endswith('.git'): dir_name = uri[:-4] # drop .git else: dir_name = uri dir_name = self.sanitize_uri_path(dir_name) if ref is not None: dir_name += "-%s" % ref return dir_name
[ "def", "sanitize_git_path", "(", "self", ",", "uri", ",", "ref", "=", "None", ")", ":", "if", "uri", ".", "endswith", "(", "'.git'", ")", ":", "dir_name", "=", "uri", "[", ":", "-", "4", "]", "# drop .git", "else", ":", "dir_name", "=", "uri", "dir...
Take a git URI and ref and converts it to a directory safe path. Args: uri (string): git URI (e.g. git@github.com:foo/bar.git) ref (string): optional git ref to be appended to the path Returns: str: Directory name for the supplied uri
[ "Take", "a", "git", "URI", "and", "ref", "and", "converts", "it", "to", "a", "directory", "safe", "path", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L848-L867
233,644
cloudtools/stacker
stacker/hooks/command.py
run_command
def run_command(provider, context, command, capture=False, interactive=False, ignore_status=False, quiet=False, stdin=None, env=None, **kwargs): """Run a custom command as a hook Keyword Arguments: command (list or str): Command to run capture (bool, optional): If enabled, capture the command's stdout and stderr, and return them in the hook result. Default: false interactive (bool, optional): If enabled, allow the command to interact with stdin. Otherwise, stdin will be set to the null device. Default: false ignore_status (bool, optional): Don't fail the hook if the command returns a non-zero status. Default: false quiet (bool, optional): Redirect the command's stdout and stderr to the null device, silencing all output. Should not be enaled if `capture` is also enabled. Default: false stdin (str, optional): String to send to the stdin of the command. Implicitly disables `interactive`. env (dict, optional): Dictionary of environment variable overrides for the command context. Will be merged with the current environment. **kwargs: Any other arguments will be forwarded to the `subprocess.Popen` function. Interesting ones include: `cwd` and `shell`. Examples: .. code-block:: yaml pre_build: - path: stacker.hooks.command.run_command required: true enabled: true data_key: copy_env args: command: ['cp', 'environment.template', 'environment'] - path: stacker.hooks.command.run_command required: true enabled: true data_key: get_git_commit args: command: ['git', 'rev-parse', 'HEAD'] cwd: ./my-git-repo capture: true - path: stacker.hooks.command.run_command args: command: `cd $PROJECT_DIR/project; npm install' env: PROJECT_DIR: ./my-project shell: true """ if quiet and capture: raise ImproperlyConfigured( __name__ + '.run_command', 'Cannot enable `quiet` and `capture` options simultaneously') if quiet: out_err_type = _devnull() elif capture: out_err_type = PIPE else: out_err_type = None if interactive: in_type = None elif stdin: in_type = PIPE else: in_type = _devnull() if env: full_env = os.environ.copy() full_env.update(env) env = full_env logger.info('Running command: %s', command) proc = Popen(command, stdin=in_type, stdout=out_err_type, stderr=out_err_type, env=env, **kwargs) try: out, err = proc.communicate(stdin) status = proc.wait() if status == 0 or ignore_status: return { 'returncode': proc.returncode, 'stdout': out, 'stderr': err } # Don't print the command line again if we already did earlier if logger.isEnabledFor(logging.INFO): logger.warn('Command failed with returncode %d', status) else: logger.warn('Command failed with returncode %d: %s', status, command) return None finally: if proc.returncode is None: proc.kill()
python
def run_command(provider, context, command, capture=False, interactive=False, ignore_status=False, quiet=False, stdin=None, env=None, **kwargs): if quiet and capture: raise ImproperlyConfigured( __name__ + '.run_command', 'Cannot enable `quiet` and `capture` options simultaneously') if quiet: out_err_type = _devnull() elif capture: out_err_type = PIPE else: out_err_type = None if interactive: in_type = None elif stdin: in_type = PIPE else: in_type = _devnull() if env: full_env = os.environ.copy() full_env.update(env) env = full_env logger.info('Running command: %s', command) proc = Popen(command, stdin=in_type, stdout=out_err_type, stderr=out_err_type, env=env, **kwargs) try: out, err = proc.communicate(stdin) status = proc.wait() if status == 0 or ignore_status: return { 'returncode': proc.returncode, 'stdout': out, 'stderr': err } # Don't print the command line again if we already did earlier if logger.isEnabledFor(logging.INFO): logger.warn('Command failed with returncode %d', status) else: logger.warn('Command failed with returncode %d: %s', status, command) return None finally: if proc.returncode is None: proc.kill()
[ "def", "run_command", "(", "provider", ",", "context", ",", "command", ",", "capture", "=", "False", ",", "interactive", "=", "False", ",", "ignore_status", "=", "False", ",", "quiet", "=", "False", ",", "stdin", "=", "None", ",", "env", "=", "None", "...
Run a custom command as a hook Keyword Arguments: command (list or str): Command to run capture (bool, optional): If enabled, capture the command's stdout and stderr, and return them in the hook result. Default: false interactive (bool, optional): If enabled, allow the command to interact with stdin. Otherwise, stdin will be set to the null device. Default: false ignore_status (bool, optional): Don't fail the hook if the command returns a non-zero status. Default: false quiet (bool, optional): Redirect the command's stdout and stderr to the null device, silencing all output. Should not be enaled if `capture` is also enabled. Default: false stdin (str, optional): String to send to the stdin of the command. Implicitly disables `interactive`. env (dict, optional): Dictionary of environment variable overrides for the command context. Will be merged with the current environment. **kwargs: Any other arguments will be forwarded to the `subprocess.Popen` function. Interesting ones include: `cwd` and `shell`. Examples: .. code-block:: yaml pre_build: - path: stacker.hooks.command.run_command required: true enabled: true data_key: copy_env args: command: ['cp', 'environment.template', 'environment'] - path: stacker.hooks.command.run_command required: true enabled: true data_key: get_git_commit args: command: ['git', 'rev-parse', 'HEAD'] cwd: ./my-git-repo capture: true - path: stacker.hooks.command.run_command args: command: `cd $PROJECT_DIR/project; npm install' env: PROJECT_DIR: ./my-project shell: true
[ "Run", "a", "custom", "command", "as", "a", "hook" ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/command.py#L18-L124
233,645
cloudtools/stacker
stacker/hooks/keypair.py
ensure_keypair_exists
def ensure_keypair_exists(provider, context, **kwargs): """Ensure a specific keypair exists within AWS. If the key doesn't exist, upload it. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance keypair (str): name of the key pair to create ssm_parameter_name (str, optional): path to an SSM store parameter to receive the generated private key, instead of importing it or storing it locally. ssm_key_id (str, optional): ID of a KMS key to encrypt the SSM parameter with. If omitted, the default key will be used. public_key_path (str, optional): path to a public key file to be imported instead of generating a new key. Incompatible with the SSM options, as the private key will not be available for storing. Returns: In case of failure ``False``, otherwise a dict containing: status (str): one of "exists", "imported" or "created" key_name (str): name of the key pair fingerprint (str): fingerprint of the key pair file_path (str, optional): if a new key was created, the path to the file where the private key was stored """ keypair_name = kwargs["keypair"] ssm_parameter_name = kwargs.get("ssm_parameter_name") ssm_key_id = kwargs.get("ssm_key_id") public_key_path = kwargs.get("public_key_path") if public_key_path and ssm_parameter_name: logger.error("public_key_path and ssm_parameter_name cannot be " "specified at the same time") return False session = get_session(region=provider.region, profile=kwargs.get("profile")) ec2 = session.client("ec2") keypair = get_existing_key_pair(ec2, keypair_name) if keypair: return keypair if public_key_path: keypair = create_key_pair_from_public_key_file( ec2, keypair_name, public_key_path) elif ssm_parameter_name: ssm = session.client('ssm') keypair = create_key_pair_in_ssm( ec2, ssm, keypair_name, ssm_parameter_name, ssm_key_id) else: action, path = interactive_prompt(keypair_name) if action == "import": keypair = create_key_pair_from_public_key_file( ec2, keypair_name, path) elif action == "create": keypair = create_key_pair_local(ec2, keypair_name, path) else: logger.warning("no action to find keypair, failing") if not keypair: return False return keypair
python
def ensure_keypair_exists(provider, context, **kwargs): keypair_name = kwargs["keypair"] ssm_parameter_name = kwargs.get("ssm_parameter_name") ssm_key_id = kwargs.get("ssm_key_id") public_key_path = kwargs.get("public_key_path") if public_key_path and ssm_parameter_name: logger.error("public_key_path and ssm_parameter_name cannot be " "specified at the same time") return False session = get_session(region=provider.region, profile=kwargs.get("profile")) ec2 = session.client("ec2") keypair = get_existing_key_pair(ec2, keypair_name) if keypair: return keypair if public_key_path: keypair = create_key_pair_from_public_key_file( ec2, keypair_name, public_key_path) elif ssm_parameter_name: ssm = session.client('ssm') keypair = create_key_pair_in_ssm( ec2, ssm, keypair_name, ssm_parameter_name, ssm_key_id) else: action, path = interactive_prompt(keypair_name) if action == "import": keypair = create_key_pair_from_public_key_file( ec2, keypair_name, path) elif action == "create": keypair = create_key_pair_local(ec2, keypair_name, path) else: logger.warning("no action to find keypair, failing") if not keypair: return False return keypair
[ "def", "ensure_keypair_exists", "(", "provider", ",", "context", ",", "*", "*", "kwargs", ")", ":", "keypair_name", "=", "kwargs", "[", "\"keypair\"", "]", "ssm_parameter_name", "=", "kwargs", ".", "get", "(", "\"ssm_parameter_name\"", ")", "ssm_key_id", "=", ...
Ensure a specific keypair exists within AWS. If the key doesn't exist, upload it. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance keypair (str): name of the key pair to create ssm_parameter_name (str, optional): path to an SSM store parameter to receive the generated private key, instead of importing it or storing it locally. ssm_key_id (str, optional): ID of a KMS key to encrypt the SSM parameter with. If omitted, the default key will be used. public_key_path (str, optional): path to a public key file to be imported instead of generating a new key. Incompatible with the SSM options, as the private key will not be available for storing. Returns: In case of failure ``False``, otherwise a dict containing: status (str): one of "exists", "imported" or "created" key_name (str): name of the key pair fingerprint (str): fingerprint of the key pair file_path (str, optional): if a new key was created, the path to the file where the private key was stored
[ "Ensure", "a", "specific", "keypair", "exists", "within", "AWS", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/keypair.py#L184-L252
233,646
cloudtools/stacker
stacker/context.py
get_fqn
def get_fqn(base_fqn, delimiter, name=None): """Return the fully qualified name of an object within this context. If the name passed already appears to be a fully qualified name, it will be returned with no further processing. """ if name and name.startswith("%s%s" % (base_fqn, delimiter)): return name return delimiter.join([_f for _f in [base_fqn, name] if _f])
python
def get_fqn(base_fqn, delimiter, name=None): if name and name.startswith("%s%s" % (base_fqn, delimiter)): return name return delimiter.join([_f for _f in [base_fqn, name] if _f])
[ "def", "get_fqn", "(", "base_fqn", ",", "delimiter", ",", "name", "=", "None", ")", ":", "if", "name", "and", "name", ".", "startswith", "(", "\"%s%s\"", "%", "(", "base_fqn", ",", "delimiter", ")", ")", ":", "return", "name", "return", "delimiter", "....
Return the fully qualified name of an object within this context. If the name passed already appears to be a fully qualified name, it will be returned with no further processing.
[ "Return", "the", "fully", "qualified", "name", "of", "an", "object", "within", "this", "context", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/context.py#L19-L29
233,647
cloudtools/stacker
stacker/context.py
Context.get_targets
def get_targets(self): """Returns the named targets that are specified in the config. Returns: list: a list of :class:`stacker.target.Target` objects """ if not hasattr(self, "_targets"): targets = [] for target_def in self.config.targets or []: target = Target(target_def) targets.append(target) self._targets = targets return self._targets
python
def get_targets(self): if not hasattr(self, "_targets"): targets = [] for target_def in self.config.targets or []: target = Target(target_def) targets.append(target) self._targets = targets return self._targets
[ "def", "get_targets", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_targets\"", ")", ":", "targets", "=", "[", "]", "for", "target_def", "in", "self", ".", "config", ".", "targets", "or", "[", "]", ":", "target", "=", "Target",...
Returns the named targets that are specified in the config. Returns: list: a list of :class:`stacker.target.Target` objects
[ "Returns", "the", "named", "targets", "that", "are", "specified", "in", "the", "config", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/context.py#L127-L140
233,648
cloudtools/stacker
stacker/context.py
Context.get_stacks
def get_stacks(self): """Get the stacks for the current action. Handles configuring the :class:`stacker.stack.Stack` objects that will be used in the current action. Returns: list: a list of :class:`stacker.stack.Stack` objects """ if not hasattr(self, "_stacks"): stacks = [] definitions = self._get_stack_definitions() for stack_def in definitions: stack = Stack( definition=stack_def, context=self, mappings=self.mappings, force=stack_def.name in self.force_stacks, locked=stack_def.locked, enabled=stack_def.enabled, protected=stack_def.protected, ) stacks.append(stack) self._stacks = stacks return self._stacks
python
def get_stacks(self): if not hasattr(self, "_stacks"): stacks = [] definitions = self._get_stack_definitions() for stack_def in definitions: stack = Stack( definition=stack_def, context=self, mappings=self.mappings, force=stack_def.name in self.force_stacks, locked=stack_def.locked, enabled=stack_def.enabled, protected=stack_def.protected, ) stacks.append(stack) self._stacks = stacks return self._stacks
[ "def", "get_stacks", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_stacks\"", ")", ":", "stacks", "=", "[", "]", "definitions", "=", "self", ".", "_get_stack_definitions", "(", ")", "for", "stack_def", "in", "definitions", ":", "st...
Get the stacks for the current action. Handles configuring the :class:`stacker.stack.Stack` objects that will be used in the current action. Returns: list: a list of :class:`stacker.stack.Stack` objects
[ "Get", "the", "stacks", "for", "the", "current", "action", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/context.py#L142-L167
233,649
cloudtools/stacker
stacker/context.py
Context.set_hook_data
def set_hook_data(self, key, data): """Set hook data for the given key. Args: key(str): The key to store the hook data in. data(:class:`collections.Mapping`): A dictionary of data to store, as returned from a hook. """ if not isinstance(data, collections.Mapping): raise ValueError("Hook (key: %s) data must be an instance of " "collections.Mapping (a dictionary for " "example)." % key) if key in self.hook_data: raise KeyError("Hook data for key %s already exists, each hook " "must have a unique data_key.", key) self.hook_data[key] = data
python
def set_hook_data(self, key, data): if not isinstance(data, collections.Mapping): raise ValueError("Hook (key: %s) data must be an instance of " "collections.Mapping (a dictionary for " "example)." % key) if key in self.hook_data: raise KeyError("Hook data for key %s already exists, each hook " "must have a unique data_key.", key) self.hook_data[key] = data
[ "def", "set_hook_data", "(", "self", ",", "key", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "collections", ".", "Mapping", ")", ":", "raise", "ValueError", "(", "\"Hook (key: %s) data must be an instance of \"", "\"collections.Mapping (a dic...
Set hook data for the given key. Args: key(str): The key to store the hook data in. data(:class:`collections.Mapping`): A dictionary of data to store, as returned from a hook.
[ "Set", "hook", "data", "for", "the", "given", "key", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/context.py#L186-L204
233,650
cloudtools/stacker
stacker/config/__init__.py
render_parse_load
def render_parse_load(raw_config, environment=None, validate=True): """Encapsulates the render -> parse -> validate -> load process. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config validate (bool): if provided, the config is validated before being loaded. Returns: :class:`Config`: the parsed stacker config. """ pre_rendered = render(raw_config, environment) rendered = process_remote_sources(pre_rendered, environment) config = parse(rendered) # For backwards compatibility, if the config doesn't specify a namespace, # we fall back to fetching it from the environment, if provided. if config.namespace is None: namespace = environment.get("namespace") if namespace: logger.warn("DEPRECATION WARNING: specifying namespace in the " "environment is deprecated. See " "https://stacker.readthedocs.io/en/latest/config.html" "#namespace " "for more info.") config.namespace = namespace if validate: config.validate() return load(config)
python
def render_parse_load(raw_config, environment=None, validate=True): pre_rendered = render(raw_config, environment) rendered = process_remote_sources(pre_rendered, environment) config = parse(rendered) # For backwards compatibility, if the config doesn't specify a namespace, # we fall back to fetching it from the environment, if provided. if config.namespace is None: namespace = environment.get("namespace") if namespace: logger.warn("DEPRECATION WARNING: specifying namespace in the " "environment is deprecated. See " "https://stacker.readthedocs.io/en/latest/config.html" "#namespace " "for more info.") config.namespace = namespace if validate: config.validate() return load(config)
[ "def", "render_parse_load", "(", "raw_config", ",", "environment", "=", "None", ",", "validate", "=", "True", ")", ":", "pre_rendered", "=", "render", "(", "raw_config", ",", "environment", ")", "rendered", "=", "process_remote_sources", "(", "pre_rendered", ","...
Encapsulates the render -> parse -> validate -> load process. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config validate (bool): if provided, the config is validated before being loaded. Returns: :class:`Config`: the parsed stacker config.
[ "Encapsulates", "the", "render", "-", ">", "parse", "-", ">", "validate", "-", ">", "load", "process", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L42-L78
233,651
cloudtools/stacker
stacker/config/__init__.py
render
def render(raw_config, environment=None): """Renders a config, using it as a template with the environment. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config Returns: str: the stacker configuration populated with any values passed from the environment """ t = Template(raw_config) buff = StringIO() if not environment: environment = {} try: substituted = t.substitute(environment) except KeyError as e: raise exceptions.MissingEnvironment(e.args[0]) except ValueError: # Support "invalid" placeholders for lookup placeholders. substituted = t.safe_substitute(environment) if not isinstance(substituted, str): substituted = substituted.decode('utf-8') buff.write(substituted) buff.seek(0) return buff.read()
python
def render(raw_config, environment=None): t = Template(raw_config) buff = StringIO() if not environment: environment = {} try: substituted = t.substitute(environment) except KeyError as e: raise exceptions.MissingEnvironment(e.args[0]) except ValueError: # Support "invalid" placeholders for lookup placeholders. substituted = t.safe_substitute(environment) if not isinstance(substituted, str): substituted = substituted.decode('utf-8') buff.write(substituted) buff.seek(0) return buff.read()
[ "def", "render", "(", "raw_config", ",", "environment", "=", "None", ")", ":", "t", "=", "Template", "(", "raw_config", ")", "buff", "=", "StringIO", "(", ")", "if", "not", "environment", ":", "environment", "=", "{", "}", "try", ":", "substituted", "=...
Renders a config, using it as a template with the environment. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config Returns: str: the stacker configuration populated with any values passed from the environment
[ "Renders", "a", "config", "using", "it", "as", "a", "template", "with", "the", "environment", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L81-L112
233,652
cloudtools/stacker
stacker/config/__init__.py
parse
def parse(raw_config): """Parse a raw yaml formatted stacker config. Args: raw_config (str): the raw stacker configuration string in yaml format. Returns: :class:`Config`: the parsed stacker config. """ # Convert any applicable dictionaries back into lists # This is necessary due to the move from lists for these top level config # values to either lists or OrderedDicts. # Eventually we should probably just make them OrderedDicts only. config_dict = yaml_to_ordered_dict(raw_config) if config_dict: for top_level_key in ['stacks', 'pre_build', 'post_build', 'pre_destroy', 'post_destroy']: top_level_value = config_dict.get(top_level_key) if isinstance(top_level_value, dict): tmp_list = [] for key, value in top_level_value.items(): tmp_dict = copy.deepcopy(value) if top_level_key == 'stacks': tmp_dict['name'] = key tmp_list.append(tmp_dict) config_dict[top_level_key] = tmp_list # Top-level excess keys are removed by Config._convert, so enabling strict # mode is fine here. try: return Config(config_dict, strict=True) except SchematicsError as e: raise exceptions.InvalidConfig(e.errors)
python
def parse(raw_config): # Convert any applicable dictionaries back into lists # This is necessary due to the move from lists for these top level config # values to either lists or OrderedDicts. # Eventually we should probably just make them OrderedDicts only. config_dict = yaml_to_ordered_dict(raw_config) if config_dict: for top_level_key in ['stacks', 'pre_build', 'post_build', 'pre_destroy', 'post_destroy']: top_level_value = config_dict.get(top_level_key) if isinstance(top_level_value, dict): tmp_list = [] for key, value in top_level_value.items(): tmp_dict = copy.deepcopy(value) if top_level_key == 'stacks': tmp_dict['name'] = key tmp_list.append(tmp_dict) config_dict[top_level_key] = tmp_list # Top-level excess keys are removed by Config._convert, so enabling strict # mode is fine here. try: return Config(config_dict, strict=True) except SchematicsError as e: raise exceptions.InvalidConfig(e.errors)
[ "def", "parse", "(", "raw_config", ")", ":", "# Convert any applicable dictionaries back into lists", "# This is necessary due to the move from lists for these top level config", "# values to either lists or OrderedDicts.", "# Eventually we should probably just make them OrderedDicts only.", "co...
Parse a raw yaml formatted stacker config. Args: raw_config (str): the raw stacker configuration string in yaml format. Returns: :class:`Config`: the parsed stacker config.
[ "Parse", "a", "raw", "yaml", "formatted", "stacker", "config", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L115-L149
233,653
cloudtools/stacker
stacker/config/__init__.py
load
def load(config): """Loads a stacker configuration by modifying sys paths, loading lookups, etc. Args: config (:class:`Config`): the stacker config to load. Returns: :class:`Config`: the stacker config provided above. """ if config.sys_path: logger.debug("Appending %s to sys.path.", config.sys_path) sys.path.append(config.sys_path) logger.debug("sys.path is now %s", sys.path) if config.lookups: for key, handler in config.lookups.items(): register_lookup_handler(key, handler) return config
python
def load(config): if config.sys_path: logger.debug("Appending %s to sys.path.", config.sys_path) sys.path.append(config.sys_path) logger.debug("sys.path is now %s", sys.path) if config.lookups: for key, handler in config.lookups.items(): register_lookup_handler(key, handler) return config
[ "def", "load", "(", "config", ")", ":", "if", "config", ".", "sys_path", ":", "logger", ".", "debug", "(", "\"Appending %s to sys.path.\"", ",", "config", ".", "sys_path", ")", "sys", ".", "path", ".", "append", "(", "config", ".", "sys_path", ")", "logg...
Loads a stacker configuration by modifying sys paths, loading lookups, etc. Args: config (:class:`Config`): the stacker config to load. Returns: :class:`Config`: the stacker config provided above.
[ "Loads", "a", "stacker", "configuration", "by", "modifying", "sys", "paths", "loading", "lookups", "etc", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L152-L172
233,654
cloudtools/stacker
stacker/config/__init__.py
dump
def dump(config): """Dumps a stacker Config object as yaml. Args: config (:class:`Config`): the stacker Config object. stream (stream): an optional stream object to write to. Returns: str: the yaml formatted stacker Config. """ return yaml.safe_dump( config.to_primitive(), default_flow_style=False, encoding='utf-8', allow_unicode=True)
python
def dump(config): return yaml.safe_dump( config.to_primitive(), default_flow_style=False, encoding='utf-8', allow_unicode=True)
[ "def", "dump", "(", "config", ")", ":", "return", "yaml", ".", "safe_dump", "(", "config", ".", "to_primitive", "(", ")", ",", "default_flow_style", "=", "False", ",", "encoding", "=", "'utf-8'", ",", "allow_unicode", "=", "True", ")" ]
Dumps a stacker Config object as yaml. Args: config (:class:`Config`): the stacker Config object. stream (stream): an optional stream object to write to. Returns: str: the yaml formatted stacker Config.
[ "Dumps", "a", "stacker", "Config", "object", "as", "yaml", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L175-L191
233,655
cloudtools/stacker
stacker/config/__init__.py
process_remote_sources
def process_remote_sources(raw_config, environment=None): """Stage remote package sources and merge in remote configs. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config Returns: str: the raw stacker configuration string """ config = yaml.safe_load(raw_config) if config and config.get('package_sources'): processor = SourceProcessor( sources=config['package_sources'], stacker_cache_dir=config.get('stacker_cache_dir') ) processor.get_package_sources() if processor.configs_to_merge: for i in processor.configs_to_merge: logger.debug("Merging in remote config \"%s\"", i) remote_config = yaml.safe_load(open(i)) config = merge_map(remote_config, config) # Call the render again as the package_sources may have merged in # additional environment lookups if not environment: environment = {} return render(str(config), environment) return raw_config
python
def process_remote_sources(raw_config, environment=None): config = yaml.safe_load(raw_config) if config and config.get('package_sources'): processor = SourceProcessor( sources=config['package_sources'], stacker_cache_dir=config.get('stacker_cache_dir') ) processor.get_package_sources() if processor.configs_to_merge: for i in processor.configs_to_merge: logger.debug("Merging in remote config \"%s\"", i) remote_config = yaml.safe_load(open(i)) config = merge_map(remote_config, config) # Call the render again as the package_sources may have merged in # additional environment lookups if not environment: environment = {} return render(str(config), environment) return raw_config
[ "def", "process_remote_sources", "(", "raw_config", ",", "environment", "=", "None", ")", ":", "config", "=", "yaml", ".", "safe_load", "(", "raw_config", ")", "if", "config", "and", "config", ".", "get", "(", "'package_sources'", ")", ":", "processor", "=",...
Stage remote package sources and merge in remote configs. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config Returns: str: the raw stacker configuration string
[ "Stage", "remote", "package", "sources", "and", "merge", "in", "remote", "configs", "." ]
ad6013a03a560c46ba3c63c4d153336273e6da5d
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/config/__init__.py#L194-L225
233,656
SoCo/SoCo
soco/plugins/wimp.py
_post
def _post(url, headers, body, retries=3, timeout=3.0): """Try 3 times to request the content. :param headers: The HTTP headers :type headers: dict :param body: The body of the HTTP post :type body: str :param retries: The number of times to retry before giving up :type retries: int :param timeout: The time to wait for the post to complete, before timing out :type timeout: float """ retry = 0 out = None while out is None: try: out = requests.post(url, headers=headers, data=body, timeout=timeout) # Due to a bug in requests, the post command will sometimes fail to # properly wrap a socket.timeout exception in requests own exception. # See https://github.com/kennethreitz/requests/issues/2045 # Until this is fixed, we need to catch both types of exceptions except (requests.exceptions.Timeout, socket.timeout) as exception: retry += 1 if retry == retries: # pylint: disable=maybe-no-member raise requests.exceptions.Timeout(exception.message) return out
python
def _post(url, headers, body, retries=3, timeout=3.0): retry = 0 out = None while out is None: try: out = requests.post(url, headers=headers, data=body, timeout=timeout) # Due to a bug in requests, the post command will sometimes fail to # properly wrap a socket.timeout exception in requests own exception. # See https://github.com/kennethreitz/requests/issues/2045 # Until this is fixed, we need to catch both types of exceptions except (requests.exceptions.Timeout, socket.timeout) as exception: retry += 1 if retry == retries: # pylint: disable=maybe-no-member raise requests.exceptions.Timeout(exception.message) return out
[ "def", "_post", "(", "url", ",", "headers", ",", "body", ",", "retries", "=", "3", ",", "timeout", "=", "3.0", ")", ":", "retry", "=", "0", "out", "=", "None", "while", "out", "is", "None", ":", "try", ":", "out", "=", "requests", ".", "post", ...
Try 3 times to request the content. :param headers: The HTTP headers :type headers: dict :param body: The body of the HTTP post :type body: str :param retries: The number of times to retry before giving up :type retries: int :param timeout: The time to wait for the post to complete, before timing out :type timeout: float
[ "Try", "3", "times", "to", "request", "the", "content", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L28-L56
233,657
SoCo/SoCo
soco/plugins/wimp.py
_get_header
def _get_header(soap_action): """Return the HTTP for SOAP Action. :param soap_action: The soap action to include in the header. Can be either 'search' or 'get_metadata' :type soap_action: str """ # This way of setting accepted language is obviously flawed, in that it # depends on the locale settings of the system. However, I'm unsure if # they are actually used. The character coding is set elsewhere and I think # the available music in each country is bound to the account. language, _ = locale.getdefaultlocale() if language is None: language = '' else: language = language.replace('_', '-') + ', ' header = { 'CONNECTION': 'close', 'ACCEPT-ENCODING': 'gzip', 'ACCEPT-LANGUAGE': '{}en-US;q=0.9'.format(language), 'Content-Type': 'text/xml; charset="utf-8"', 'SOAPACTION': SOAP_ACTION[soap_action] } return header
python
def _get_header(soap_action): # This way of setting accepted language is obviously flawed, in that it # depends on the locale settings of the system. However, I'm unsure if # they are actually used. The character coding is set elsewhere and I think # the available music in each country is bound to the account. language, _ = locale.getdefaultlocale() if language is None: language = '' else: language = language.replace('_', '-') + ', ' header = { 'CONNECTION': 'close', 'ACCEPT-ENCODING': 'gzip', 'ACCEPT-LANGUAGE': '{}en-US;q=0.9'.format(language), 'Content-Type': 'text/xml; charset="utf-8"', 'SOAPACTION': SOAP_ACTION[soap_action] } return header
[ "def", "_get_header", "(", "soap_action", ")", ":", "# This way of setting accepted language is obviously flawed, in that it", "# depends on the locale settings of the system. However, I'm unsure if", "# they are actually used. The character coding is set elsewhere and I think", "# the available m...
Return the HTTP for SOAP Action. :param soap_action: The soap action to include in the header. Can be either 'search' or 'get_metadata' :type soap_action: str
[ "Return", "the", "HTTP", "for", "SOAP", "Action", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L72-L96
233,658
SoCo/SoCo
soco/plugins/wimp.py
Wimp.get_tracks
def get_tracks(self, search, start=0, max_items=100): """Search for tracks. See get_music_service_information for details on the arguments """ return self.get_music_service_information('tracks', search, start, max_items)
python
def get_tracks(self, search, start=0, max_items=100): return self.get_music_service_information('tracks', search, start, max_items)
[ "def", "get_tracks", "(", "self", ",", "search", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "return", "self", ".", "get_music_service_information", "(", "'tracks'", ",", "search", ",", "start", ",", "max_items", ")" ]
Search for tracks. See get_music_service_information for details on the arguments
[ "Search", "for", "tracks", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L192-L198
233,659
SoCo/SoCo
soco/plugins/wimp.py
Wimp.get_albums
def get_albums(self, search, start=0, max_items=100): """Search for albums. See get_music_service_information for details on the arguments """ return self.get_music_service_information('albums', search, start, max_items)
python
def get_albums(self, search, start=0, max_items=100): return self.get_music_service_information('albums', search, start, max_items)
[ "def", "get_albums", "(", "self", ",", "search", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "return", "self", ".", "get_music_service_information", "(", "'albums'", ",", "search", ",", "start", ",", "max_items", ")" ]
Search for albums. See get_music_service_information for details on the arguments
[ "Search", "for", "albums", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L200-L206
233,660
SoCo/SoCo
soco/plugins/wimp.py
Wimp.get_artists
def get_artists(self, search, start=0, max_items=100): """Search for artists. See get_music_service_information for details on the arguments """ return self.get_music_service_information('artists', search, start, max_items)
python
def get_artists(self, search, start=0, max_items=100): return self.get_music_service_information('artists', search, start, max_items)
[ "def", "get_artists", "(", "self", ",", "search", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "return", "self", ".", "get_music_service_information", "(", "'artists'", ",", "search", ",", "start", ",", "max_items", ")" ]
Search for artists. See get_music_service_information for details on the arguments
[ "Search", "for", "artists", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L208-L214
233,661
SoCo/SoCo
soco/plugins/wimp.py
Wimp.get_playlists
def get_playlists(self, search, start=0, max_items=100): """Search for playlists. See get_music_service_information for details on the arguments. Note: Un-intuitively this method returns MSAlbumList items. See note in class doc string for details. """ return self.get_music_service_information('playlists', search, start, max_items)
python
def get_playlists(self, search, start=0, max_items=100): return self.get_music_service_information('playlists', search, start, max_items)
[ "def", "get_playlists", "(", "self", ",", "search", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "return", "self", ".", "get_music_service_information", "(", "'playlists'", ",", "search", ",", "start", ",", "max_items", ")" ]
Search for playlists. See get_music_service_information for details on the arguments. Note: Un-intuitively this method returns MSAlbumList items. See note in class doc string for details.
[ "Search", "for", "playlists", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L216-L227
233,662
SoCo/SoCo
soco/plugins/wimp.py
Wimp.get_music_service_information
def get_music_service_information(self, search_type, search, start=0, max_items=100): """Search for music service information items. :param search_type: The type of search to perform, possible values are: 'artists', 'albums', 'tracks' and 'playlists' :type search_type: str :param search: The search string to use :type search: str :param start: The starting index of the returned items :type start: int :param max_items: The maximum number of returned items :type max_items: int Note: Un-intuitively the playlist search returns MSAlbumList items. See note in class doc string for details. """ # Check input if search_type not in ['artists', 'albums', 'tracks', 'playlists']: message = 'The requested search {} is not valid'\ .format(search_type) raise ValueError(message) # Transform search: tracks -> tracksearch search_type = '{}earch'.format(search_type) parent_id = SEARCH_PREFIX.format(search_type=search_type, search=search) # Perform search body = self._search_body(search_type, search, start, max_items) headers = _get_header('search') response = _post(self._url, headers, body, **self._http_vars) self._check_for_errors(response) result_dom = XML.fromstring(response.text.encode('utf-8')) # Parse results search_result = result_dom.find('.//' + _ns_tag('', 'searchResult')) out = {'item_list': []} for element in ['index', 'count', 'total']: out[element] = search_result.findtext(_ns_tag('', element)) if search_type == 'tracksearch': item_name = 'mediaMetadata' else: item_name = 'mediaCollection' for element in search_result.findall(_ns_tag('', item_name)): out['item_list'].append(get_ms_item(element, self, parent_id)) return out
python
def get_music_service_information(self, search_type, search, start=0, max_items=100): # Check input if search_type not in ['artists', 'albums', 'tracks', 'playlists']: message = 'The requested search {} is not valid'\ .format(search_type) raise ValueError(message) # Transform search: tracks -> tracksearch search_type = '{}earch'.format(search_type) parent_id = SEARCH_PREFIX.format(search_type=search_type, search=search) # Perform search body = self._search_body(search_type, search, start, max_items) headers = _get_header('search') response = _post(self._url, headers, body, **self._http_vars) self._check_for_errors(response) result_dom = XML.fromstring(response.text.encode('utf-8')) # Parse results search_result = result_dom.find('.//' + _ns_tag('', 'searchResult')) out = {'item_list': []} for element in ['index', 'count', 'total']: out[element] = search_result.findtext(_ns_tag('', element)) if search_type == 'tracksearch': item_name = 'mediaMetadata' else: item_name = 'mediaCollection' for element in search_result.findall(_ns_tag('', item_name)): out['item_list'].append(get_ms_item(element, self, parent_id)) return out
[ "def", "get_music_service_information", "(", "self", ",", "search_type", ",", "search", ",", "start", "=", "0", ",", "max_items", "=", "100", ")", ":", "# Check input", "if", "search_type", "not", "in", "[", "'artists'", ",", "'albums'", ",", "'tracks'", ","...
Search for music service information items. :param search_type: The type of search to perform, possible values are: 'artists', 'albums', 'tracks' and 'playlists' :type search_type: str :param search: The search string to use :type search: str :param start: The starting index of the returned items :type start: int :param max_items: The maximum number of returned items :type max_items: int Note: Un-intuitively the playlist search returns MSAlbumList items. See note in class doc string for details.
[ "Search", "for", "music", "service", "information", "items", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L229-L277
233,663
SoCo/SoCo
soco/plugins/wimp.py
Wimp.browse
def browse(self, ms_item=None): """Return the sub-elements of item or of the root if item is None :param item: Instance of sub-class of :py:class:`soco.data_structures.MusicServiceItem`. This object must have item_id, service_id and extended_id properties Note: Browsing a MSTrack item will return itself. Note: This plugin cannot yet set the parent ID of the results correctly when browsing :py:class:`soco.data_structures.MSFavorites` and :py:class:`soco.data_structures.MSCollection` elements. """ # Check for correct service if ms_item is not None and ms_item.service_id != self._service_id: message = 'This music service item is not for this service' raise ValueError(message) # Form HTTP body and set parent_id if ms_item: body = self._browse_body(ms_item.item_id) parent_id = ms_item.extended_id if parent_id is None: parent_id = '' else: body = self._browse_body('root') parent_id = '0' # Get HTTP header and post headers = _get_header('get_metadata') response = _post(self._url, headers, body, **self._http_vars) # Check for errors and get XML self._check_for_errors(response) result_dom = XML.fromstring(really_utf8(response.text)) # Find the getMetadataResult item ... xpath_search = './/' + _ns_tag('', 'getMetadataResult') metadata_result = list(result_dom.findall(xpath_search)) # ... and make sure there is exactly 1 if len(metadata_result) != 1: raise UnknownXMLStructure( 'The results XML has more than 1 \'getMetadataResult\'. This ' 'is unexpected and parsing will dis-continue.' ) metadata_result = metadata_result[0] # Browse the children of metadata result out = {'item_list': []} for element in ['index', 'count', 'total']: out[element] = metadata_result.findtext(_ns_tag('', element)) for result in metadata_result: if result.tag in [_ns_tag('', 'mediaCollection'), _ns_tag('', 'mediaMetadata')]: out['item_list'].append(get_ms_item(result, self, parent_id)) return out
python
def browse(self, ms_item=None): # Check for correct service if ms_item is not None and ms_item.service_id != self._service_id: message = 'This music service item is not for this service' raise ValueError(message) # Form HTTP body and set parent_id if ms_item: body = self._browse_body(ms_item.item_id) parent_id = ms_item.extended_id if parent_id is None: parent_id = '' else: body = self._browse_body('root') parent_id = '0' # Get HTTP header and post headers = _get_header('get_metadata') response = _post(self._url, headers, body, **self._http_vars) # Check for errors and get XML self._check_for_errors(response) result_dom = XML.fromstring(really_utf8(response.text)) # Find the getMetadataResult item ... xpath_search = './/' + _ns_tag('', 'getMetadataResult') metadata_result = list(result_dom.findall(xpath_search)) # ... and make sure there is exactly 1 if len(metadata_result) != 1: raise UnknownXMLStructure( 'The results XML has more than 1 \'getMetadataResult\'. This ' 'is unexpected and parsing will dis-continue.' ) metadata_result = metadata_result[0] # Browse the children of metadata result out = {'item_list': []} for element in ['index', 'count', 'total']: out[element] = metadata_result.findtext(_ns_tag('', element)) for result in metadata_result: if result.tag in [_ns_tag('', 'mediaCollection'), _ns_tag('', 'mediaMetadata')]: out['item_list'].append(get_ms_item(result, self, parent_id)) return out
[ "def", "browse", "(", "self", ",", "ms_item", "=", "None", ")", ":", "# Check for correct service", "if", "ms_item", "is", "not", "None", "and", "ms_item", ".", "service_id", "!=", "self", ".", "_service_id", ":", "message", "=", "'This music service item is not...
Return the sub-elements of item or of the root if item is None :param item: Instance of sub-class of :py:class:`soco.data_structures.MusicServiceItem`. This object must have item_id, service_id and extended_id properties Note: Browsing a MSTrack item will return itself. Note: This plugin cannot yet set the parent ID of the results correctly when browsing :py:class:`soco.data_structures.MSFavorites` and :py:class:`soco.data_structures.MSCollection` elements.
[ "Return", "the", "sub", "-", "elements", "of", "item", "or", "of", "the", "root", "if", "item", "is", "None" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L279-L337
233,664
SoCo/SoCo
soco/plugins/wimp.py
Wimp.id_to_extended_id
def id_to_extended_id(item_id, item_class): """Return the extended ID from an ID. :param item_id: The ID of the music library item :type item_id: str :param cls: The class of the music service item :type cls: Sub-class of :py:class:`soco.data_structures.MusicServiceItem` The extended id can be something like 00030020trackid_22757082 where the id is just trackid_22757082. For classes where the prefix is not known returns None. """ out = ID_PREFIX[item_class] if out: out += item_id return out
python
def id_to_extended_id(item_id, item_class): out = ID_PREFIX[item_class] if out: out += item_id return out
[ "def", "id_to_extended_id", "(", "item_id", ",", "item_class", ")", ":", "out", "=", "ID_PREFIX", "[", "item_class", "]", "if", "out", ":", "out", "+=", "item_id", "return", "out" ]
Return the extended ID from an ID. :param item_id: The ID of the music library item :type item_id: str :param cls: The class of the music service item :type cls: Sub-class of :py:class:`soco.data_structures.MusicServiceItem` The extended id can be something like 00030020trackid_22757082 where the id is just trackid_22757082. For classes where the prefix is not known returns None.
[ "Return", "the", "extended", "ID", "from", "an", "ID", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L340-L356
233,665
SoCo/SoCo
soco/plugins/wimp.py
Wimp.form_uri
def form_uri(item_content, item_class): """Form the URI for a music service element. :param item_content: The content dict of the item :type item_content: dict :param item_class: The class of the item :type item_class: Sub-class of :py:class:`soco.data_structures.MusicServiceItem` """ extension = None if 'mime_type' in item_content: extension = MIME_TYPE_TO_EXTENSION[item_content['mime_type']] out = URIS.get(item_class) if out: out = out.format(extension=extension, **item_content) return out
python
def form_uri(item_content, item_class): extension = None if 'mime_type' in item_content: extension = MIME_TYPE_TO_EXTENSION[item_content['mime_type']] out = URIS.get(item_class) if out: out = out.format(extension=extension, **item_content) return out
[ "def", "form_uri", "(", "item_content", ",", "item_class", ")", ":", "extension", "=", "None", "if", "'mime_type'", "in", "item_content", ":", "extension", "=", "MIME_TYPE_TO_EXTENSION", "[", "item_content", "[", "'mime_type'", "]", "]", "out", "=", "URIS", "....
Form the URI for a music service element. :param item_content: The content dict of the item :type item_content: dict :param item_class: The class of the item :type item_class: Sub-class of :py:class:`soco.data_structures.MusicServiceItem`
[ "Form", "the", "URI", "for", "a", "music", "service", "element", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L359-L374
233,666
SoCo/SoCo
soco/plugins/wimp.py
Wimp._search_body
def _search_body(self, search_type, search_term, start, max_items): """Return the search XML body. :param search_type: The search type :type search_type: str :param search_term: The search term e.g. 'Jon Bon Jovi' :type search_term: str :param start: The start index of the returned results :type start: int :param max_items: The maximum number of returned results :type max_items: int The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <search xmlns="http://www.sonos.com/Services/1.1"> <id>search_type</id> <term>search_term</term> <index>start</index> <count>max_items</count> </search> </s:Body> """ xml = self._base_body() # Add the Body part XML.SubElement(xml, 's:Body') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } search = XML.SubElement(xml[1], 'search', item_attrib) XML.SubElement(search, 'id').text = search_type XML.SubElement(search, 'term').text = search_term XML.SubElement(search, 'index').text = str(start) XML.SubElement(search, 'count').text = str(max_items) return XML.tostring(xml)
python
def _search_body(self, search_type, search_term, start, max_items): xml = self._base_body() # Add the Body part XML.SubElement(xml, 's:Body') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } search = XML.SubElement(xml[1], 'search', item_attrib) XML.SubElement(search, 'id').text = search_type XML.SubElement(search, 'term').text = search_term XML.SubElement(search, 'index').text = str(start) XML.SubElement(search, 'count').text = str(max_items) return XML.tostring(xml)
[ "def", "_search_body", "(", "self", ",", "search_type", ",", "search_term", ",", "start", ",", "max_items", ")", ":", "xml", "=", "self", ".", "_base_body", "(", ")", "# Add the Body part", "XML", ".", "SubElement", "(", "xml", ",", "'s:Body'", ")", "item_...
Return the search XML body. :param search_type: The search type :type search_type: str :param search_term: The search term e.g. 'Jon Bon Jovi' :type search_term: str :param start: The start index of the returned results :type start: int :param max_items: The maximum number of returned results :type max_items: int The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <search xmlns="http://www.sonos.com/Services/1.1"> <id>search_type</id> <term>search_term</term> <index>start</index> <count>max_items</count> </search> </s:Body>
[ "Return", "the", "search", "XML", "body", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L376-L415
233,667
SoCo/SoCo
soco/plugins/wimp.py
Wimp._browse_body
def _browse_body(self, search_id): """Return the browse XML body. The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <getMetadata xmlns="http://www.sonos.com/Services/1.1"> <id>root</id> <index>0</index> <count>100</count> </getMetadata> </s:Body> .. note:: The XML contains index and count, but the service does not seem to respect them, so therefore they have not been included as arguments. """ xml = self._base_body() # Add the Body part XML.SubElement(xml, 's:Body') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } search = XML.SubElement(xml[1], 'getMetadata', item_attrib) XML.SubElement(search, 'id').text = search_id # Investigate this index, count stuff more XML.SubElement(search, 'index').text = '0' XML.SubElement(search, 'count').text = '100' return XML.tostring(xml)
python
def _browse_body(self, search_id): xml = self._base_body() # Add the Body part XML.SubElement(xml, 's:Body') item_attrib = { 'xmlns': 'http://www.sonos.com/Services/1.1' } search = XML.SubElement(xml[1], 'getMetadata', item_attrib) XML.SubElement(search, 'id').text = search_id # Investigate this index, count stuff more XML.SubElement(search, 'index').text = '0' XML.SubElement(search, 'count').text = '100' return XML.tostring(xml)
[ "def", "_browse_body", "(", "self", ",", "search_id", ")", ":", "xml", "=", "self", ".", "_base_body", "(", ")", "# Add the Body part", "XML", ".", "SubElement", "(", "xml", ",", "'s:Body'", ")", "item_attrib", "=", "{", "'xmlns'", ":", "'http://www.sonos.co...
Return the browse XML body. The XML is formed by adding, to the envelope of the XML returned by ``self._base_body``, the following ``Body`` part: .. code :: xml <s:Body> <getMetadata xmlns="http://www.sonos.com/Services/1.1"> <id>root</id> <index>0</index> <count>100</count> </getMetadata> </s:Body> .. note:: The XML contains index and count, but the service does not seem to respect them, so therefore they have not been included as arguments.
[ "Return", "the", "browse", "XML", "body", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L417-L450
233,668
SoCo/SoCo
soco/plugins/wimp.py
Wimp._check_for_errors
def _check_for_errors(self, response): """Check a response for errors. :param response: the response from requests.post() """ if response.status_code != 200: xml_error = really_utf8(response.text) error_dom = XML.fromstring(xml_error) fault = error_dom.find('.//' + _ns_tag('s', 'Fault')) error_description = fault.find('faultstring').text error_code = EXCEPTION_STR_TO_CODE[error_description] message = 'UPnP Error {} received: {} from {}'.format( error_code, error_description, self._url) raise SoCoUPnPException( message=message, error_code=error_code, error_description=error_description, error_xml=really_utf8(response.text) )
python
def _check_for_errors(self, response): if response.status_code != 200: xml_error = really_utf8(response.text) error_dom = XML.fromstring(xml_error) fault = error_dom.find('.//' + _ns_tag('s', 'Fault')) error_description = fault.find('faultstring').text error_code = EXCEPTION_STR_TO_CODE[error_description] message = 'UPnP Error {} received: {} from {}'.format( error_code, error_description, self._url) raise SoCoUPnPException( message=message, error_code=error_code, error_description=error_description, error_xml=really_utf8(response.text) )
[ "def", "_check_for_errors", "(", "self", ",", "response", ")", ":", "if", "response", ".", "status_code", "!=", "200", ":", "xml_error", "=", "really_utf8", "(", "response", ".", "text", ")", "error_dom", "=", "XML", ".", "fromstring", "(", "xml_error", ")...
Check a response for errors. :param response: the response from requests.post()
[ "Check", "a", "response", "for", "errors", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L484-L502
233,669
SoCo/SoCo
soco/music_services/music_service.py
desc_from_uri
def desc_from_uri(uri): """Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'`` """ # # If there is an sn parameter (which is the serial number of an account), # we can obtain all the information we need from that, because we can find # the relevant service_id in the account database (it is the same as the # service_type). Consequently, the sid parameter is unneeded. But if sn is # missing, we need the sid (service_type) parameter to find a relevant # account # urlparse does not work consistently with custom URI schemes such as # those used by Sonos. This is especially broken in Python 2.6 and # early versions of 2.7: http://bugs.python.org/issue9374 # As a workaround, we split off the scheme manually, and then parse # the uri as if it were http if ":" in uri: _, uri = uri.split(":", 1) query_string = parse_qs(urlparse(uri, 'http').query) # Is there an account serial number? if query_string.get('sn'): account_serial_number = query_string['sn'][0] try: account = Account.get_accounts()[account_serial_number] desc = "SA_RINCON{}_{}".format( account.service_type, account.username) return desc except KeyError: # There is no account matching this serial number. Fall back to # using the service id to find an account pass if query_string.get('sid'): service_id = query_string['sid'][0] for service in MusicService._get_music_services_data().values(): if service_id == service["ServiceID"]: service_type = service["ServiceType"] account = Account.get_accounts_for_service(service_type) if not account: break # Use the first account we find account = account[0] desc = "SA_RINCON{}_{}".format( account.service_type, account.username) return desc # Nothing found. Default to the standard desc value. Is this the right # thing to do? desc = 'RINCON_AssociatedZPUDN' return desc
python
def desc_from_uri(uri): # # If there is an sn parameter (which is the serial number of an account), # we can obtain all the information we need from that, because we can find # the relevant service_id in the account database (it is the same as the # service_type). Consequently, the sid parameter is unneeded. But if sn is # missing, we need the sid (service_type) parameter to find a relevant # account # urlparse does not work consistently with custom URI schemes such as # those used by Sonos. This is especially broken in Python 2.6 and # early versions of 2.7: http://bugs.python.org/issue9374 # As a workaround, we split off the scheme manually, and then parse # the uri as if it were http if ":" in uri: _, uri = uri.split(":", 1) query_string = parse_qs(urlparse(uri, 'http').query) # Is there an account serial number? if query_string.get('sn'): account_serial_number = query_string['sn'][0] try: account = Account.get_accounts()[account_serial_number] desc = "SA_RINCON{}_{}".format( account.service_type, account.username) return desc except KeyError: # There is no account matching this serial number. Fall back to # using the service id to find an account pass if query_string.get('sid'): service_id = query_string['sid'][0] for service in MusicService._get_music_services_data().values(): if service_id == service["ServiceID"]: service_type = service["ServiceType"] account = Account.get_accounts_for_service(service_type) if not account: break # Use the first account we find account = account[0] desc = "SA_RINCON{}_{}".format( account.service_type, account.username) return desc # Nothing found. Default to the standard desc value. Is this the right # thing to do? desc = 'RINCON_AssociatedZPUDN' return desc
[ "def", "desc_from_uri", "(", "uri", ")", ":", "#", "# If there is an sn parameter (which is the serial number of an account),", "# we can obtain all the information we need from that, because we can find", "# the relevant service_id in the account database (it is the same as the", "# service_typ...
Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'``
[ "Create", "the", "content", "of", "DIDL", "desc", "element", "from", "a", "uri", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L824-L879
233,670
SoCo/SoCo
soco/music_services/music_service.py
MusicServiceSoapClient.get_soap_header
def get_soap_header(self): """Generate the SOAP authentication header for the related service. This header contains all the necessary authentication details. Returns: str: A string representation of the XML content of the SOAP header. """ # According to the SONOS SMAPI, this header must be sent with all # SOAP requests. Building this is an expensive operation (though # occasionally necessary), so f we have a cached value, return it if self._cached_soap_header is not None: return self._cached_soap_header music_service = self.music_service credentials_header = XML.Element( "credentials", {'xmlns': "http://www.sonos.com/Services/1.1"}) device_id = XML.SubElement(credentials_header, 'deviceId') device_id.text = self._device_id device_provider = XML.SubElement(credentials_header, 'deviceProvider') device_provider.text = 'Sonos' if music_service.account.oa_device_id: # OAuth account credentials are present. We must use them to # authenticate. login_token = XML.Element('loginToken') token = XML.SubElement(login_token, 'token') token.text = music_service.account.oa_device_id key = XML.SubElement(login_token, 'key') key.text = music_service.account.key household_id = XML.SubElement(login_token, 'householdId') household_id.text = self._device.household_id credentials_header.append(login_token) # otherwise, perhaps use DeviceLink or UserId auth elif music_service.auth_type in ['DeviceLink', 'UserId']: # We need a session ID from Sonos session_id = self._device.musicServices.GetSessionId([ ('ServiceId', music_service.service_id), ('Username', music_service.account.username) ])['SessionId'] session_elt = XML.Element('sessionId') session_elt.text = session_id credentials_header.append(session_elt) # Anonymous auth. No need for anything further. self._cached_soap_header = XML.tostring( credentials_header, encoding='utf-8').decode(encoding='utf-8') return self._cached_soap_header
python
def get_soap_header(self): # According to the SONOS SMAPI, this header must be sent with all # SOAP requests. Building this is an expensive operation (though # occasionally necessary), so f we have a cached value, return it if self._cached_soap_header is not None: return self._cached_soap_header music_service = self.music_service credentials_header = XML.Element( "credentials", {'xmlns': "http://www.sonos.com/Services/1.1"}) device_id = XML.SubElement(credentials_header, 'deviceId') device_id.text = self._device_id device_provider = XML.SubElement(credentials_header, 'deviceProvider') device_provider.text = 'Sonos' if music_service.account.oa_device_id: # OAuth account credentials are present. We must use them to # authenticate. login_token = XML.Element('loginToken') token = XML.SubElement(login_token, 'token') token.text = music_service.account.oa_device_id key = XML.SubElement(login_token, 'key') key.text = music_service.account.key household_id = XML.SubElement(login_token, 'householdId') household_id.text = self._device.household_id credentials_header.append(login_token) # otherwise, perhaps use DeviceLink or UserId auth elif music_service.auth_type in ['DeviceLink', 'UserId']: # We need a session ID from Sonos session_id = self._device.musicServices.GetSessionId([ ('ServiceId', music_service.service_id), ('Username', music_service.account.username) ])['SessionId'] session_elt = XML.Element('sessionId') session_elt.text = session_id credentials_header.append(session_elt) # Anonymous auth. No need for anything further. self._cached_soap_header = XML.tostring( credentials_header, encoding='utf-8').decode(encoding='utf-8') return self._cached_soap_header
[ "def", "get_soap_header", "(", "self", ")", ":", "# According to the SONOS SMAPI, this header must be sent with all", "# SOAP requests. Building this is an expensive operation (though", "# occasionally necessary), so f we have a cached value, return it", "if", "self", ".", "_cached_soap_head...
Generate the SOAP authentication header for the related service. This header contains all the necessary authentication details. Returns: str: A string representation of the XML content of the SOAP header.
[ "Generate", "the", "SOAP", "authentication", "header", "for", "the", "related", "service", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L76-L125
233,671
SoCo/SoCo
soco/music_services/music_service.py
MusicServiceSoapClient.call
def call(self, method, args=None): """Call a method on the server. Args: method (str): The name of the method to call. args (List[Tuple[str, str]] or None): A list of (parameter, value) pairs representing the parameters of the method. Defaults to `None`. Returns: ~collections.OrderedDict: An OrderedDict representing the response. Raises: `MusicServiceException`: containing details of the error returned by the music service. """ message = SoapMessage( endpoint=self.endpoint, method=method, parameters=[] if args is None else args, http_headers=self.http_headers, soap_action="http://www.sonos.com/Services/1" ".1#{0}".format(method), soap_header=self.get_soap_header(), namespace=self.namespace, timeout=self.timeout) try: result_elt = message.call() except SoapFault as exc: if 'Client.TokenRefreshRequired' in exc.faultcode: log.debug('Token refresh required. Trying again') # Remove any cached value for the SOAP header self._cached_soap_header = None # <detail> # <refreshAuthTokenResult> # <authToken>xxxxxxx</authToken> # <privateKey>zzzzzz</privateKey> # </refreshAuthTokenResult> # </detail> auth_token = exc.detail.findtext('.//authToken') private_key = exc.detail.findtext('.//privateKey') # We have new details - update the account self.music_service.account.oa_device_id = auth_token self.music_service.account.key = private_key message = SoapMessage( endpoint=self.endpoint, method=method, parameters=args, http_headers=self.http_headers, soap_action="http://www.sonos.com/Services/1" ".1#{0}".format(method), soap_header=self.get_soap_header(), namespace=self.namespace, timeout=self.timeout) result_elt = message.call() else: raise MusicServiceException(exc.faultstring, exc.faultcode) # The top key in the OrderedDict will be the methodResult. Its # value may be None if no results were returned. result = list(parse( XML.tostring(result_elt), process_namespaces=True, namespaces={'http://www.sonos.com/Services/1.1': None} ).values())[0] return result if result is not None else {}
python
def call(self, method, args=None): message = SoapMessage( endpoint=self.endpoint, method=method, parameters=[] if args is None else args, http_headers=self.http_headers, soap_action="http://www.sonos.com/Services/1" ".1#{0}".format(method), soap_header=self.get_soap_header(), namespace=self.namespace, timeout=self.timeout) try: result_elt = message.call() except SoapFault as exc: if 'Client.TokenRefreshRequired' in exc.faultcode: log.debug('Token refresh required. Trying again') # Remove any cached value for the SOAP header self._cached_soap_header = None # <detail> # <refreshAuthTokenResult> # <authToken>xxxxxxx</authToken> # <privateKey>zzzzzz</privateKey> # </refreshAuthTokenResult> # </detail> auth_token = exc.detail.findtext('.//authToken') private_key = exc.detail.findtext('.//privateKey') # We have new details - update the account self.music_service.account.oa_device_id = auth_token self.music_service.account.key = private_key message = SoapMessage( endpoint=self.endpoint, method=method, parameters=args, http_headers=self.http_headers, soap_action="http://www.sonos.com/Services/1" ".1#{0}".format(method), soap_header=self.get_soap_header(), namespace=self.namespace, timeout=self.timeout) result_elt = message.call() else: raise MusicServiceException(exc.faultstring, exc.faultcode) # The top key in the OrderedDict will be the methodResult. Its # value may be None if no results were returned. result = list(parse( XML.tostring(result_elt), process_namespaces=True, namespaces={'http://www.sonos.com/Services/1.1': None} ).values())[0] return result if result is not None else {}
[ "def", "call", "(", "self", ",", "method", ",", "args", "=", "None", ")", ":", "message", "=", "SoapMessage", "(", "endpoint", "=", "self", ".", "endpoint", ",", "method", "=", "method", ",", "parameters", "=", "[", "]", "if", "args", "is", "None", ...
Call a method on the server. Args: method (str): The name of the method to call. args (List[Tuple[str, str]] or None): A list of (parameter, value) pairs representing the parameters of the method. Defaults to `None`. Returns: ~collections.OrderedDict: An OrderedDict representing the response. Raises: `MusicServiceException`: containing details of the error returned by the music service.
[ "Call", "a", "method", "on", "the", "server", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L127-L195
233,672
SoCo/SoCo
soco/music_services/music_service.py
MusicService._get_music_services_data_xml
def _get_music_services_data_xml(soco=None): """Fetch the music services data xml from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If none is specified, a random device will be used. Defaults to `None`. Returns: str: a string containing the music services data xml """ device = soco or discovery.any_soco() log.debug("Fetching music services data from %s", device) available_services = device.musicServices.ListAvailableServices() descriptor_list_xml = available_services[ 'AvailableServiceDescriptorList'] log.debug("Services descriptor list: %s", descriptor_list_xml) return descriptor_list_xml
python
def _get_music_services_data_xml(soco=None): device = soco or discovery.any_soco() log.debug("Fetching music services data from %s", device) available_services = device.musicServices.ListAvailableServices() descriptor_list_xml = available_services[ 'AvailableServiceDescriptorList'] log.debug("Services descriptor list: %s", descriptor_list_xml) return descriptor_list_xml
[ "def", "_get_music_services_data_xml", "(", "soco", "=", "None", ")", ":", "device", "=", "soco", "or", "discovery", ".", "any_soco", "(", ")", "log", ".", "debug", "(", "\"Fetching music services data from %s\"", ",", "device", ")", "available_services", "=", "...
Fetch the music services data xml from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If none is specified, a random device will be used. Defaults to `None`. Returns: str: a string containing the music services data xml
[ "Fetch", "the", "music", "services", "data", "xml", "from", "a", "Sonos", "device", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L371-L387
233,673
SoCo/SoCo
soco/music_services/music_service.py
MusicService._get_music_services_data
def _get_music_services_data(cls): """Parse raw account data xml into a useful python datastructure. Returns: dict: Each key is a service_type, and each value is a `dict` containing relevant data. """ # Return from cache if we have it. if cls._music_services_data is not None: return cls._music_services_data result = {} root = XML.fromstring( cls._get_music_services_data_xml().encode('utf-8') ) # <Services SchemaVersion="1"> # <Service Id="163" Name="Spreaker" Version="1.1" # Uri="http://sonos.spreaker.com/sonos/service/v1" # SecureUri="https://sonos.spreaker.com/sonos/service/v1" # ContainerType="MService" # Capabilities="513" # MaxMessagingChars="0"> # <Policy Auth="Anonymous" PollInterval="30" /> # <Presentation> # <Strings # Version="1" # Uri="https:...string_table.xml" /> # <PresentationMap Version="2" # Uri="https://...presentation_map.xml" /> # </Presentation> # </Service> # ... # </ Services> # Ideally, the search path should be './/Service' to find Service # elements at any level, but Python 2.6 breaks with this if Service # is a child of the current element. Since 'Service' works here, we use # that instead services = root.findall('Service') for service in services: result_value = service.attrib.copy() name = service.get('Name') result_value['Name'] = name auth_element = (service.find('Policy')) auth = auth_element.attrib result_value.update(auth) presentation_element = (service.find('.//PresentationMap')) if presentation_element is not None: result_value['PresentationMapUri'] = \ presentation_element.get('Uri') result_value['ServiceID'] = service.get('Id') # ServiceType is used elsewhere in Sonos, eg to form tokens, # and get_subscribed_music_services() below. It is also the # 'Type' used in account_xml (see above). Its value always # seems to be (ID*256) + 7. Some serviceTypes are also # listed in available_services['AvailableServiceTypeList'] # but this does not seem to be comprehensive service_type = str(int(service.get('Id')) * 256 + 7) result_value['ServiceType'] = service_type result[service_type] = result_value # Cache this so we don't need to do it again. cls._music_services_data = result return result
python
def _get_music_services_data(cls): # Return from cache if we have it. if cls._music_services_data is not None: return cls._music_services_data result = {} root = XML.fromstring( cls._get_music_services_data_xml().encode('utf-8') ) # <Services SchemaVersion="1"> # <Service Id="163" Name="Spreaker" Version="1.1" # Uri="http://sonos.spreaker.com/sonos/service/v1" # SecureUri="https://sonos.spreaker.com/sonos/service/v1" # ContainerType="MService" # Capabilities="513" # MaxMessagingChars="0"> # <Policy Auth="Anonymous" PollInterval="30" /> # <Presentation> # <Strings # Version="1" # Uri="https:...string_table.xml" /> # <PresentationMap Version="2" # Uri="https://...presentation_map.xml" /> # </Presentation> # </Service> # ... # </ Services> # Ideally, the search path should be './/Service' to find Service # elements at any level, but Python 2.6 breaks with this if Service # is a child of the current element. Since 'Service' works here, we use # that instead services = root.findall('Service') for service in services: result_value = service.attrib.copy() name = service.get('Name') result_value['Name'] = name auth_element = (service.find('Policy')) auth = auth_element.attrib result_value.update(auth) presentation_element = (service.find('.//PresentationMap')) if presentation_element is not None: result_value['PresentationMapUri'] = \ presentation_element.get('Uri') result_value['ServiceID'] = service.get('Id') # ServiceType is used elsewhere in Sonos, eg to form tokens, # and get_subscribed_music_services() below. It is also the # 'Type' used in account_xml (see above). Its value always # seems to be (ID*256) + 7. Some serviceTypes are also # listed in available_services['AvailableServiceTypeList'] # but this does not seem to be comprehensive service_type = str(int(service.get('Id')) * 256 + 7) result_value['ServiceType'] = service_type result[service_type] = result_value # Cache this so we don't need to do it again. cls._music_services_data = result return result
[ "def", "_get_music_services_data", "(", "cls", ")", ":", "# Return from cache if we have it.", "if", "cls", ".", "_music_services_data", "is", "not", "None", ":", "return", "cls", ".", "_music_services_data", "result", "=", "{", "}", "root", "=", "XML", ".", "fr...
Parse raw account data xml into a useful python datastructure. Returns: dict: Each key is a service_type, and each value is a `dict` containing relevant data.
[ "Parse", "raw", "account", "data", "xml", "into", "a", "useful", "python", "datastructure", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L390-L452
233,674
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_subscribed_services_names
def get_subscribed_services_names(cls): """Get a list of the names of all subscribed music services. Returns: list: A list of strings. """ # This is very inefficient - loops within loops within loops, and # many network requests # Optimise it? accounts_for_service = Account.get_accounts_for_service service_data = cls._get_music_services_data().values() return [ service['Name'] for service in service_data if len( accounts_for_service(service['ServiceType']) ) > 0 ]
python
def get_subscribed_services_names(cls): # This is very inefficient - loops within loops within loops, and # many network requests # Optimise it? accounts_for_service = Account.get_accounts_for_service service_data = cls._get_music_services_data().values() return [ service['Name'] for service in service_data if len( accounts_for_service(service['ServiceType']) ) > 0 ]
[ "def", "get_subscribed_services_names", "(", "cls", ")", ":", "# This is very inefficient - loops within loops within loops, and", "# many network requests", "# Optimise it?", "accounts_for_service", "=", "Account", ".", "get_accounts_for_service", "service_data", "=", "cls", ".", ...
Get a list of the names of all subscribed music services. Returns: list: A list of strings.
[ "Get", "a", "list", "of", "the", "names", "of", "all", "subscribed", "music", "services", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L469-L485
233,675
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_data_for_name
def get_data_for_name(cls, service_name): """Get the data relating to a named music service. Args: service_name (str): The name of the music service for which data is required. Returns: dict: Data relating to the music service. Raises: `MusicServiceException`: if the music service cannot be found. """ for service in cls._get_music_services_data().values(): if service_name == service["Name"]: return service raise MusicServiceException( "Unknown music service: '%s'" % service_name)
python
def get_data_for_name(cls, service_name): for service in cls._get_music_services_data().values(): if service_name == service["Name"]: return service raise MusicServiceException( "Unknown music service: '%s'" % service_name)
[ "def", "get_data_for_name", "(", "cls", ",", "service_name", ")", ":", "for", "service", "in", "cls", ".", "_get_music_services_data", "(", ")", ".", "values", "(", ")", ":", "if", "service_name", "==", "service", "[", "\"Name\"", "]", ":", "return", "serv...
Get the data relating to a named music service. Args: service_name (str): The name of the music service for which data is required. Returns: dict: Data relating to the music service. Raises: `MusicServiceException`: if the music service cannot be found.
[ "Get", "the", "data", "relating", "to", "a", "named", "music", "service", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L488-L505
233,676
SoCo/SoCo
soco/music_services/music_service.py
MusicService._get_search_prefix_map
def _get_search_prefix_map(self): """Fetch and parse the service search category mapping. Standard Sonos search categories are 'all', 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service """ # TuneIn does not have a pmap. Its search keys are is search:station, # search:show, search:host # Presentation maps can also define custom categories. See eg # http://sonos-pmap.ws.sonos.com/hypemachine_pmap.6.xml # <SearchCategories> # ... # <CustomCategory mappedId="SBLG" stringId="Blogs"/> # </SearchCategories> # Is it already cached? If so, return it if self._search_prefix_map is not None: return self._search_prefix_map # Not cached. Fetch and parse presentation map self._search_prefix_map = {} # Tunein is a special case. It has no pmap, but supports searching if self.service_name == "TuneIn": self._search_prefix_map = { 'stations': 'search:station', 'shows': 'search:show', 'hosts': 'search:host', } return self._search_prefix_map if self.presentation_map_uri is None: # Assume not searchable? return self._search_prefix_map log.info('Fetching presentation map from %s', self.presentation_map_uri) pmap = requests.get(self.presentation_map_uri, timeout=9) pmap_root = XML.fromstring(pmap.content) # Search translations can appear in Category or CustomCategory elements categories = pmap_root.findall(".//SearchCategories/Category") if categories is None: return self._search_prefix_map for cat in categories: self._search_prefix_map[cat.get('id')] = cat.get('mappedId') custom_categories = pmap_root.findall( ".//SearchCategories/CustomCategory") for cat in custom_categories: self._search_prefix_map[cat.get('stringId')] = cat.get('mappedId') return self._search_prefix_map
python
def _get_search_prefix_map(self): # TuneIn does not have a pmap. Its search keys are is search:station, # search:show, search:host # Presentation maps can also define custom categories. See eg # http://sonos-pmap.ws.sonos.com/hypemachine_pmap.6.xml # <SearchCategories> # ... # <CustomCategory mappedId="SBLG" stringId="Blogs"/> # </SearchCategories> # Is it already cached? If so, return it if self._search_prefix_map is not None: return self._search_prefix_map # Not cached. Fetch and parse presentation map self._search_prefix_map = {} # Tunein is a special case. It has no pmap, but supports searching if self.service_name == "TuneIn": self._search_prefix_map = { 'stations': 'search:station', 'shows': 'search:show', 'hosts': 'search:host', } return self._search_prefix_map if self.presentation_map_uri is None: # Assume not searchable? return self._search_prefix_map log.info('Fetching presentation map from %s', self.presentation_map_uri) pmap = requests.get(self.presentation_map_uri, timeout=9) pmap_root = XML.fromstring(pmap.content) # Search translations can appear in Category or CustomCategory elements categories = pmap_root.findall(".//SearchCategories/Category") if categories is None: return self._search_prefix_map for cat in categories: self._search_prefix_map[cat.get('id')] = cat.get('mappedId') custom_categories = pmap_root.findall( ".//SearchCategories/CustomCategory") for cat in custom_categories: self._search_prefix_map[cat.get('stringId')] = cat.get('mappedId') return self._search_prefix_map
[ "def", "_get_search_prefix_map", "(", "self", ")", ":", "# TuneIn does not have a pmap. Its search keys are is search:station,", "# search:show, search:host", "# Presentation maps can also define custom categories. See eg", "# http://sonos-pmap.ws.sonos.com/hypemachine_pmap.6.xml", "# <SearchCat...
Fetch and parse the service search category mapping. Standard Sonos search categories are 'all', 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service
[ "Fetch", "and", "parse", "the", "service", "search", "category", "mapping", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L507-L553
233,677
SoCo/SoCo
soco/music_services/music_service.py
MusicService.sonos_uri_from_id
def sonos_uri_from_id(self, item_id): """Get a uri which can be sent for playing. Args: item_id (str): The unique id of a playable item for this music service, such as that returned in the metadata from `get_metadata`, eg ``spotify:track:2qs5ZcLByNTctJKbhAZ9JE`` Returns: str: A URI of the form: ``soco://spotify%3Atrack %3A2qs5ZcLByNTctJKbhAZ9JE?sid=2311&sn=1`` which encodes the ``item_id``, and relevant data from the account for the music service. This URI can be sent to a Sonos device for playing, and the device itself will retrieve all the necessary metadata such as title, album etc. """ # Real Sonos URIs look like this: # x-sonos-http:tr%3a92352286.mp3?sid=2&flags=8224&sn=4 The # extension (.mp3) presumably comes from the mime-type returned in a # MusicService.get_metadata() result (though for Spotify the mime-type # is audio/x-spotify, and there is no extension. See # http://musicpartners.sonos.com/node/464 for supported mime-types and # related extensions). The scheme (x-sonos-http) presumably # indicates how the player is to obtain the stream for playing. It # is not clear what the flags param is used for (perhaps bitrate, # or certain metadata such as canSkip?). Fortunately, none of these # seems to be necessary. We can leave them out, (or in the case of # the scheme, use 'soco' as dummy text, and the players still seem # to do the right thing. # quote_url will break if given unicode on Py2.6, and early 2.7. So # we need to encode. item_id = quote_url(item_id.encode('utf-8')) # Add the account info to the end as query params account = self.account result = "soco://{}?sid={}&sn={}".format( item_id, self.service_id, account.serial_number ) return result
python
def sonos_uri_from_id(self, item_id): # Real Sonos URIs look like this: # x-sonos-http:tr%3a92352286.mp3?sid=2&flags=8224&sn=4 The # extension (.mp3) presumably comes from the mime-type returned in a # MusicService.get_metadata() result (though for Spotify the mime-type # is audio/x-spotify, and there is no extension. See # http://musicpartners.sonos.com/node/464 for supported mime-types and # related extensions). The scheme (x-sonos-http) presumably # indicates how the player is to obtain the stream for playing. It # is not clear what the flags param is used for (perhaps bitrate, # or certain metadata such as canSkip?). Fortunately, none of these # seems to be necessary. We can leave them out, (or in the case of # the scheme, use 'soco' as dummy text, and the players still seem # to do the right thing. # quote_url will break if given unicode on Py2.6, and early 2.7. So # we need to encode. item_id = quote_url(item_id.encode('utf-8')) # Add the account info to the end as query params account = self.account result = "soco://{}?sid={}&sn={}".format( item_id, self.service_id, account.serial_number ) return result
[ "def", "sonos_uri_from_id", "(", "self", ",", "item_id", ")", ":", "# Real Sonos URIs look like this:", "# x-sonos-http:tr%3a92352286.mp3?sid=2&flags=8224&sn=4 The", "# extension (.mp3) presumably comes from the mime-type returned in a", "# MusicService.get_metadata() result (though for Spotif...
Get a uri which can be sent for playing. Args: item_id (str): The unique id of a playable item for this music service, such as that returned in the metadata from `get_metadata`, eg ``spotify:track:2qs5ZcLByNTctJKbhAZ9JE`` Returns: str: A URI of the form: ``soco://spotify%3Atrack %3A2qs5ZcLByNTctJKbhAZ9JE?sid=2311&sn=1`` which encodes the ``item_id``, and relevant data from the account for the music service. This URI can be sent to a Sonos device for playing, and the device itself will retrieve all the necessary metadata such as title, album etc.
[ "Get", "a", "uri", "which", "can", "be", "sent", "for", "playing", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L577-L616
233,678
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_metadata
def get_metadata( self, item='root', index=0, count=100, recursive=False): """Get metadata for a container or item. Args: item (str or MusicServiceItem): The container or item to browse given either as a MusicServiceItem instance or as a str. Defaults to the root item. index (int): The starting index. Default 0. count (int): The maximum number of items to return. Default 100. recursive (bool): Whether the browse should recurse into sub-items (Does not always work). Defaults to `False`. Returns: ~collections.OrderedDict: The item or container's metadata, or `None`. See also: The Sonos `getMetadata API <http://musicpartners.sonos.com/node/83>`_. """ if isinstance(item, MusicServiceItem): item_id = item.id # pylint: disable=no-member else: item_id = item response = self.soap_client.call( 'getMetadata', [ ('id', item_id), ('index', index), ('count', count), ('recursive', 1 if recursive else 0)] ) return parse_response(self, response, 'browse')
python
def get_metadata( self, item='root', index=0, count=100, recursive=False): if isinstance(item, MusicServiceItem): item_id = item.id # pylint: disable=no-member else: item_id = item response = self.soap_client.call( 'getMetadata', [ ('id', item_id), ('index', index), ('count', count), ('recursive', 1 if recursive else 0)] ) return parse_response(self, response, 'browse')
[ "def", "get_metadata", "(", "self", ",", "item", "=", "'root'", ",", "index", "=", "0", ",", "count", "=", "100", ",", "recursive", "=", "False", ")", ":", "if", "isinstance", "(", "item", ",", "MusicServiceItem", ")", ":", "item_id", "=", "item", "....
Get metadata for a container or item. Args: item (str or MusicServiceItem): The container or item to browse given either as a MusicServiceItem instance or as a str. Defaults to the root item. index (int): The starting index. Default 0. count (int): The maximum number of items to return. Default 100. recursive (bool): Whether the browse should recurse into sub-items (Does not always work). Defaults to `False`. Returns: ~collections.OrderedDict: The item or container's metadata, or `None`. See also: The Sonos `getMetadata API <http://musicpartners.sonos.com/node/83>`_.
[ "Get", "metadata", "for", "a", "container", "or", "item", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L661-L693
233,679
SoCo/SoCo
soco/music_services/music_service.py
MusicService.search
def search(self, category, term='', index=0, count=100): """Search for an item in a category. Args: category (str): The search category to use. Standard Sonos search categories are 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service. Call available_search_categories for a list for this service. term (str): The term to search for. index (int): The starting index. Default 0. count (int): The maximum number of items to return. Default 100. Returns: ~collections.OrderedDict: The search results, or `None`. See also: The Sonos `search API <http://musicpartners.sonos.com/node/86>`_ """ search_category = self._get_search_prefix_map().get(category, None) if search_category is None: raise MusicServiceException( "%s does not support the '%s' search category" % ( self.service_name, category)) response = self.soap_client.call( 'search', [ ('id', search_category), ('term', term), ('index', index), ('count', count)]) return parse_response(self, response, category)
python
def search(self, category, term='', index=0, count=100): search_category = self._get_search_prefix_map().get(category, None) if search_category is None: raise MusicServiceException( "%s does not support the '%s' search category" % ( self.service_name, category)) response = self.soap_client.call( 'search', [ ('id', search_category), ('term', term), ('index', index), ('count', count)]) return parse_response(self, response, category)
[ "def", "search", "(", "self", ",", "category", ",", "term", "=", "''", ",", "index", "=", "0", ",", "count", "=", "100", ")", ":", "search_category", "=", "self", ".", "_get_search_prefix_map", "(", ")", ".", "get", "(", "category", ",", "None", ")",...
Search for an item in a category. Args: category (str): The search category to use. Standard Sonos search categories are 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service. Call available_search_categories for a list for this service. term (str): The term to search for. index (int): The starting index. Default 0. count (int): The maximum number of items to return. Default 100. Returns: ~collections.OrderedDict: The search results, or `None`. See also: The Sonos `search API <http://musicpartners.sonos.com/node/86>`_
[ "Search", "for", "an", "item", "in", "a", "category", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L695-L726
233,680
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_media_metadata
def get_media_metadata(self, item_id): """Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMediaMetadata API <http://musicpartners.sonos.com/node/83>`_ """ response = self.soap_client.call( 'getMediaMetadata', [('id', item_id)]) return response.get('getMediaMetadataResult', None)
python
def get_media_metadata(self, item_id): response = self.soap_client.call( 'getMediaMetadata', [('id', item_id)]) return response.get('getMediaMetadataResult', None)
[ "def", "get_media_metadata", "(", "self", ",", "item_id", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getMediaMetadata'", ",", "[", "(", "'id'", ",", "item_id", ")", "]", ")", "return", "response", ".", "get", "(", "'getMed...
Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMediaMetadata API <http://musicpartners.sonos.com/node/83>`_
[ "Get", "metadata", "for", "a", "media", "item", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L728-L744
233,681
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_media_uri
def get_media_uri(self, item_id): """Get a streaming URI for an item. Note: You should not need to use this directly. It is used by the Sonos players (not the controllers) to obtain the uri of the media stream. If you want to have a player play a media item, you should add add it to the queue using its id and let the player work out where to get the stream from (see `On Demand Playback <http://musicpartners.sonos.com/node/421>`_ and `Programmed Radio <http://musicpartners.sonos.com/node/422>`_) Args: item_id (str): The item for which the URI is required Returns: str: The item's streaming URI. """ response = self.soap_client.call( 'getMediaURI', [('id', item_id)]) return response.get('getMediaURIResult', None)
python
def get_media_uri(self, item_id): response = self.soap_client.call( 'getMediaURI', [('id', item_id)]) return response.get('getMediaURIResult', None)
[ "def", "get_media_uri", "(", "self", ",", "item_id", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getMediaURI'", ",", "[", "(", "'id'", ",", "item_id", ")", "]", ")", "return", "response", ".", "get", "(", "'getMediaURIResul...
Get a streaming URI for an item. Note: You should not need to use this directly. It is used by the Sonos players (not the controllers) to obtain the uri of the media stream. If you want to have a player play a media item, you should add add it to the queue using its id and let the player work out where to get the stream from (see `On Demand Playback <http://musicpartners.sonos.com/node/421>`_ and `Programmed Radio <http://musicpartners.sonos.com/node/422>`_) Args: item_id (str): The item for which the URI is required Returns: str: The item's streaming URI.
[ "Get", "a", "streaming", "URI", "for", "an", "item", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L746-L767
233,682
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_extended_metadata
def get_extended_metadata(self, item_id): """Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <http://musicpartners.sonos.com/node/128>`_ """ response = self.soap_client.call( 'getExtendedMetadata', [('id', item_id)]) return response.get('getExtendedMetadataResult', None)
python
def get_extended_metadata(self, item_id): response = self.soap_client.call( 'getExtendedMetadata', [('id', item_id)]) return response.get('getExtendedMetadataResult', None)
[ "def", "get_extended_metadata", "(", "self", ",", "item_id", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getExtendedMetadata'", ",", "[", "(", "'id'", ",", "item_id", ")", "]", ")", "return", "response", ".", "get", "(", "'...
Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <http://musicpartners.sonos.com/node/128>`_
[ "Get", "extended", "metadata", "for", "a", "media", "item", "such", "as", "related", "items", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L783-L799
233,683
SoCo/SoCo
soco/music_services/music_service.py
MusicService.get_extended_metadata_text
def get_extended_metadata_text(self, item_id, metadata_type): """Get extended metadata text for a media item. Args: item_id (str): The item for which metadata is required metadata_type (str): The type of text to return, eg ``'ARTIST_BIO'``, or ``'ALBUM_NOTES'``. Calling `get_extended_metadata` for the item will show which extended metadata_types are available (under relatedBrowse and relatedText). Returns: str: The item's extended metadata text or None See also: The Sonos `getExtendedMetadataText API <http://musicpartners.sonos.com/node/127>`_ """ response = self.soap_client.call( 'getExtendedMetadataText', [('id', item_id), ('type', metadata_type)]) return response.get('getExtendedMetadataTextResult', None)
python
def get_extended_metadata_text(self, item_id, metadata_type): response = self.soap_client.call( 'getExtendedMetadataText', [('id', item_id), ('type', metadata_type)]) return response.get('getExtendedMetadataTextResult', None)
[ "def", "get_extended_metadata_text", "(", "self", ",", "item_id", ",", "metadata_type", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getExtendedMetadataText'", ",", "[", "(", "'id'", ",", "item_id", ")", ",", "(", "'type'", ",",...
Get extended metadata text for a media item. Args: item_id (str): The item for which metadata is required metadata_type (str): The type of text to return, eg ``'ARTIST_BIO'``, or ``'ALBUM_NOTES'``. Calling `get_extended_metadata` for the item will show which extended metadata_types are available (under relatedBrowse and relatedText). Returns: str: The item's extended metadata text or None See also: The Sonos `getExtendedMetadataText API <http://musicpartners.sonos.com/node/127>`_
[ "Get", "extended", "metadata", "text", "for", "a", "media", "item", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L801-L821
233,684
SoCo/SoCo
soco/music_services/data_structures.py
get_class
def get_class(class_key): """Form a music service data structure class from the class key Args: class_key (str): A concatenation of the base class (e.g. MediaMetadata) and the class name Returns: class: Subclass of MusicServiceItem """ if class_key not in CLASSES: for basecls in (MediaMetadata, MediaCollection): if class_key.startswith(basecls.__name__): # So MediaMetadataTrack turns into MSTrack class_name = 'MS' + class_key.replace(basecls.__name__, '') if sys.version_info[0] == 2: class_name = class_name.encode('ascii') CLASSES[class_key] = type(class_name, (basecls,), {}) _LOG.info('Class %s created', CLASSES[class_key]) return CLASSES[class_key]
python
def get_class(class_key): if class_key not in CLASSES: for basecls in (MediaMetadata, MediaCollection): if class_key.startswith(basecls.__name__): # So MediaMetadataTrack turns into MSTrack class_name = 'MS' + class_key.replace(basecls.__name__, '') if sys.version_info[0] == 2: class_name = class_name.encode('ascii') CLASSES[class_key] = type(class_name, (basecls,), {}) _LOG.info('Class %s created', CLASSES[class_key]) return CLASSES[class_key]
[ "def", "get_class", "(", "class_key", ")", ":", "if", "class_key", "not", "in", "CLASSES", ":", "for", "basecls", "in", "(", "MediaMetadata", ",", "MediaCollection", ")", ":", "if", "class_key", ".", "startswith", "(", "basecls", ".", "__name__", ")", ":",...
Form a music service data structure class from the class key Args: class_key (str): A concatenation of the base class (e.g. MediaMetadata) and the class name Returns: class: Subclass of MusicServiceItem
[ "Form", "a", "music", "service", "data", "structure", "class", "from", "the", "class", "key" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L80-L99
233,685
SoCo/SoCo
soco/music_services/data_structures.py
parse_response
def parse_response(service, response, search_type): """Parse the response to a music service query and return a SearchResult Args: service (MusicService): The music service that produced the response response (OrderedDict): The response from the soap client call search_type (str): A string that indicates the search type that the response is from Returns: SearchResult: A SearchResult object """ _LOG.debug('Parse response "%s" from service "%s" of type "%s"', response, service, search_type) items = [] # The result to be parsed is in either searchResult or getMetadataResult if 'searchResult' in response: response = response['searchResult'] elif 'getMetadataResult' in response: response = response['getMetadataResult'] else: raise ValueError('"response" should contain either the key ' '"searchResult" or "getMetadataResult"') # Form the search metadata search_metadata = { 'number_returned': response['count'], 'total_matches': None, 'search_type': search_type, 'update_id': None, } for result_type in ('mediaCollection', 'mediaMetadata'): # Upper case the first letter (used for the class_key) result_type_proper = result_type[0].upper() + result_type[1:] raw_items = response.get(result_type, []) # If there is only 1 result, it is not put in an array if isinstance(raw_items, OrderedDict): raw_items = [raw_items] for raw_item in raw_items: # Form the class_key, which is a unique string for this type, # formed by concatenating the result type with the item type. Turns # into e.g: MediaMetadataTrack class_key = result_type_proper + raw_item['itemType'].title() cls = get_class(class_key) items.append(cls.from_music_service(service, raw_item)) return SearchResult(items, **search_metadata)
python
def parse_response(service, response, search_type): _LOG.debug('Parse response "%s" from service "%s" of type "%s"', response, service, search_type) items = [] # The result to be parsed is in either searchResult or getMetadataResult if 'searchResult' in response: response = response['searchResult'] elif 'getMetadataResult' in response: response = response['getMetadataResult'] else: raise ValueError('"response" should contain either the key ' '"searchResult" or "getMetadataResult"') # Form the search metadata search_metadata = { 'number_returned': response['count'], 'total_matches': None, 'search_type': search_type, 'update_id': None, } for result_type in ('mediaCollection', 'mediaMetadata'): # Upper case the first letter (used for the class_key) result_type_proper = result_type[0].upper() + result_type[1:] raw_items = response.get(result_type, []) # If there is only 1 result, it is not put in an array if isinstance(raw_items, OrderedDict): raw_items = [raw_items] for raw_item in raw_items: # Form the class_key, which is a unique string for this type, # formed by concatenating the result type with the item type. Turns # into e.g: MediaMetadataTrack class_key = result_type_proper + raw_item['itemType'].title() cls = get_class(class_key) items.append(cls.from_music_service(service, raw_item)) return SearchResult(items, **search_metadata)
[ "def", "parse_response", "(", "service", ",", "response", ",", "search_type", ")", ":", "_LOG", ".", "debug", "(", "'Parse response \"%s\" from service \"%s\" of type \"%s\"'", ",", "response", ",", "service", ",", "search_type", ")", "items", "=", "[", "]", "# Th...
Parse the response to a music service query and return a SearchResult Args: service (MusicService): The music service that produced the response response (OrderedDict): The response from the soap client call search_type (str): A string that indicates the search type that the response is from Returns: SearchResult: A SearchResult object
[ "Parse", "the", "response", "to", "a", "music", "service", "query", "and", "return", "a", "SearchResult" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L102-L149
233,686
SoCo/SoCo
soco/music_services/data_structures.py
form_uri
def form_uri(item_id, service, is_track): """Form and return a music service item uri Args: item_id (str): The item id service (MusicService): The music service that the item originates from is_track (bool): Whether the item_id is from a track or not Returns: str: The music service item uri """ if is_track: uri = service.sonos_uri_from_id(item_id) else: uri = 'x-rincon-cpcontainer:' + item_id return uri
python
def form_uri(item_id, service, is_track): if is_track: uri = service.sonos_uri_from_id(item_id) else: uri = 'x-rincon-cpcontainer:' + item_id return uri
[ "def", "form_uri", "(", "item_id", ",", "service", ",", "is_track", ")", ":", "if", "is_track", ":", "uri", "=", "service", ".", "sonos_uri_from_id", "(", "item_id", ")", "else", ":", "uri", "=", "'x-rincon-cpcontainer:'", "+", "item_id", "return", "uri" ]
Form and return a music service item uri Args: item_id (str): The item id service (MusicService): The music service that the item originates from is_track (bool): Whether the item_id is from a track or not Returns: str: The music service item uri
[ "Form", "and", "return", "a", "music", "service", "item", "uri" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L152-L167
233,687
SoCo/SoCo
soco/music_services/data_structures.py
bool_str
def bool_str(string): """Returns a boolean from a string imput of 'true' or 'false'""" if string not in BOOL_STRS: raise ValueError('Invalid boolean string: "{}"'.format(string)) return True if string == 'true' else False
python
def bool_str(string): """Returns a boolean from a string imput of 'true' or 'false'""" if string not in BOOL_STRS: raise ValueError('Invalid boolean string: "{}"'.format(string)) return True if string == 'true' else False
[ "def", "bool_str", "(", "string", ")", ":", "if", "string", "not", "in", "BOOL_STRS", ":", "raise", "ValueError", "(", "'Invalid boolean string: \"{}\"'", ".", "format", "(", "string", ")", ")", "return", "True", "if", "string", "==", "'true'", "else", "Fals...
Returns a boolean from a string imput of 'true' or 'false
[ "Returns", "a", "boolean", "from", "a", "string", "imput", "of", "true", "or", "false" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L174-L178
233,688
SoCo/SoCo
soco/music_services/accounts.py
Account._get_account_xml
def _get_account_xml(soco): """Fetch the account data from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If soco is `None`, a random device will be used. Returns: str: a byte string containing the account data xml """ # It is likely that the same information is available over UPnP as well # via a call to # systemProperties.GetStringX([('VariableName','R_SvcAccounts')])) # This returns an encrypted string, and, so far, we cannot decrypt it device = soco or discovery.any_soco() log.debug("Fetching account data from %s", device) settings_url = "http://{}:1400/status/accounts".format( device.ip_address) result = requests.get(settings_url).content log.debug("Account data: %s", result) return result
python
def _get_account_xml(soco): # It is likely that the same information is available over UPnP as well # via a call to # systemProperties.GetStringX([('VariableName','R_SvcAccounts')])) # This returns an encrypted string, and, so far, we cannot decrypt it device = soco or discovery.any_soco() log.debug("Fetching account data from %s", device) settings_url = "http://{}:1400/status/accounts".format( device.ip_address) result = requests.get(settings_url).content log.debug("Account data: %s", result) return result
[ "def", "_get_account_xml", "(", "soco", ")", ":", "# It is likely that the same information is available over UPnP as well", "# via a call to", "# systemProperties.GetStringX([('VariableName','R_SvcAccounts')]))", "# This returns an encrypted string, and, so far, we cannot decrypt it", "device",...
Fetch the account data from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If soco is `None`, a random device will be used. Returns: str: a byte string containing the account data xml
[ "Fetch", "the", "account", "data", "from", "a", "Sonos", "device", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/accounts.py#L67-L87
233,689
SoCo/SoCo
soco/music_services/accounts.py
Account.get_accounts
def get_accounts(cls, soco=None): """Get all accounts known to the Sonos system. Args: soco (`SoCo`, optional): a `SoCo` instance to query. If `None`, a random instance is used. Defaults to `None`. Returns: dict: A dict containing account instances. Each key is the account's serial number, and each value is the related Account instance. Accounts which have been marked as deleted are excluded. Note: Any existing Account instance will have its attributes updated to those currently stored on the Sonos system. """ root = XML.fromstring(cls._get_account_xml(soco)) # _get_account_xml returns an ElementTree element like this: # <ZPSupportInfo type="User"> # <Accounts # LastUpdateDevice="RINCON_000XXXXXXXX400" # Version="8" NextSerialNum="5"> # <Account Type="2311" SerialNum="1"> # <UN>12345678</UN> # <MD>1</MD> # <NN></NN> # <OADevID></OADevID> # <Key></Key> # </Account> # <Account Type="41735" SerialNum="3" Deleted="1"> # <UN></UN> # <MD>1</MD> # <NN>Nickname</NN> # <OADevID></OADevID> # <Key></Key> # </Account> # ... # <Accounts /> xml_accounts = root.findall('.//Account') result = {} for xml_account in xml_accounts: serial_number = xml_account.get('SerialNum') is_deleted = True if xml_account.get('Deleted') == '1' else False # cls._all_accounts is a weakvaluedict keyed by serial number. # We use it as a database to store details of the accounts we # know about. We need to update it with info obtained from the # XML just obtained, so (1) check to see if we already have an # entry in cls._all_accounts for the account we have found in # XML; (2) if so, delete it if the XML says it has been deleted; # and (3) if not, create an entry for it if cls._all_accounts.get(serial_number): # We have an existing entry in our database. Do we need to # delete it? if is_deleted: # Yes, so delete it and move to the next XML account del cls._all_accounts[serial_number] continue else: # No, so load up its details, ready to update them account = cls._all_accounts.get(serial_number) else: # We have no existing entry for this account if is_deleted: # but it is marked as deleted, so we don't need one continue # If it is not marked as deleted, we need to create an entry account = Account() account.serial_number = serial_number cls._all_accounts[serial_number] = account # Now, update the entry in our database with the details from XML account.service_type = xml_account.get('Type') account.deleted = is_deleted account.username = xml_account.findtext('UN') # Not sure what 'MD' stands for. Metadata? May Delete? account.metadata = xml_account.findtext('MD') account.nickname = xml_account.findtext('NN') account.oa_device_id = xml_account.findtext('OADevID') account.key = xml_account.findtext('Key') result[serial_number] = account # There is always a TuneIn account, but it is handled separately # by Sonos, and does not appear in the xml account data. We # need to add it ourselves. tunein = Account() tunein.service_type = '65031' # Is this always the case? tunein.deleted = False tunein.username = '' tunein.metadata = '' tunein.nickname = '' tunein.oa_device_id = '' tunein.key = '' tunein.serial_number = '0' result['0'] = tunein return result
python
def get_accounts(cls, soco=None): root = XML.fromstring(cls._get_account_xml(soco)) # _get_account_xml returns an ElementTree element like this: # <ZPSupportInfo type="User"> # <Accounts # LastUpdateDevice="RINCON_000XXXXXXXX400" # Version="8" NextSerialNum="5"> # <Account Type="2311" SerialNum="1"> # <UN>12345678</UN> # <MD>1</MD> # <NN></NN> # <OADevID></OADevID> # <Key></Key> # </Account> # <Account Type="41735" SerialNum="3" Deleted="1"> # <UN></UN> # <MD>1</MD> # <NN>Nickname</NN> # <OADevID></OADevID> # <Key></Key> # </Account> # ... # <Accounts /> xml_accounts = root.findall('.//Account') result = {} for xml_account in xml_accounts: serial_number = xml_account.get('SerialNum') is_deleted = True if xml_account.get('Deleted') == '1' else False # cls._all_accounts is a weakvaluedict keyed by serial number. # We use it as a database to store details of the accounts we # know about. We need to update it with info obtained from the # XML just obtained, so (1) check to see if we already have an # entry in cls._all_accounts for the account we have found in # XML; (2) if so, delete it if the XML says it has been deleted; # and (3) if not, create an entry for it if cls._all_accounts.get(serial_number): # We have an existing entry in our database. Do we need to # delete it? if is_deleted: # Yes, so delete it and move to the next XML account del cls._all_accounts[serial_number] continue else: # No, so load up its details, ready to update them account = cls._all_accounts.get(serial_number) else: # We have no existing entry for this account if is_deleted: # but it is marked as deleted, so we don't need one continue # If it is not marked as deleted, we need to create an entry account = Account() account.serial_number = serial_number cls._all_accounts[serial_number] = account # Now, update the entry in our database with the details from XML account.service_type = xml_account.get('Type') account.deleted = is_deleted account.username = xml_account.findtext('UN') # Not sure what 'MD' stands for. Metadata? May Delete? account.metadata = xml_account.findtext('MD') account.nickname = xml_account.findtext('NN') account.oa_device_id = xml_account.findtext('OADevID') account.key = xml_account.findtext('Key') result[serial_number] = account # There is always a TuneIn account, but it is handled separately # by Sonos, and does not appear in the xml account data. We # need to add it ourselves. tunein = Account() tunein.service_type = '65031' # Is this always the case? tunein.deleted = False tunein.username = '' tunein.metadata = '' tunein.nickname = '' tunein.oa_device_id = '' tunein.key = '' tunein.serial_number = '0' result['0'] = tunein return result
[ "def", "get_accounts", "(", "cls", ",", "soco", "=", "None", ")", ":", "root", "=", "XML", ".", "fromstring", "(", "cls", ".", "_get_account_xml", "(", "soco", ")", ")", "# _get_account_xml returns an ElementTree element like this:", "# <ZPSupportInfo type=\"User\">",...
Get all accounts known to the Sonos system. Args: soco (`SoCo`, optional): a `SoCo` instance to query. If `None`, a random instance is used. Defaults to `None`. Returns: dict: A dict containing account instances. Each key is the account's serial number, and each value is the related Account instance. Accounts which have been marked as deleted are excluded. Note: Any existing Account instance will have its attributes updated to those currently stored on the Sonos system.
[ "Get", "all", "accounts", "known", "to", "the", "Sonos", "system", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/accounts.py#L90-L187
233,690
SoCo/SoCo
soco/music_services/accounts.py
Account.get_accounts_for_service
def get_accounts_for_service(cls, service_type): """Get a list of accounts for a given music service. Args: service_type (str): The service_type to use. Returns: list: A list of `Account` instances. """ return [ a for a in cls.get_accounts().values() if a.service_type == service_type ]
python
def get_accounts_for_service(cls, service_type): return [ a for a in cls.get_accounts().values() if a.service_type == service_type ]
[ "def", "get_accounts_for_service", "(", "cls", ",", "service_type", ")", ":", "return", "[", "a", "for", "a", "in", "cls", ".", "get_accounts", "(", ")", ".", "values", "(", ")", "if", "a", ".", "service_type", "==", "service_type", "]" ]
Get a list of accounts for a given music service. Args: service_type (str): The service_type to use. Returns: list: A list of `Account` instances.
[ "Get", "a", "list", "of", "accounts", "for", "a", "given", "music", "service", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/accounts.py#L190-L202
233,691
SoCo/SoCo
examples/snapshot/multi_zone_snap.py
play_alert
def play_alert(zones, alert_uri, alert_volume=20, alert_duration=0, fade_back=False): """ Demo function using soco.snapshot across multiple Sonos players. Args: zones (set): a set of SoCo objects alert_uri (str): uri that Sonos can play as an alert alert_volume (int): volume level for playing alert (0 tp 100) alert_duration (int): length of alert (if zero then length of track) fade_back (bool): on reinstating the zones fade up the sound? """ # Use soco.snapshot to capture current state of each zone to allow restore for zone in zones: zone.snap = Snapshot(zone) zone.snap.snapshot() print('snapshot of zone: {}'.format(zone.player_name)) # prepare all zones for playing the alert for zone in zones: # Each Sonos group has one coordinator only these can play, pause, etc. if zone.is_coordinator: if not zone.is_playing_tv: # can't pause TV - so don't try! # pause music for each coordinators if playing trans_state = zone.get_current_transport_info() if trans_state['current_transport_state'] == 'PLAYING': zone.pause() # For every Sonos player set volume and mute for every zone zone.volume = alert_volume zone.mute = False # play the sound (uri) on each sonos coordinator print('will play: {} on all coordinators'.format(alert_uri)) for zone in zones: if zone.is_coordinator: zone.play_uri(uri=alert_uri, title='Sonos Alert') # wait for alert_duration time.sleep(alert_duration) # restore each zone to previous state for zone in zones: print('restoring {}'.format(zone.player_name)) zone.snap.restore(fade=fade_back)
python
def play_alert(zones, alert_uri, alert_volume=20, alert_duration=0, fade_back=False): # Use soco.snapshot to capture current state of each zone to allow restore for zone in zones: zone.snap = Snapshot(zone) zone.snap.snapshot() print('snapshot of zone: {}'.format(zone.player_name)) # prepare all zones for playing the alert for zone in zones: # Each Sonos group has one coordinator only these can play, pause, etc. if zone.is_coordinator: if not zone.is_playing_tv: # can't pause TV - so don't try! # pause music for each coordinators if playing trans_state = zone.get_current_transport_info() if trans_state['current_transport_state'] == 'PLAYING': zone.pause() # For every Sonos player set volume and mute for every zone zone.volume = alert_volume zone.mute = False # play the sound (uri) on each sonos coordinator print('will play: {} on all coordinators'.format(alert_uri)) for zone in zones: if zone.is_coordinator: zone.play_uri(uri=alert_uri, title='Sonos Alert') # wait for alert_duration time.sleep(alert_duration) # restore each zone to previous state for zone in zones: print('restoring {}'.format(zone.player_name)) zone.snap.restore(fade=fade_back)
[ "def", "play_alert", "(", "zones", ",", "alert_uri", ",", "alert_volume", "=", "20", ",", "alert_duration", "=", "0", ",", "fade_back", "=", "False", ")", ":", "# Use soco.snapshot to capture current state of each zone to allow restore", "for", "zone", "in", "zones", ...
Demo function using soco.snapshot across multiple Sonos players. Args: zones (set): a set of SoCo objects alert_uri (str): uri that Sonos can play as an alert alert_volume (int): volume level for playing alert (0 tp 100) alert_duration (int): length of alert (if zero then length of track) fade_back (bool): on reinstating the zones fade up the sound?
[ "Demo", "function", "using", "soco", ".", "snapshot", "across", "multiple", "Sonos", "players", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/examples/snapshot/multi_zone_snap.py#L27-L71
233,692
SoCo/SoCo
soco/cache.py
TimedCache.get
def get(self, *args, **kwargs): """Get an item from the cache for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. Returns: object: The object which has been found in the cache, or `None` if no unexpired item is found. This means that there is no point storing an item in the cache if it is `None`. """ if not self.enabled: return None # Look in the cache to see if there is an unexpired item. If there is # we can just return the cached result. cache_key = self.make_key(args, kwargs) # Lock and load with self._cache_lock: if cache_key in self._cache: expirytime, item = self._cache[cache_key] if expirytime >= time(): return item else: # An expired item is present - delete it del self._cache[cache_key] # Nothing found return None
python
def get(self, *args, **kwargs): if not self.enabled: return None # Look in the cache to see if there is an unexpired item. If there is # we can just return the cached result. cache_key = self.make_key(args, kwargs) # Lock and load with self._cache_lock: if cache_key in self._cache: expirytime, item = self._cache[cache_key] if expirytime >= time(): return item else: # An expired item is present - delete it del self._cache[cache_key] # Nothing found return None
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "None", "# Look in the cache to see if there is an unexpired item. If there is", "# we can just return the cached result.", "cache_key", ...
Get an item from the cache for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. Returns: object: The object which has been found in the cache, or `None` if no unexpired item is found. This means that there is no point storing an item in the cache if it is `None`.
[ "Get", "an", "item", "from", "the", "cache", "for", "this", "combination", "of", "args", "and", "kwargs", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/cache.py#L117-L146
233,693
SoCo/SoCo
soco/cache.py
TimedCache.put
def put(self, item, *args, **kwargs): """Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available for retrieval for ``timeout`` seconds. If ``timeout`` is `None` or not specified, the ``default_timeout`` for this cache will be used. Specify a ``timeout`` of 0 (or ensure that the ``default_timeout`` for this cache is 0) if this item is not to be cached. """ if not self.enabled: return # Check for a timeout keyword, store and remove it. timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.default_timeout cache_key = self.make_key(args, kwargs) # Store the item, along with the time at which it will expire with self._cache_lock: self._cache[cache_key] = (time() + timeout, item)
python
def put(self, item, *args, **kwargs): if not self.enabled: return # Check for a timeout keyword, store and remove it. timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.default_timeout cache_key = self.make_key(args, kwargs) # Store the item, along with the time at which it will expire with self._cache_lock: self._cache[cache_key] = (time() + timeout, item)
[ "def", "put", "(", "self", ",", "item", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "# Check for a timeout keyword, store and remove it.", "timeout", "=", "kwargs", ".", "pop", "(", "'timeout'", ...
Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available for retrieval for ``timeout`` seconds. If ``timeout`` is `None` or not specified, the ``default_timeout`` for this cache will be used. Specify a ``timeout`` of 0 (or ensure that the ``default_timeout`` for this cache is 0) if this item is not to be cached.
[ "Put", "an", "item", "into", "the", "cache", "for", "this", "combination", "of", "args", "and", "kwargs", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/cache.py#L148-L170
233,694
SoCo/SoCo
soco/cache.py
TimedCache.delete
def delete(self, *args, **kwargs): """Delete an item from the cache for this combination of args and kwargs.""" cache_key = self.make_key(args, kwargs) with self._cache_lock: try: del self._cache[cache_key] except KeyError: pass
python
def delete(self, *args, **kwargs): cache_key = self.make_key(args, kwargs) with self._cache_lock: try: del self._cache[cache_key] except KeyError: pass
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cache_key", "=", "self", ".", "make_key", "(", "args", ",", "kwargs", ")", "with", "self", ".", "_cache_lock", ":", "try", ":", "del", "self", ".", "_cache", "[", ...
Delete an item from the cache for this combination of args and kwargs.
[ "Delete", "an", "item", "from", "the", "cache", "for", "this", "combination", "of", "args", "and", "kwargs", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/cache.py#L172-L180
233,695
SoCo/SoCo
soco/music_library.py
MusicLibrary.build_album_art_full_uri
def build_album_art_full_uri(self, url): """Ensure an Album Art URI is an absolute URI. Args: url (str): the album art URI. Returns: str: An absolute URI. """ # Add on the full album art link, as the URI version # does not include the ipaddress if not url.startswith(('http:', 'https:')): url = 'http://' + self.soco.ip_address + ':1400' + url return url
python
def build_album_art_full_uri(self, url): # Add on the full album art link, as the URI version # does not include the ipaddress if not url.startswith(('http:', 'https:')): url = 'http://' + self.soco.ip_address + ':1400' + url return url
[ "def", "build_album_art_full_uri", "(", "self", ",", "url", ")", ":", "# Add on the full album art link, as the URI version", "# does not include the ipaddress", "if", "not", "url", ".", "startswith", "(", "(", "'http:'", ",", "'https:'", ")", ")", ":", "url", "=", ...
Ensure an Album Art URI is an absolute URI. Args: url (str): the album art URI. Returns: str: An absolute URI.
[ "Ensure", "an", "Album", "Art", "URI", "is", "an", "absolute", "URI", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L59-L72
233,696
SoCo/SoCo
soco/music_library.py
MusicLibrary._update_album_art_to_full_uri
def _update_album_art_to_full_uri(self, item): """Update an item's Album Art URI to be an absolute URI. Args: item: The item to update the URI for """ if getattr(item, 'album_art_uri', False): item.album_art_uri = self.build_album_art_full_uri( item.album_art_uri)
python
def _update_album_art_to_full_uri(self, item): if getattr(item, 'album_art_uri', False): item.album_art_uri = self.build_album_art_full_uri( item.album_art_uri)
[ "def", "_update_album_art_to_full_uri", "(", "self", ",", "item", ")", ":", "if", "getattr", "(", "item", ",", "'album_art_uri'", ",", "False", ")", ":", "item", ".", "album_art_uri", "=", "self", ".", "build_album_art_full_uri", "(", "item", ".", "album_art_u...
Update an item's Album Art URI to be an absolute URI. Args: item: The item to update the URI for
[ "Update", "an", "item", "s", "Album", "Art", "URI", "to", "be", "an", "absolute", "URI", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L74-L82
233,697
SoCo/SoCo
soco/music_library.py
MusicLibrary.get_music_library_information
def get_music_library_information(self, search_type, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None, complete_result=False): """Retrieve music information objects from the music library. This method is the main method to get music information items, like e.g. tracks, albums etc., from the music library with. It can be used in a few different ways: The ``search_term`` argument performs a fuzzy search on that string in the results, so e.g calling:: get_music_library_information('artists', search_term='Metallica') will perform a fuzzy search for the term 'Metallica' among all the artists. Using the ``subcategories`` argument, will jump directly into that subcategory of the search and return results from there. So. e.g knowing that among the artist is one called 'Metallica', calling:: get_music_library_information('artists', subcategories=['Metallica']) will jump directly into the 'Metallica' sub category and return the albums associated with Metallica and:: get_music_library_information('artists', subcategories=['Metallica', 'Black']) will return the tracks of the album 'Black' by the artist 'Metallica'. The order of sub category types is: Genres->Artists->Albums->Tracks. It is also possible to combine the two, to perform a fuzzy search in a sub category. The ``start``, ``max_items`` and ``complete_result`` arguments all have to do with paging of the results. By default the searches are always paged, because there is a limit to how many items we can get at a time. This paging is exposed to the user with the ``start`` and ``max_items`` arguments. So calling:: get_music_library_information('artists', start=0, max_items=100) get_music_library_information('artists', start=100, max_items=100) will get the first and next 100 items, respectively. It is also possible to ask for all the elements at once:: get_music_library_information('artists', complete_result=True) This will perform the paging internally and simply return all the items. Args: search_type (str): The kind of information to retrieve. Can be one of: ``'artists'``, ``'album_artists'``, ``'albums'``, ``'genres'``, ``'composers'``, ``'tracks'``, ``'share'``, ``'sonos_playlists'``, or ``'playlists'``, where playlists are the imported playlists from the music library. start (int, optional): starting number of returned matches (zero based). Default 0. max_items (int, optional): Maximum number of returned matches. Default 100. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. search_term (str, optional): a string that will be used to perform a fuzzy search among the search results. If used in combination with subcategories, the fuzzy search will be performed in the subcategory. subcategories (str, optional): A list of strings that indicate one or more subcategories to dive into. complete_result (bool): if `True`, will disable paging (ignore ``start`` and ``max_items``) and return all results for the search. Warning: Getting e.g. all the tracks in a large collection might take some time. Returns: `SearchResult`: an instance of `SearchResult`. Note: * The maximum numer of results may be restricted by the unit, presumably due to transfer size consideration, so check the returned number against that requested. * The playlists that are returned with the ``'playlists'`` search, are the playlists imported from the music library, they are not the Sonos playlists. Raises: `SoCoException` upon errors. """ search = self.SEARCH_TRANSLATION[search_type] # Add sub categories if subcategories is not None: for category in subcategories: search += '/' + url_escape_path(really_unicode(category)) # Add fuzzy search if search_term is not None: search += ':' + url_escape_path(really_unicode(search_term)) item_list = [] metadata = {'total_matches': 100000} while len(item_list) < metadata['total_matches']: # Change start and max for complete searches if complete_result: start, max_items = len(item_list), 100000 # Try and get this batch of results try: response, metadata = \ self._music_lib_search(search, start, max_items) except SoCoUPnPException as exception: # 'No such object' UPnP errors if exception.error_code == '701': return SearchResult([], search_type, 0, 0, None) else: raise exception # Parse the results items = from_didl_string(response['Result']) for item in items: # Check if the album art URI should be fully qualified if full_album_art_uri: self._update_album_art_to_full_uri(item) # Append the item to the list item_list.append(item) # If we are not after the complete results, the stop after 1 # iteration if not complete_result: break metadata['search_type'] = search_type if complete_result: metadata['number_returned'] = len(item_list) # pylint: disable=star-args return SearchResult(item_list, **metadata)
python
def get_music_library_information(self, search_type, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None, complete_result=False): search = self.SEARCH_TRANSLATION[search_type] # Add sub categories if subcategories is not None: for category in subcategories: search += '/' + url_escape_path(really_unicode(category)) # Add fuzzy search if search_term is not None: search += ':' + url_escape_path(really_unicode(search_term)) item_list = [] metadata = {'total_matches': 100000} while len(item_list) < metadata['total_matches']: # Change start and max for complete searches if complete_result: start, max_items = len(item_list), 100000 # Try and get this batch of results try: response, metadata = \ self._music_lib_search(search, start, max_items) except SoCoUPnPException as exception: # 'No such object' UPnP errors if exception.error_code == '701': return SearchResult([], search_type, 0, 0, None) else: raise exception # Parse the results items = from_didl_string(response['Result']) for item in items: # Check if the album art URI should be fully qualified if full_album_art_uri: self._update_album_art_to_full_uri(item) # Append the item to the list item_list.append(item) # If we are not after the complete results, the stop after 1 # iteration if not complete_result: break metadata['search_type'] = search_type if complete_result: metadata['number_returned'] = len(item_list) # pylint: disable=star-args return SearchResult(item_list, **metadata)
[ "def", "get_music_library_information", "(", "self", ",", "search_type", ",", "start", "=", "0", ",", "max_items", "=", "100", ",", "full_album_art_uri", "=", "False", ",", "search_term", "=", "None", ",", "subcategories", "=", "None", ",", "complete_result", ...
Retrieve music information objects from the music library. This method is the main method to get music information items, like e.g. tracks, albums etc., from the music library with. It can be used in a few different ways: The ``search_term`` argument performs a fuzzy search on that string in the results, so e.g calling:: get_music_library_information('artists', search_term='Metallica') will perform a fuzzy search for the term 'Metallica' among all the artists. Using the ``subcategories`` argument, will jump directly into that subcategory of the search and return results from there. So. e.g knowing that among the artist is one called 'Metallica', calling:: get_music_library_information('artists', subcategories=['Metallica']) will jump directly into the 'Metallica' sub category and return the albums associated with Metallica and:: get_music_library_information('artists', subcategories=['Metallica', 'Black']) will return the tracks of the album 'Black' by the artist 'Metallica'. The order of sub category types is: Genres->Artists->Albums->Tracks. It is also possible to combine the two, to perform a fuzzy search in a sub category. The ``start``, ``max_items`` and ``complete_result`` arguments all have to do with paging of the results. By default the searches are always paged, because there is a limit to how many items we can get at a time. This paging is exposed to the user with the ``start`` and ``max_items`` arguments. So calling:: get_music_library_information('artists', start=0, max_items=100) get_music_library_information('artists', start=100, max_items=100) will get the first and next 100 items, respectively. It is also possible to ask for all the elements at once:: get_music_library_information('artists', complete_result=True) This will perform the paging internally and simply return all the items. Args: search_type (str): The kind of information to retrieve. Can be one of: ``'artists'``, ``'album_artists'``, ``'albums'``, ``'genres'``, ``'composers'``, ``'tracks'``, ``'share'``, ``'sonos_playlists'``, or ``'playlists'``, where playlists are the imported playlists from the music library. start (int, optional): starting number of returned matches (zero based). Default 0. max_items (int, optional): Maximum number of returned matches. Default 100. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. search_term (str, optional): a string that will be used to perform a fuzzy search among the search results. If used in combination with subcategories, the fuzzy search will be performed in the subcategory. subcategories (str, optional): A list of strings that indicate one or more subcategories to dive into. complete_result (bool): if `True`, will disable paging (ignore ``start`` and ``max_items``) and return all results for the search. Warning: Getting e.g. all the tracks in a large collection might take some time. Returns: `SearchResult`: an instance of `SearchResult`. Note: * The maximum numer of results may be restricted by the unit, presumably due to transfer size consideration, so check the returned number against that requested. * The playlists that are returned with the ``'playlists'`` search, are the playlists imported from the music library, they are not the Sonos playlists. Raises: `SoCoException` upon errors.
[ "Retrieve", "music", "information", "objects", "from", "the", "music", "library", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L188-L334
233,698
SoCo/SoCo
soco/music_library.py
MusicLibrary._music_lib_search
def _music_lib_search(self, search, start, max_items): """Perform a music library search and extract search numbers. You can get an overview of all the relevant search prefixes (like 'A:') and their meaning with the request: .. code :: response = device.contentDirectory.Browse([ ('ObjectID', '0'), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', 0), ('RequestedCount', 100), ('SortCriteria', '') ]) Args: search (str): The ID to search. start (int): The index of the forst item to return. max_items (int): The maximum number of items to return. Returns: tuple: (response, metadata) where response is the returned metadata and metadata is a dict with the 'number_returned', 'total_matches' and 'update_id' integers """ response = self.contentDirectory.Browse([ ('ObjectID', search), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', start), ('RequestedCount', max_items), ('SortCriteria', '') ]) # Get result information metadata = {} for tag in ['NumberReturned', 'TotalMatches', 'UpdateID']: metadata[camel_to_underscore(tag)] = int(response[tag]) return response, metadata
python
def _music_lib_search(self, search, start, max_items): response = self.contentDirectory.Browse([ ('ObjectID', search), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', start), ('RequestedCount', max_items), ('SortCriteria', '') ]) # Get result information metadata = {} for tag in ['NumberReturned', 'TotalMatches', 'UpdateID']: metadata[camel_to_underscore(tag)] = int(response[tag]) return response, metadata
[ "def", "_music_lib_search", "(", "self", ",", "search", ",", "start", ",", "max_items", ")", ":", "response", "=", "self", ".", "contentDirectory", ".", "Browse", "(", "[", "(", "'ObjectID'", ",", "search", ")", ",", "(", "'BrowseFlag'", ",", "'BrowseDirec...
Perform a music library search and extract search numbers. You can get an overview of all the relevant search prefixes (like 'A:') and their meaning with the request: .. code :: response = device.contentDirectory.Browse([ ('ObjectID', '0'), ('BrowseFlag', 'BrowseDirectChildren'), ('Filter', '*'), ('StartingIndex', 0), ('RequestedCount', 100), ('SortCriteria', '') ]) Args: search (str): The ID to search. start (int): The index of the forst item to return. max_items (int): The maximum number of items to return. Returns: tuple: (response, metadata) where response is the returned metadata and metadata is a dict with the 'number_returned', 'total_matches' and 'update_id' integers
[ "Perform", "a", "music", "library", "search", "and", "extract", "search", "numbers", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L446-L486
233,699
SoCo/SoCo
soco/music_library.py
MusicLibrary.search_track
def search_track(self, artist, album=None, track=None, full_album_art_uri=False): """Search for an artist, an artist's albums, or specific track. Args: artist (str): an artist's name. album (str, optional): an album name. Default `None`. track (str, optional): a track name. Default `None`. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance. """ subcategories = [artist] subcategories.append(album or '') # Perform the search result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, search_term=track, complete_result=True) result._metadata['search_type'] = 'search_track' return result
python
def search_track(self, artist, album=None, track=None, full_album_art_uri=False): subcategories = [artist] subcategories.append(album or '') # Perform the search result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, search_term=track, complete_result=True) result._metadata['search_type'] = 'search_track' return result
[ "def", "search_track", "(", "self", ",", "artist", ",", "album", "=", "None", ",", "track", "=", "None", ",", "full_album_art_uri", "=", "False", ")", ":", "subcategories", "=", "[", "artist", "]", "subcategories", ".", "append", "(", "album", "or", "''"...
Search for an artist, an artist's albums, or specific track. Args: artist (str): an artist's name. album (str, optional): an album name. Default `None`. track (str, optional): a track name. Default `None`. full_album_art_uri (bool): whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance.
[ "Search", "for", "an", "artist", "an", "artist", "s", "albums", "or", "specific", "track", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L506-L529