repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
necaris/python3-openid
openid/extensions/ax.py
FetchRequest.parseExtensionArgs
def parseExtensionArgs(self, ax_args): """Given attribute exchange arguments, populate this FetchRequest. @param ax_args: Attribute Exchange arguments from the request. As returned from L{Message.getArgs<openid.message.Message.getArgs>}. @type ax_args: dict @raises KeyError: if the message is not consistent in its use of namespace aliases. @raises NotAXMessage: If ax_args does not include an Attribute Exchange mode. @raises AXError: If the data to be parsed does not follow the attribute exchange specification. At least when 'if_available' or 'required' is not specified for a particular attribute type. """ # Raises an exception if the mode is not the expected value self._checkMode(ax_args) aliases = NamespaceMap() for key, value in ax_args.items(): if key.startswith('type.'): alias = key[5:] type_uri = value aliases.addAlias(type_uri, alias) count_key = 'count.' + alias count_s = ax_args.get(count_key) if count_s: try: count = int(count_s) if count <= 0: raise AXError( "Count %r must be greater than zero, got %r" % (count_key, count_s, )) except ValueError: if count_s != UNLIMITED_VALUES: raise AXError("Invalid count value for %r: %r" % (count_key, count_s, )) count = count_s else: count = 1 self.add(AttrInfo(type_uri, alias=alias, count=count)) required = toTypeURIs(aliases, ax_args.get('required')) for type_uri in required: self.requested_attributes[type_uri].required = True if_available = toTypeURIs(aliases, ax_args.get('if_available')) all_type_uris = required + if_available for type_uri in aliases.iterNamespaceURIs(): if type_uri not in all_type_uris: raise AXError('Type URI %r was in the request but not ' 'present in "required" or "if_available"' % (type_uri, )) self.update_url = ax_args.get('update_url')
python
def parseExtensionArgs(self, ax_args): """Given attribute exchange arguments, populate this FetchRequest. @param ax_args: Attribute Exchange arguments from the request. As returned from L{Message.getArgs<openid.message.Message.getArgs>}. @type ax_args: dict @raises KeyError: if the message is not consistent in its use of namespace aliases. @raises NotAXMessage: If ax_args does not include an Attribute Exchange mode. @raises AXError: If the data to be parsed does not follow the attribute exchange specification. At least when 'if_available' or 'required' is not specified for a particular attribute type. """ # Raises an exception if the mode is not the expected value self._checkMode(ax_args) aliases = NamespaceMap() for key, value in ax_args.items(): if key.startswith('type.'): alias = key[5:] type_uri = value aliases.addAlias(type_uri, alias) count_key = 'count.' + alias count_s = ax_args.get(count_key) if count_s: try: count = int(count_s) if count <= 0: raise AXError( "Count %r must be greater than zero, got %r" % (count_key, count_s, )) except ValueError: if count_s != UNLIMITED_VALUES: raise AXError("Invalid count value for %r: %r" % (count_key, count_s, )) count = count_s else: count = 1 self.add(AttrInfo(type_uri, alias=alias, count=count)) required = toTypeURIs(aliases, ax_args.get('required')) for type_uri in required: self.requested_attributes[type_uri].required = True if_available = toTypeURIs(aliases, ax_args.get('if_available')) all_type_uris = required + if_available for type_uri in aliases.iterNamespaceURIs(): if type_uri not in all_type_uris: raise AXError('Type URI %r was in the request but not ' 'present in "required" or "if_available"' % (type_uri, )) self.update_url = ax_args.get('update_url')
Given attribute exchange arguments, populate this FetchRequest. @param ax_args: Attribute Exchange arguments from the request. As returned from L{Message.getArgs<openid.message.Message.getArgs>}. @type ax_args: dict @raises KeyError: if the message is not consistent in its use of namespace aliases. @raises NotAXMessage: If ax_args does not include an Attribute Exchange mode. @raises AXError: If the data to be parsed does not follow the attribute exchange specification. At least when 'if_available' or 'required' is not specified for a particular attribute type.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/extensions/ax.py#L334-L397
necaris/python3-openid
openid/consumer/html_parse.py
findLinksRel
def findLinksRel(link_attrs_list, target_rel): """Filter the list of link attributes on whether it has target_rel as a relationship.""" # XXX: TESTME matchesTarget = lambda attrs: linkHasRel(attrs, target_rel) return list(filter(matchesTarget, link_attrs_list))
python
def findLinksRel(link_attrs_list, target_rel): """Filter the list of link attributes on whether it has target_rel as a relationship.""" # XXX: TESTME matchesTarget = lambda attrs: linkHasRel(attrs, target_rel) return list(filter(matchesTarget, link_attrs_list))
Filter the list of link attributes on whether it has target_rel as a relationship.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/consumer/html_parse.py#L262-L267
necaris/python3-openid
openid/store/sqlstore.py
SQLStore.txn_getAssociation
def txn_getAssociation(self, server_url, handle=None): """Get the most recent association that has been set for this server URL and handle. str -> NoneType or Association """ if handle is not None: self.db_get_assoc(server_url, handle) else: self.db_get_assocs(server_url) rows = self.cur.fetchall() if len(rows) == 0: return None else: associations = [] for values in rows: values = list(values) values[1] = self.blobDecode(values[1]) assoc = Association(*values) if assoc.expiresIn == 0: self.txn_removeAssociation(server_url, assoc.handle) else: associations.append((assoc.issued, assoc)) if associations: associations.sort() return associations[-1][1] else: return None
python
def txn_getAssociation(self, server_url, handle=None): """Get the most recent association that has been set for this server URL and handle. str -> NoneType or Association """ if handle is not None: self.db_get_assoc(server_url, handle) else: self.db_get_assocs(server_url) rows = self.cur.fetchall() if len(rows) == 0: return None else: associations = [] for values in rows: values = list(values) values[1] = self.blobDecode(values[1]) assoc = Association(*values) if assoc.expiresIn == 0: self.txn_removeAssociation(server_url, assoc.handle) else: associations.append((assoc.issued, assoc)) if associations: associations.sort() return associations[-1][1] else: return None
Get the most recent association that has been set for this server URL and handle. str -> NoneType or Association
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/store/sqlstore.py#L220-L249
necaris/python3-openid
openid/fetchers.py
Urllib2Fetcher._makeResponse
def _makeResponse(self, urllib2_response): ''' Construct an HTTPResponse from the the urllib response. Attempt to decode the response body from bytes to str if the necessary information is available. ''' resp = HTTPResponse() resp.body = urllib2_response.read(MAX_RESPONSE_KB * 1024) resp.final_url = urllib2_response.geturl() resp.headers = self._lowerCaseKeys( dict(list(urllib2_response.info().items()))) if hasattr(urllib2_response, 'code'): resp.status = urllib2_response.code else: resp.status = 200 _, extra_dict = self._parseHeaderValue( resp.headers.get("content-type", "")) # Try to decode the response body to a string, if there's a # charset known; fall back to ISO-8859-1 otherwise, since that's # what's suggested in HTTP/1.1 charset = extra_dict.get('charset', 'latin1') try: resp.body = resp.body.decode(charset) except Exception: pass return resp
python
def _makeResponse(self, urllib2_response): ''' Construct an HTTPResponse from the the urllib response. Attempt to decode the response body from bytes to str if the necessary information is available. ''' resp = HTTPResponse() resp.body = urllib2_response.read(MAX_RESPONSE_KB * 1024) resp.final_url = urllib2_response.geturl() resp.headers = self._lowerCaseKeys( dict(list(urllib2_response.info().items()))) if hasattr(urllib2_response, 'code'): resp.status = urllib2_response.code else: resp.status = 200 _, extra_dict = self._parseHeaderValue( resp.headers.get("content-type", "")) # Try to decode the response body to a string, if there's a # charset known; fall back to ISO-8859-1 otherwise, since that's # what's suggested in HTTP/1.1 charset = extra_dict.get('charset', 'latin1') try: resp.body = resp.body.decode(charset) except Exception: pass return resp
Construct an HTTPResponse from the the urllib response. Attempt to decode the response body from bytes to str if the necessary information is available.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/fetchers.py#L243-L271
necaris/python3-openid
openid/fetchers.py
Urllib2Fetcher._parseHeaderValue
def _parseHeaderValue(self, header_value): """ Parse out a complex header value (such as Content-Type, with a value like "text/html; charset=utf-8") into a main value and a dictionary of extra information (in this case, 'text/html' and {'charset': 'utf8'}). """ values = header_value.split(';', 1) if len(values) == 1: # There's no extra info -- return the main value and an empty dict return values[0], {} main_value, extra_values = values[0], values[1].split(';') extra_dict = {} for value_string in extra_values: try: key, value = value_string.split('=', 1) extra_dict[key.strip()] = value.strip() except ValueError: # Can't unpack it -- must be malformed. Ignore pass return main_value, extra_dict
python
def _parseHeaderValue(self, header_value): """ Parse out a complex header value (such as Content-Type, with a value like "text/html; charset=utf-8") into a main value and a dictionary of extra information (in this case, 'text/html' and {'charset': 'utf8'}). """ values = header_value.split(';', 1) if len(values) == 1: # There's no extra info -- return the main value and an empty dict return values[0], {} main_value, extra_values = values[0], values[1].split(';') extra_dict = {} for value_string in extra_values: try: key, value = value_string.split('=', 1) extra_dict[key.strip()] = value.strip() except ValueError: # Can't unpack it -- must be malformed. Ignore pass return main_value, extra_dict
Parse out a complex header value (such as Content-Type, with a value like "text/html; charset=utf-8") into a main value and a dictionary of extra information (in this case, 'text/html' and {'charset': 'utf8'}).
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/fetchers.py#L279-L298
necaris/python3-openid
openid/message.py
registerNamespaceAlias
def registerNamespaceAlias(namespace_uri, alias): """ Registers a (namespace URI, alias) mapping in a global namespace alias map. Raises NamespaceAliasRegistrationError if either the namespace URI or alias has already been registered with a different value. This function is required if you want to use a namespace with an OpenID 1 message. """ global registered_aliases if registered_aliases.get(alias) == namespace_uri: return if namespace_uri in list(registered_aliases.values()): raise NamespaceAliasRegistrationError( 'Namespace uri %r already registered' % (namespace_uri, )) if alias in registered_aliases: raise NamespaceAliasRegistrationError('Alias %r already registered' % (alias, )) registered_aliases[alias] = namespace_uri
python
def registerNamespaceAlias(namespace_uri, alias): """ Registers a (namespace URI, alias) mapping in a global namespace alias map. Raises NamespaceAliasRegistrationError if either the namespace URI or alias has already been registered with a different value. This function is required if you want to use a namespace with an OpenID 1 message. """ global registered_aliases if registered_aliases.get(alias) == namespace_uri: return if namespace_uri in list(registered_aliases.values()): raise NamespaceAliasRegistrationError( 'Namespace uri %r already registered' % (namespace_uri, )) if alias in registered_aliases: raise NamespaceAliasRegistrationError('Alias %r already registered' % (alias, )) registered_aliases[alias] = namespace_uri
Registers a (namespace URI, alias) mapping in a global namespace alias map. Raises NamespaceAliasRegistrationError if either the namespace URI or alias has already been registered with a different value. This function is required if you want to use a namespace with an OpenID 1 message.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L115-L136
necaris/python3-openid
openid/message.py
Message.setOpenIDNamespace
def setOpenIDNamespace(self, openid_ns_uri, implicit): """Set the OpenID namespace URI used in this message. @raises InvalidOpenIDNamespace: if the namespace is not in L{Message.allowed_openid_namespaces} """ if isinstance(openid_ns_uri, bytes): openid_ns_uri = str(openid_ns_uri, encoding="utf-8") if openid_ns_uri not in self.allowed_openid_namespaces: raise InvalidOpenIDNamespace(openid_ns_uri) self.namespaces.addAlias(openid_ns_uri, NULL_NAMESPACE, implicit) self._openid_ns_uri = openid_ns_uri
python
def setOpenIDNamespace(self, openid_ns_uri, implicit): """Set the OpenID namespace URI used in this message. @raises InvalidOpenIDNamespace: if the namespace is not in L{Message.allowed_openid_namespaces} """ if isinstance(openid_ns_uri, bytes): openid_ns_uri = str(openid_ns_uri, encoding="utf-8") if openid_ns_uri not in self.allowed_openid_namespaces: raise InvalidOpenIDNamespace(openid_ns_uri) self.namespaces.addAlias(openid_ns_uri, NULL_NAMESPACE, implicit) self._openid_ns_uri = openid_ns_uri
Set the OpenID namespace URI used in this message. @raises InvalidOpenIDNamespace: if the namespace is not in L{Message.allowed_openid_namespaces}
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L256-L268
necaris/python3-openid
openid/message.py
Message.toPostArgs
def toPostArgs(self): """ Return all arguments with openid. in front of namespaced arguments. @return bytes """ args = {} # Add namespace definitions to the output for ns_uri, alias in self.namespaces.items(): if self.namespaces.isImplicit(ns_uri): continue if alias == NULL_NAMESPACE: ns_key = 'openid.ns' else: ns_key = 'openid.ns.' + alias args[ns_key] = oidutil.toUnicode(ns_uri) for (ns_uri, ns_key), value in self.args.items(): key = self.getKey(ns_uri, ns_key) # Ensure the resulting value is an UTF-8 encoded *bytestring*. args[key] = oidutil.toUnicode(value) return args
python
def toPostArgs(self): """ Return all arguments with openid. in front of namespaced arguments. @return bytes """ args = {} # Add namespace definitions to the output for ns_uri, alias in self.namespaces.items(): if self.namespaces.isImplicit(ns_uri): continue if alias == NULL_NAMESPACE: ns_key = 'openid.ns' else: ns_key = 'openid.ns.' + alias args[ns_key] = oidutil.toUnicode(ns_uri) for (ns_uri, ns_key), value in self.args.items(): key = self.getKey(ns_uri, ns_key) # Ensure the resulting value is an UTF-8 encoded *bytestring*. args[key] = oidutil.toUnicode(value) return args
Return all arguments with openid. in front of namespaced arguments. @return bytes
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L288-L310
necaris/python3-openid
openid/message.py
Message.toArgs
def toArgs(self): """Return all namespaced arguments, failing if any non-namespaced arguments exist.""" # FIXME - undocumented exception post_args = self.toPostArgs() kvargs = {} for k, v in post_args.items(): if not k.startswith('openid.'): raise ValueError( 'This message can only be encoded as a POST, because it ' 'contains arguments that are not prefixed with "openid."') else: kvargs[k[7:]] = v return kvargs
python
def toArgs(self): """Return all namespaced arguments, failing if any non-namespaced arguments exist.""" # FIXME - undocumented exception post_args = self.toPostArgs() kvargs = {} for k, v in post_args.items(): if not k.startswith('openid.'): raise ValueError( 'This message can only be encoded as a POST, because it ' 'contains arguments that are not prefixed with "openid."') else: kvargs[k[7:]] = v return kvargs
Return all namespaced arguments, failing if any non-namespaced arguments exist.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L312-L326
necaris/python3-openid
openid/message.py
Message.toFormMarkup
def toFormMarkup(self, action_url, form_tag_attrs=None, submit_text="Continue"): """Generate HTML form markup that contains the values in this message, to be HTTP POSTed as x-www-form-urlencoded UTF-8. @param action_url: The URL to which the form will be POSTed @type action_url: str @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. @type form_tag_attrs: {unicode: unicode} @param submit_text: The text that will appear on the submit button for this form. @type submit_text: unicode @returns: A string containing (X)HTML markup for a form that encodes the values in this Message object. @rtype: str """ if ElementTree is None: raise RuntimeError('This function requires ElementTree.') assert action_url is not None form = ElementTree.Element('form') if form_tag_attrs: for name, attr in form_tag_attrs.items(): form.attrib[name] = attr form.attrib['action'] = oidutil.toUnicode(action_url) form.attrib['method'] = 'post' form.attrib['accept-charset'] = 'UTF-8' form.attrib['enctype'] = 'application/x-www-form-urlencoded' for name, value in self.toPostArgs().items(): attrs = { 'type': 'hidden', 'name': oidutil.toUnicode(name), 'value': oidutil.toUnicode(value) } form.append(ElementTree.Element('input', attrs)) submit = ElementTree.Element( 'input', {'type': 'submit', 'value': oidutil.toUnicode(submit_text)}) form.append(submit) return str(ElementTree.tostring(form, encoding='utf-8'), encoding="utf-8")
python
def toFormMarkup(self, action_url, form_tag_attrs=None, submit_text="Continue"): """Generate HTML form markup that contains the values in this message, to be HTTP POSTed as x-www-form-urlencoded UTF-8. @param action_url: The URL to which the form will be POSTed @type action_url: str @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. @type form_tag_attrs: {unicode: unicode} @param submit_text: The text that will appear on the submit button for this form. @type submit_text: unicode @returns: A string containing (X)HTML markup for a form that encodes the values in this Message object. @rtype: str """ if ElementTree is None: raise RuntimeError('This function requires ElementTree.') assert action_url is not None form = ElementTree.Element('form') if form_tag_attrs: for name, attr in form_tag_attrs.items(): form.attrib[name] = attr form.attrib['action'] = oidutil.toUnicode(action_url) form.attrib['method'] = 'post' form.attrib['accept-charset'] = 'UTF-8' form.attrib['enctype'] = 'application/x-www-form-urlencoded' for name, value in self.toPostArgs().items(): attrs = { 'type': 'hidden', 'name': oidutil.toUnicode(name), 'value': oidutil.toUnicode(value) } form.append(ElementTree.Element('input', attrs)) submit = ElementTree.Element( 'input', {'type': 'submit', 'value': oidutil.toUnicode(submit_text)}) form.append(submit) return str(ElementTree.tostring(form, encoding='utf-8'), encoding="utf-8")
Generate HTML form markup that contains the values in this message, to be HTTP POSTed as x-www-form-urlencoded UTF-8. @param action_url: The URL to which the form will be POSTed @type action_url: str @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. @type form_tag_attrs: {unicode: unicode} @param submit_text: The text that will appear on the submit button for this form. @type submit_text: unicode @returns: A string containing (X)HTML markup for a form that encodes the values in this Message object. @rtype: str
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L328-L383
necaris/python3-openid
openid/message.py
Message.toURLEncoded
def toURLEncoded(self): """Generate an x-www-urlencoded string""" args = sorted(self.toPostArgs().items()) return urllib.parse.urlencode(args)
python
def toURLEncoded(self): """Generate an x-www-urlencoded string""" args = sorted(self.toPostArgs().items()) return urllib.parse.urlencode(args)
Generate an x-www-urlencoded string
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L397-L400
necaris/python3-openid
openid/message.py
Message._fixNS
def _fixNS(self, namespace): """Convert an input value into the internally used values of this object @param namespace: The string or constant to convert @type namespace: str or unicode or BARE_NS or OPENID_NS """ if isinstance(namespace, bytes): namespace = str(namespace, encoding="utf-8") if namespace == OPENID_NS: if self._openid_ns_uri is None: raise UndefinedOpenIDNamespace('OpenID namespace not set') else: namespace = self._openid_ns_uri if namespace != BARE_NS and not isinstance(namespace, str): raise TypeError( "Namespace must be BARE_NS, OPENID_NS or a string. got %r" % (namespace, )) if namespace != BARE_NS and ':' not in namespace: fmt = 'OpenID 2.0 namespace identifiers SHOULD be URIs. Got %r' warnings.warn(fmt % (namespace, ), DeprecationWarning) if namespace == 'sreg': fmt = 'Using %r instead of "sreg" as namespace' warnings.warn( fmt % (SREG_URI, ), DeprecationWarning, ) return SREG_URI return namespace
python
def _fixNS(self, namespace): """Convert an input value into the internally used values of this object @param namespace: The string or constant to convert @type namespace: str or unicode or BARE_NS or OPENID_NS """ if isinstance(namespace, bytes): namespace = str(namespace, encoding="utf-8") if namespace == OPENID_NS: if self._openid_ns_uri is None: raise UndefinedOpenIDNamespace('OpenID namespace not set') else: namespace = self._openid_ns_uri if namespace != BARE_NS and not isinstance(namespace, str): raise TypeError( "Namespace must be BARE_NS, OPENID_NS or a string. got %r" % (namespace, )) if namespace != BARE_NS and ':' not in namespace: fmt = 'OpenID 2.0 namespace identifiers SHOULD be URIs. Got %r' warnings.warn(fmt % (namespace, ), DeprecationWarning) if namespace == 'sreg': fmt = 'Using %r instead of "sreg" as namespace' warnings.warn( fmt % (SREG_URI, ), DeprecationWarning, ) return SREG_URI return namespace
Convert an input value into the internally used values of this object @param namespace: The string or constant to convert @type namespace: str or unicode or BARE_NS or OPENID_NS
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L402-L434
necaris/python3-openid
openid/message.py
Message.getArgs
def getArgs(self, namespace): """Get the arguments that are defined for this namespace URI @returns: mapping from namespaced keys to values @returntype: dict of {str:bytes} """ namespace = self._fixNS(namespace) args = [] for ((pair_ns, ns_key), value) in self.args.items(): if pair_ns == namespace: if isinstance(ns_key, bytes): k = str(ns_key, encoding="utf-8") else: k = ns_key if isinstance(value, bytes): v = str(value, encoding="utf-8") else: v = value args.append((k, v)) return dict(args)
python
def getArgs(self, namespace): """Get the arguments that are defined for this namespace URI @returns: mapping from namespaced keys to values @returntype: dict of {str:bytes} """ namespace = self._fixNS(namespace) args = [] for ((pair_ns, ns_key), value) in self.args.items(): if pair_ns == namespace: if isinstance(ns_key, bytes): k = str(ns_key, encoding="utf-8") else: k = ns_key if isinstance(value, bytes): v = str(value, encoding="utf-8") else: v = value args.append((k, v)) return dict(args)
Get the arguments that are defined for this namespace URI @returns: mapping from namespaced keys to values @returntype: dict of {str:bytes}
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L488-L507
necaris/python3-openid
openid/message.py
Message.setArg
def setArg(self, namespace, key, value): """Set a single argument in this namespace""" assert key is not None assert value is not None namespace = self._fixNS(namespace) # try to ensure that internally it's consistent, at least: str -> str if isinstance(value, bytes): value = str(value, encoding="utf-8") self.args[(namespace, key)] = value if not (namespace is BARE_NS): self.namespaces.add(namespace)
python
def setArg(self, namespace, key, value): """Set a single argument in this namespace""" assert key is not None assert value is not None namespace = self._fixNS(namespace) # try to ensure that internally it's consistent, at least: str -> str if isinstance(value, bytes): value = str(value, encoding="utf-8") self.args[(namespace, key)] = value if not (namespace is BARE_NS): self.namespaces.add(namespace)
Set a single argument in this namespace
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L519-L529
necaris/python3-openid
openid/message.py
NamespaceMap.addAlias
def addAlias(self, namespace_uri, desired_alias, implicit=False): """Add an alias from this namespace URI to the desired alias """ if isinstance(namespace_uri, bytes): namespace_uri = str(namespace_uri, encoding="utf-8") # Check that desired_alias is not an openid protocol field as # per the spec. assert desired_alias not in OPENID_PROTOCOL_FIELDS, \ "%r is not an allowed namespace alias" % (desired_alias,) # Check that desired_alias does not contain a period as per # the spec. if isinstance(desired_alias, str): assert '.' not in desired_alias, \ "%r must not contain a dot" % (desired_alias,) # Check that there is not a namespace already defined for # the desired alias current_namespace_uri = self.alias_to_namespace.get(desired_alias) if (current_namespace_uri is not None and current_namespace_uri != namespace_uri): fmt = ('Cannot map %r to alias %r. ' '%r is already mapped to alias %r') msg = fmt % (namespace_uri, desired_alias, current_namespace_uri, desired_alias) raise KeyError(msg) # Check that there is not already a (different) alias for # this namespace URI alias = self.namespace_to_alias.get(namespace_uri) if alias is not None and alias != desired_alias: fmt = ('Cannot map %r to alias %r. ' 'It is already mapped to alias %r') raise KeyError(fmt % (namespace_uri, desired_alias, alias)) assert (desired_alias == NULL_NAMESPACE or type(desired_alias) in [str, str]), repr(desired_alias) assert namespace_uri not in self.implicit_namespaces self.alias_to_namespace[desired_alias] = namespace_uri self.namespace_to_alias[namespace_uri] = desired_alias if implicit: self.implicit_namespaces.append(namespace_uri) return desired_alias
python
def addAlias(self, namespace_uri, desired_alias, implicit=False): """Add an alias from this namespace URI to the desired alias """ if isinstance(namespace_uri, bytes): namespace_uri = str(namespace_uri, encoding="utf-8") # Check that desired_alias is not an openid protocol field as # per the spec. assert desired_alias not in OPENID_PROTOCOL_FIELDS, \ "%r is not an allowed namespace alias" % (desired_alias,) # Check that desired_alias does not contain a period as per # the spec. if isinstance(desired_alias, str): assert '.' not in desired_alias, \ "%r must not contain a dot" % (desired_alias,) # Check that there is not a namespace already defined for # the desired alias current_namespace_uri = self.alias_to_namespace.get(desired_alias) if (current_namespace_uri is not None and current_namespace_uri != namespace_uri): fmt = ('Cannot map %r to alias %r. ' '%r is already mapped to alias %r') msg = fmt % (namespace_uri, desired_alias, current_namespace_uri, desired_alias) raise KeyError(msg) # Check that there is not already a (different) alias for # this namespace URI alias = self.namespace_to_alias.get(namespace_uri) if alias is not None and alias != desired_alias: fmt = ('Cannot map %r to alias %r. ' 'It is already mapped to alias %r') raise KeyError(fmt % (namespace_uri, desired_alias, alias)) assert (desired_alias == NULL_NAMESPACE or type(desired_alias) in [str, str]), repr(desired_alias) assert namespace_uri not in self.implicit_namespaces self.alias_to_namespace[desired_alias] = namespace_uri self.namespace_to_alias[namespace_uri] = desired_alias if implicit: self.implicit_namespaces.append(namespace_uri) return desired_alias
Add an alias from this namespace URI to the desired alias
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/message.py#L604-L648
necaris/python3-openid
openid/yadis/xrires.py
_appendArgs
def _appendArgs(url, args): """Append some arguments to an HTTP query. """ # to be merged with oidutil.appendArgs when we combine the projects. if hasattr(args, 'items'): args = list(args.items()) args.sort() if len(args) == 0: return url # According to XRI Resolution section "QXRI query parameters": # # """If the original QXRI had a null query component (only a leading # question mark), or a query component consisting of only question # marks, one additional leading question mark MUST be added when # adding any XRI resolution parameters.""" if '?' in url.rstrip('?'): sep = '&' else: sep = '?' return '%s%s%s' % (url, sep, urlencode(args))
python
def _appendArgs(url, args): """Append some arguments to an HTTP query. """ # to be merged with oidutil.appendArgs when we combine the projects. if hasattr(args, 'items'): args = list(args.items()) args.sort() if len(args) == 0: return url # According to XRI Resolution section "QXRI query parameters": # # """If the original QXRI had a null query component (only a leading # question mark), or a query component consisting of only question # marks, one additional leading question mark MUST be added when # adding any XRI resolution parameters.""" if '?' in url.rstrip('?'): sep = '&' else: sep = '?' return '%s%s%s' % (url, sep, urlencode(args))
Append some arguments to an HTTP query.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/yadis/xrires.py#L100-L123
necaris/python3-openid
examples/djopenid/util.py
getOpenIDStore
def getOpenIDStore(filestore_path, table_prefix): """ Returns an OpenID association store object based on the database engine chosen for this Django application. * If no database engine is chosen, a filesystem-based store will be used whose path is filestore_path. * If a database engine is chosen, a store object for that database type will be returned. * If the chosen engine is not supported by the OpenID library, raise ImproperlyConfigured. * If a database store is used, this will create the tables necessary to use it. The table names will be prefixed with table_prefix. DO NOT use the same table prefix for both an OpenID consumer and an OpenID server in the same database. The result of this function should be passed to the Consumer constructor as the store parameter. """ db_engine = settings.DATABASES['default']['ENGINE'] if not db_engine: return FileOpenIDStore(filestore_path) # Possible side-effect: create a database connection if one isn't # already open. connection.cursor() # Create table names to specify for SQL-backed stores. tablenames = { 'associations_table': table_prefix + 'openid_associations', 'nonces_table': table_prefix + 'openid_nonces', } types = { 'django.db.backends.postgresql_psycopg2': sqlstore.PostgreSQLStore, 'django.db.backends.mysql': sqlstore.MySQLStore, 'django.db.backends.sqlite3': sqlstore.SQLiteStore, } if db_engine not in types: raise ImproperlyConfigured( "Database engine %s not supported by OpenID library" % db_engine) s = types[db_engine](connection.connection, **tablenames) try: s.createTables() except (SystemExit, KeyboardInterrupt, MemoryError): raise except: # XXX This is not the Right Way to do this, but because the # underlying database implementation might differ in behavior # at this point, we can't reliably catch the right # exception(s) here. Ideally, the SQL store in the OpenID # library would catch exceptions that it expects and fail # silently, but that could be bad, too. More ideally, the SQL # store would not attempt to create tables it knows already # exists. pass return s
python
def getOpenIDStore(filestore_path, table_prefix): """ Returns an OpenID association store object based on the database engine chosen for this Django application. * If no database engine is chosen, a filesystem-based store will be used whose path is filestore_path. * If a database engine is chosen, a store object for that database type will be returned. * If the chosen engine is not supported by the OpenID library, raise ImproperlyConfigured. * If a database store is used, this will create the tables necessary to use it. The table names will be prefixed with table_prefix. DO NOT use the same table prefix for both an OpenID consumer and an OpenID server in the same database. The result of this function should be passed to the Consumer constructor as the store parameter. """ db_engine = settings.DATABASES['default']['ENGINE'] if not db_engine: return FileOpenIDStore(filestore_path) # Possible side-effect: create a database connection if one isn't # already open. connection.cursor() # Create table names to specify for SQL-backed stores. tablenames = { 'associations_table': table_prefix + 'openid_associations', 'nonces_table': table_prefix + 'openid_nonces', } types = { 'django.db.backends.postgresql_psycopg2': sqlstore.PostgreSQLStore, 'django.db.backends.mysql': sqlstore.MySQLStore, 'django.db.backends.sqlite3': sqlstore.SQLiteStore, } if db_engine not in types: raise ImproperlyConfigured( "Database engine %s not supported by OpenID library" % db_engine) s = types[db_engine](connection.connection, **tablenames) try: s.createTables() except (SystemExit, KeyboardInterrupt, MemoryError): raise except: # XXX This is not the Right Way to do this, but because the # underlying database implementation might differ in behavior # at this point, we can't reliably catch the right # exception(s) here. Ideally, the SQL store in the OpenID # library would catch exceptions that it expects and fail # silently, but that could be bad, too. More ideally, the SQL # store would not attempt to create tables it knows already # exists. pass return s
Returns an OpenID association store object based on the database engine chosen for this Django application. * If no database engine is chosen, a filesystem-based store will be used whose path is filestore_path. * If a database engine is chosen, a store object for that database type will be returned. * If the chosen engine is not supported by the OpenID library, raise ImproperlyConfigured. * If a database store is used, this will create the tables necessary to use it. The table names will be prefixed with table_prefix. DO NOT use the same table prefix for both an OpenID consumer and an OpenID server in the same database. The result of this function should be passed to the Consumer constructor as the store parameter.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/examples/djopenid/util.py#L27-L91
necaris/python3-openid
examples/djopenid/util.py
renderXRDS
def renderXRDS(request, type_uris, endpoint_urls): """Render an XRDS page with the specified type URIs and endpoint URLs in one service block, and return a response with the appropriate content-type. """ response = render_to_response( 'xrds.xml', {'type_uris': type_uris, 'endpoint_urls': endpoint_urls}, context_instance=RequestContext(request)) response['Content-Type'] = YADIS_CONTENT_TYPE return response
python
def renderXRDS(request, type_uris, endpoint_urls): """Render an XRDS page with the specified type URIs and endpoint URLs in one service block, and return a response with the appropriate content-type. """ response = render_to_response( 'xrds.xml', {'type_uris': type_uris, 'endpoint_urls': endpoint_urls}, context_instance=RequestContext(request)) response['Content-Type'] = YADIS_CONTENT_TYPE return response
Render an XRDS page with the specified type URIs and endpoint URLs in one service block, and return a response with the appropriate content-type.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/examples/djopenid/util.py#L147-L157
necaris/python3-openid
openid/codecutil.py
_pct_escape_handler
def _pct_escape_handler(err): ''' Encoding error handler that does percent-escaping of Unicode, to be used with codecs.register_error TODO: replace use of this with urllib.parse.quote as appropriate ''' chunk = err.object[err.start:err.end] replacements = _pct_encoded_replacements(chunk) return ("".join(replacements), err.end)
python
def _pct_escape_handler(err): ''' Encoding error handler that does percent-escaping of Unicode, to be used with codecs.register_error TODO: replace use of this with urllib.parse.quote as appropriate ''' chunk = err.object[err.start:err.end] replacements = _pct_encoded_replacements(chunk) return ("".join(replacements), err.end)
Encoding error handler that does percent-escaping of Unicode, to be used with codecs.register_error TODO: replace use of this with urllib.parse.quote as appropriate
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/codecutil.py#L80-L88
necaris/python3-openid
openid/kvform.py
seqToKV
def seqToKV(seq, strict=False): """Represent a sequence of pairs of strings as newline-terminated key:value pairs. The pairs are generated in the order given. @param seq: The pairs @type seq: [(str, (unicode|str))] @return: A string representation of the sequence @rtype: bytes """ def err(msg): formatted = 'seqToKV warning: %s: %r' % (msg, seq) if strict: raise KVFormError(formatted) else: logging.warning(formatted) lines = [] for k, v in seq: if isinstance(k, bytes): k = k.decode('utf-8') elif not isinstance(k, str): err('Converting key to string: %r' % k) k = str(k) if '\n' in k: raise KVFormError( 'Invalid input for seqToKV: key contains newline: %r' % (k, )) if ':' in k: raise KVFormError( 'Invalid input for seqToKV: key contains colon: %r' % (k, )) if k.strip() != k: err('Key has whitespace at beginning or end: %r' % (k, )) if isinstance(v, bytes): v = v.decode('utf-8') elif not isinstance(v, str): err('Converting value to string: %r' % (v, )) v = str(v) if '\n' in v: raise KVFormError( 'Invalid input for seqToKV: value contains newline: %r' % (v, )) if v.strip() != v: err('Value has whitespace at beginning or end: %r' % (v, )) lines.append(k + ':' + v + '\n') return ''.join(lines).encode('utf-8')
python
def seqToKV(seq, strict=False): """Represent a sequence of pairs of strings as newline-terminated key:value pairs. The pairs are generated in the order given. @param seq: The pairs @type seq: [(str, (unicode|str))] @return: A string representation of the sequence @rtype: bytes """ def err(msg): formatted = 'seqToKV warning: %s: %r' % (msg, seq) if strict: raise KVFormError(formatted) else: logging.warning(formatted) lines = [] for k, v in seq: if isinstance(k, bytes): k = k.decode('utf-8') elif not isinstance(k, str): err('Converting key to string: %r' % k) k = str(k) if '\n' in k: raise KVFormError( 'Invalid input for seqToKV: key contains newline: %r' % (k, )) if ':' in k: raise KVFormError( 'Invalid input for seqToKV: key contains colon: %r' % (k, )) if k.strip() != k: err('Key has whitespace at beginning or end: %r' % (k, )) if isinstance(v, bytes): v = v.decode('utf-8') elif not isinstance(v, str): err('Converting value to string: %r' % (v, )) v = str(v) if '\n' in v: raise KVFormError( 'Invalid input for seqToKV: value contains newline: %r' % (v, )) if v.strip() != v: err('Value has whitespace at beginning or end: %r' % (v, )) lines.append(k + ':' + v + '\n') return ''.join(lines).encode('utf-8')
Represent a sequence of pairs of strings as newline-terminated key:value pairs. The pairs are generated in the order given. @param seq: The pairs @type seq: [(str, (unicode|str))] @return: A string representation of the sequence @rtype: bytes
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/kvform.py#L10-L63
necaris/python3-openid
openid/yadis/xri.py
iriToURI
def iriToURI(iri): """Transform an IRI to a URI by escaping unicode.""" # According to RFC 3987, section 3.1, "Mapping of IRIs to URIs" if isinstance(iri, bytes): iri = str(iri, encoding="utf-8") return iri.encode('ascii', errors='oid_percent_escape').decode()
python
def iriToURI(iri): """Transform an IRI to a URI by escaping unicode.""" # According to RFC 3987, section 3.1, "Mapping of IRIs to URIs" if isinstance(iri, bytes): iri = str(iri, encoding="utf-8") return iri.encode('ascii', errors='oid_percent_escape').decode()
Transform an IRI to a URI by escaping unicode.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/yadis/xri.py#L59-L64
necaris/python3-openid
openid/urinorm.py
urinorm
def urinorm(uri): ''' Normalize a URI ''' # TODO: use urllib.parse instead of these complex regular expressions if isinstance(uri, bytes): uri = str(uri, encoding='utf-8') uri = uri.encode('ascii', errors='oid_percent_escape').decode('utf-8') # _escapeme_re.sub(_pct_escape_unicode, uri).encode('ascii').decode() illegal_mo = uri_illegal_char_re.search(uri) if illegal_mo: raise ValueError('Illegal characters in URI: %r at position %s' % (illegal_mo.group(), illegal_mo.start())) uri_mo = uri_re.match(uri) scheme = uri_mo.group(2) if scheme is None: raise ValueError('No scheme specified') scheme = scheme.lower() if scheme not in ('http', 'https'): raise ValueError('Not an absolute HTTP or HTTPS URI: %r' % (uri, )) authority = uri_mo.group(4) if authority is None: raise ValueError('Not an absolute URI: %r' % (uri, )) authority_mo = authority_re.match(authority) if authority_mo is None: raise ValueError('URI does not have a valid authority: %r' % (uri, )) userinfo, host, port = authority_mo.groups() if userinfo is None: userinfo = '' if '%' in host: host = host.lower() host = pct_encoded_re.sub(_pct_encoded_replace, host) host = host.encode('idna').decode() else: host = host.lower() if port: if (port == ':' or (scheme == 'http' and port == ':80') or (scheme == 'https' and port == ':443')): port = '' else: port = '' authority = userinfo + host + port path = uri_mo.group(5) path = pct_encoded_re.sub(_pct_encoded_replace_unreserved, path) path = remove_dot_segments(path) if not path: path = '/' query = uri_mo.group(6) if query is None: query = '' fragment = uri_mo.group(8) if fragment is None: fragment = '' return scheme + '://' + authority + path + query + fragment
python
def urinorm(uri): ''' Normalize a URI ''' # TODO: use urllib.parse instead of these complex regular expressions if isinstance(uri, bytes): uri = str(uri, encoding='utf-8') uri = uri.encode('ascii', errors='oid_percent_escape').decode('utf-8') # _escapeme_re.sub(_pct_escape_unicode, uri).encode('ascii').decode() illegal_mo = uri_illegal_char_re.search(uri) if illegal_mo: raise ValueError('Illegal characters in URI: %r at position %s' % (illegal_mo.group(), illegal_mo.start())) uri_mo = uri_re.match(uri) scheme = uri_mo.group(2) if scheme is None: raise ValueError('No scheme specified') scheme = scheme.lower() if scheme not in ('http', 'https'): raise ValueError('Not an absolute HTTP or HTTPS URI: %r' % (uri, )) authority = uri_mo.group(4) if authority is None: raise ValueError('Not an absolute URI: %r' % (uri, )) authority_mo = authority_re.match(authority) if authority_mo is None: raise ValueError('URI does not have a valid authority: %r' % (uri, )) userinfo, host, port = authority_mo.groups() if userinfo is None: userinfo = '' if '%' in host: host = host.lower() host = pct_encoded_re.sub(_pct_encoded_replace, host) host = host.encode('idna').decode() else: host = host.lower() if port: if (port == ':' or (scheme == 'http' and port == ':80') or (scheme == 'https' and port == ':443')): port = '' else: port = '' authority = userinfo + host + port path = uri_mo.group(5) path = pct_encoded_re.sub(_pct_encoded_replace_unreserved, path) path = remove_dot_segments(path) if not path: path = '/' query = uri_mo.group(6) if query is None: query = '' fragment = uri_mo.group(8) if fragment is None: fragment = '' return scheme + '://' + authority + path + query + fragment
Normalize a URI
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/urinorm.py#L92-L161
necaris/python3-openid
examples/djopenid/server/views.py
server
def server(request): """ Respond to requests for the server's primary web page. """ return render_to_response( 'server/index.html', { 'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds), }, context_instance=RequestContext(request))
python
def server(request): """ Respond to requests for the server's primary web page. """ return render_to_response( 'server/index.html', { 'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds), }, context_instance=RequestContext(request))
Respond to requests for the server's primary web page.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/examples/djopenid/server/views.py#L68-L77
necaris/python3-openid
examples/djopenid/server/views.py
displayResponse
def displayResponse(request, openid_response): """ Display an OpenID response. Errors will be displayed directly to the user; successful responses and other protocol-level messages will be sent using the proper mechanism (i.e., direct response, redirection, etc.). """ s = getServer(request) # Encode the response into something that is renderable. try: webresponse = s.encodeResponse(openid_response) except EncodingError as why: # If it couldn't be encoded, display an error. text = why.response.encodeToKVForm() return render_to_response( 'server/endpoint.html', {'error': cgi.escape(text)}, context_instance=RequestContext(request)) # Construct the appropriate django framework response. r = http.HttpResponse(webresponse.body) r.status_code = webresponse.code for header, value in webresponse.headers.items(): r[header] = value return r
python
def displayResponse(request, openid_response): """ Display an OpenID response. Errors will be displayed directly to the user; successful responses and other protocol-level messages will be sent using the proper mechanism (i.e., direct response, redirection, etc.). """ s = getServer(request) # Encode the response into something that is renderable. try: webresponse = s.encodeResponse(openid_response) except EncodingError as why: # If it couldn't be encoded, display an error. text = why.response.encodeToKVForm() return render_to_response( 'server/endpoint.html', {'error': cgi.escape(text)}, context_instance=RequestContext(request)) # Construct the appropriate django framework response. r = http.HttpResponse(webresponse.body) r.status_code = webresponse.code for header, value in webresponse.headers.items(): r[header] = value return r
Display an OpenID response. Errors will be displayed directly to the user; successful responses and other protocol-level messages will be sent using the proper mechanism (i.e., direct response, redirection, etc.).
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/examples/djopenid/server/views.py#L261-L287
necaris/python3-openid
openid/store/filestore.py
_removeIfPresent
def _removeIfPresent(filename): """Attempt to remove a file, returning whether the file existed at the time of the call. str -> bool """ try: os.unlink(filename) except OSError as why: if why.errno == ENOENT: # Someone beat us to it, but it's gone, so that's OK return 0 else: raise else: # File was present return 1
python
def _removeIfPresent(filename): """Attempt to remove a file, returning whether the file existed at the time of the call. str -> bool """ try: os.unlink(filename) except OSError as why: if why.errno == ENOENT: # Someone beat us to it, but it's gone, so that's OK return 0 else: raise else: # File was present return 1
Attempt to remove a file, returning whether the file existed at the time of the call. str -> bool
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/store/filestore.py#L45-L61
necaris/python3-openid
openid/store/filestore.py
FileOpenIDStore.storeAssociation
def storeAssociation(self, server_url, association): """Store an association in the association directory. (str, Association) -> NoneType """ association_s = association.serialize() # NOTE: UTF-8 encoded bytes filename = self.getAssociationFilename(server_url, association.handle) tmp_file, tmp = self._mktemp() try: try: tmp_file.write(association_s) os.fsync(tmp_file.fileno()) finally: tmp_file.close() try: os.rename(tmp, filename) except OSError as why: if why.errno != EEXIST: raise # We only expect EEXIST to happen only on Windows. It's # possible that we will succeed in unlinking the existing # file, but not in putting the temporary file in place. try: os.unlink(filename) except OSError as why: if why.errno == ENOENT: pass else: raise # Now the target should not exist. Try renaming again, # giving up if it fails. os.rename(tmp, filename) except: # If there was an error, don't leave the temporary file # around. _removeIfPresent(tmp) raise
python
def storeAssociation(self, server_url, association): """Store an association in the association directory. (str, Association) -> NoneType """ association_s = association.serialize() # NOTE: UTF-8 encoded bytes filename = self.getAssociationFilename(server_url, association.handle) tmp_file, tmp = self._mktemp() try: try: tmp_file.write(association_s) os.fsync(tmp_file.fileno()) finally: tmp_file.close() try: os.rename(tmp, filename) except OSError as why: if why.errno != EEXIST: raise # We only expect EEXIST to happen only on Windows. It's # possible that we will succeed in unlinking the existing # file, but not in putting the temporary file in place. try: os.unlink(filename) except OSError as why: if why.errno == ENOENT: pass else: raise # Now the target should not exist. Try renaming again, # giving up if it fails. os.rename(tmp, filename) except: # If there was an error, don't leave the temporary file # around. _removeIfPresent(tmp) raise
Store an association in the association directory. (str, Association) -> NoneType
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/store/filestore.py#L175-L215
necaris/python3-openid
examples/consumer.py
OpenIDRequestHandler.doVerify
def doVerify(self): """Process the form submission, initating OpenID verification. """ # First, make sure that the user entered something openid_url = self.query.get('openid_identifier') if not openid_url: self.render( 'Enter an OpenID Identifier to verify.', css_class='error', form_contents=openid_url) return immediate = 'immediate' in self.query use_sreg = 'use_sreg' in self.query use_pape = 'use_pape' in self.query use_stateless = 'use_stateless' in self.query oidconsumer = self.getConsumer(stateless=use_stateless) try: request = oidconsumer.begin(openid_url) except consumer.DiscoveryFailure as exc: fetch_error_string = 'Error in discovery: %s' % ( cgi.escape(str(exc))) self.render( fetch_error_string, css_class='error', form_contents=openid_url) else: if request is None: msg = 'No OpenID services found for <code>%s</code>' % ( cgi.escape(openid_url), ) self.render(msg, css_class='error', form_contents=openid_url) else: # Then, ask the library to begin the authorization. # Here we find out the identity server that will verify the # user's identity, and get a token that allows us to # communicate securely with the identity server. if use_sreg: self.requestRegistrationData(request) if use_pape: self.requestPAPEDetails(request) trust_root = self.server.base_url return_to = self.buildURL('process') if request.shouldSendRedirect(): redirect_url = request.redirectURL( trust_root, return_to, immediate=immediate) self.send_response(302) self.send_header('Location', redirect_url) self.writeUserHeader() self.end_headers() else: form_html = request.htmlMarkup( trust_root, return_to, form_tag_attrs={'id': 'openid_message'}, immediate=immediate) self.wfile.write(bytes(form_html, 'utf-8'))
python
def doVerify(self): """Process the form submission, initating OpenID verification. """ # First, make sure that the user entered something openid_url = self.query.get('openid_identifier') if not openid_url: self.render( 'Enter an OpenID Identifier to verify.', css_class='error', form_contents=openid_url) return immediate = 'immediate' in self.query use_sreg = 'use_sreg' in self.query use_pape = 'use_pape' in self.query use_stateless = 'use_stateless' in self.query oidconsumer = self.getConsumer(stateless=use_stateless) try: request = oidconsumer.begin(openid_url) except consumer.DiscoveryFailure as exc: fetch_error_string = 'Error in discovery: %s' % ( cgi.escape(str(exc))) self.render( fetch_error_string, css_class='error', form_contents=openid_url) else: if request is None: msg = 'No OpenID services found for <code>%s</code>' % ( cgi.escape(openid_url), ) self.render(msg, css_class='error', form_contents=openid_url) else: # Then, ask the library to begin the authorization. # Here we find out the identity server that will verify the # user's identity, and get a token that allows us to # communicate securely with the identity server. if use_sreg: self.requestRegistrationData(request) if use_pape: self.requestPAPEDetails(request) trust_root = self.server.base_url return_to = self.buildURL('process') if request.shouldSendRedirect(): redirect_url = request.redirectURL( trust_root, return_to, immediate=immediate) self.send_response(302) self.send_header('Location', redirect_url) self.writeUserHeader() self.end_headers() else: form_html = request.htmlMarkup( trust_root, return_to, form_tag_attrs={'id': 'openid_message'}, immediate=immediate) self.wfile.write(bytes(form_html, 'utf-8'))
Process the form submission, initating OpenID verification.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/examples/consumer.py#L160-L219
necaris/python3-openid
examples/consumer.py
OpenIDRequestHandler.buildURL
def buildURL(self, action, **query): """Build a URL relative to the server base_url, with the given query parameters added.""" base = urllib.parse.urljoin(self.server.base_url, action) return appendArgs(base, query)
python
def buildURL(self, action, **query): """Build a URL relative to the server base_url, with the given query parameters added.""" base = urllib.parse.urljoin(self.server.base_url, action) return appendArgs(base, query)
Build a URL relative to the server base_url, with the given query parameters added.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/examples/consumer.py#L357-L361
necaris/python3-openid
openid/server/server.py
AssociateRequest.answer
def answer(self, assoc): """Respond to this request with an X{association}. @param assoc: The association to send back. @type assoc: L{openid.association.Association} @returns: A response with the association information, encrypted to the consumer's X{public key} if appropriate. @returntype: L{OpenIDResponse} """ response = OpenIDResponse(self) response.fields.updateArgs(OPENID_NS, { 'expires_in': str(assoc.expiresIn), 'assoc_type': self.assoc_type, 'assoc_handle': assoc.handle, }) response.fields.updateArgs(OPENID_NS, self.session.answer(assoc.secret)) if not (self.session.session_type == 'no-encryption' and self.message.isOpenID1()): # The session type "no-encryption" did not have a name # in OpenID v1, it was just omitted. response.fields.setArg(OPENID_NS, 'session_type', self.session.session_type) return response
python
def answer(self, assoc): """Respond to this request with an X{association}. @param assoc: The association to send back. @type assoc: L{openid.association.Association} @returns: A response with the association information, encrypted to the consumer's X{public key} if appropriate. @returntype: L{OpenIDResponse} """ response = OpenIDResponse(self) response.fields.updateArgs(OPENID_NS, { 'expires_in': str(assoc.expiresIn), 'assoc_type': self.assoc_type, 'assoc_handle': assoc.handle, }) response.fields.updateArgs(OPENID_NS, self.session.answer(assoc.secret)) if not (self.session.session_type == 'no-encryption' and self.message.isOpenID1()): # The session type "no-encryption" did not have a name # in OpenID v1, it was just omitted. response.fields.setArg(OPENID_NS, 'session_type', self.session.session_type) return response
Respond to this request with an X{association}. @param assoc: The association to send back. @type assoc: L{openid.association.Association} @returns: A response with the association information, encrypted to the consumer's X{public key} if appropriate. @returntype: L{OpenIDResponse}
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/server/server.py#L456-L482
necaris/python3-openid
openid/server/server.py
OpenIDResponse.whichEncoding
def whichEncoding(self): """How should I be encoded? @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM. @change: 2.1.0 added the ENCODE_HTML_FORM response. """ if self.request.mode in BROWSER_REQUEST_MODES: if self.fields.getOpenIDNamespace() == OPENID2_NS and \ len(self.encodeToURL()) > OPENID1_URL_LIMIT: return ENCODE_HTML_FORM else: return ENCODE_URL else: return ENCODE_KVFORM
python
def whichEncoding(self): """How should I be encoded? @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM. @change: 2.1.0 added the ENCODE_HTML_FORM response. """ if self.request.mode in BROWSER_REQUEST_MODES: if self.fields.getOpenIDNamespace() == OPENID2_NS and \ len(self.encodeToURL()) > OPENID1_URL_LIMIT: return ENCODE_HTML_FORM else: return ENCODE_URL else: return ENCODE_KVFORM
How should I be encoded? @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM. @change: 2.1.0 added the ENCODE_HTML_FORM response.
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/server/server.py#L1042-L1056
necaris/python3-openid
openid/extensions/draft/pape5.py
PAPEExtension._generateAlias
def _generateAlias(self): """Return an unused auth level alias""" for i in range(1000): alias = 'cust%d' % (i, ) if alias not in self.auth_level_aliases: return alias raise RuntimeError('Could not find an unused alias (tried 1000!)')
python
def _generateAlias(self): """Return an unused auth level alias""" for i in range(1000): alias = 'cust%d' % (i, ) if alias not in self.auth_level_aliases: return alias raise RuntimeError('Could not find an unused alias (tried 1000!)')
Return an unused auth level alias
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/extensions/draft/pape5.py#L73-L80
necaris/python3-openid
openid/extensions/draft/pape5.py
PAPEExtension._getAlias
def _getAlias(self, auth_level_uri): """Return the alias for the specified auth level URI. @raises KeyError: if no alias is defined """ for (alias, existing_uri) in self.auth_level_aliases.items(): if auth_level_uri == existing_uri: return alias raise KeyError(auth_level_uri)
python
def _getAlias(self, auth_level_uri): """Return the alias for the specified auth level URI. @raises KeyError: if no alias is defined """ for (alias, existing_uri) in self.auth_level_aliases.items(): if auth_level_uri == existing_uri: return alias raise KeyError(auth_level_uri)
Return the alias for the specified auth level URI. @raises KeyError: if no alias is defined
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/extensions/draft/pape5.py#L82-L91
necaris/python3-openid
openid/yadis/filters.py
mkCompoundFilter
def mkCompoundFilter(parts): """Create a filter out of a list of filter-like things Used by mkFilter @param parts: list of filter, endpoint, callable or list of any of these """ # Separate into a list of callables and a list of filter objects transformers = [] filters = [] for subfilter in parts: try: subfilter = list(subfilter) except TypeError: # If it's not an iterable if hasattr(subfilter, 'getServiceEndpoints'): # It's a full filter filters.append(subfilter) elif hasattr(subfilter, 'fromBasicServiceEndpoint'): # It's an endpoint object, so put its endpoint # conversion attribute into the list of endpoint # transformers transformers.append(subfilter.fromBasicServiceEndpoint) elif isinstance(subfilter, collections.Callable): # It's a simple callable, so add it to the list of # endpoint transformers transformers.append(subfilter) else: raise filter_type_error else: filters.append(mkCompoundFilter(subfilter)) if transformers: filters.append(TransformFilterMaker(transformers)) if len(filters) == 1: return filters[0] else: return CompoundFilter(filters)
python
def mkCompoundFilter(parts): """Create a filter out of a list of filter-like things Used by mkFilter @param parts: list of filter, endpoint, callable or list of any of these """ # Separate into a list of callables and a list of filter objects transformers = [] filters = [] for subfilter in parts: try: subfilter = list(subfilter) except TypeError: # If it's not an iterable if hasattr(subfilter, 'getServiceEndpoints'): # It's a full filter filters.append(subfilter) elif hasattr(subfilter, 'fromBasicServiceEndpoint'): # It's an endpoint object, so put its endpoint # conversion attribute into the list of endpoint # transformers transformers.append(subfilter.fromBasicServiceEndpoint) elif isinstance(subfilter, collections.Callable): # It's a simple callable, so add it to the list of # endpoint transformers transformers.append(subfilter) else: raise filter_type_error else: filters.append(mkCompoundFilter(subfilter)) if transformers: filters.append(TransformFilterMaker(transformers)) if len(filters) == 1: return filters[0] else: return CompoundFilter(filters)
Create a filter out of a list of filter-like things Used by mkFilter @param parts: list of filter, endpoint, callable or list of any of these
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/yadis/filters.py#L172-L210
gawel/irc3
irc3/plugins/cron.py
cron
def cron(cronline, venusian_category='irc3.plugins.cron'): """main decorator""" def wrapper(func): def callback(context, name, ob): obj = context.context crons = obj.get_plugin(Crons) if info.scope == 'class': callback = getattr( obj.get_plugin(ob), func.__name__) else: callback = irc3.utils.wraps_with_context(func, obj) crons.add_cron(cronline, callback) info = venusian.attach(func, callback, category=venusian_category) return func return wrapper
python
def cron(cronline, venusian_category='irc3.plugins.cron'): """main decorator""" def wrapper(func): def callback(context, name, ob): obj = context.context crons = obj.get_plugin(Crons) if info.scope == 'class': callback = getattr( obj.get_plugin(ob), func.__name__) else: callback = irc3.utils.wraps_with_context(func, obj) crons.add_cron(cronline, callback) info = venusian.attach(func, callback, category=venusian_category) return func return wrapper
main decorator
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/cron.py#L83-L98
marselester/flask-api-utils
api_utils/app.py
ResponsiveFlask.default_errorhandler
def default_errorhandler(self, f): """Decorator that registers handler of default (Werkzeug) HTTP errors. Note that it might override already defined error handlers. """ for http_code in default_exceptions: self.error_handler_spec[None][http_code] = f return f
python
def default_errorhandler(self, f): """Decorator that registers handler of default (Werkzeug) HTTP errors. Note that it might override already defined error handlers. """ for http_code in default_exceptions: self.error_handler_spec[None][http_code] = f return f
Decorator that registers handler of default (Werkzeug) HTTP errors. Note that it might override already defined error handlers.
https://github.com/marselester/flask-api-utils/blob/f633e49e883c2f4e2523941e70b2d79ff4e138dc/api_utils/app.py#L46-L54
marselester/flask-api-utils
api_utils/app.py
ResponsiveFlask._response_mimetype_based_on_accept_header
def _response_mimetype_based_on_accept_header(self): """Determines mimetype to response based on Accept header. If mimetype is not found, it returns ``None``. """ response_mimetype = None if not request.accept_mimetypes: response_mimetype = self.default_mimetype else: all_media_types_wildcard = '*/*' for mimetype, q in request.accept_mimetypes: if mimetype == all_media_types_wildcard: response_mimetype = self.default_mimetype break if mimetype in self.response_formatters: response_mimetype = mimetype break return response_mimetype
python
def _response_mimetype_based_on_accept_header(self): """Determines mimetype to response based on Accept header. If mimetype is not found, it returns ``None``. """ response_mimetype = None if not request.accept_mimetypes: response_mimetype = self.default_mimetype else: all_media_types_wildcard = '*/*' for mimetype, q in request.accept_mimetypes: if mimetype == all_media_types_wildcard: response_mimetype = self.default_mimetype break if mimetype in self.response_formatters: response_mimetype = mimetype break return response_mimetype
Determines mimetype to response based on Accept header. If mimetype is not found, it returns ``None``.
https://github.com/marselester/flask-api-utils/blob/f633e49e883c2f4e2523941e70b2d79ff4e138dc/api_utils/app.py#L56-L77
marselester/flask-api-utils
api_utils/app.py
ResponsiveFlask.make_response
def make_response(self, rv): """Returns response based on Accept header. If no Accept header field is present, then it is assumed that the client accepts all media types. This way JSON format will be used. If an Accept header field is present, and if the server cannot send a response which is acceptable according to the combined Accept field value, then a 406 (not acceptable) response will be sent. """ status = headers = None if isinstance(rv, tuple): rv, status, headers = rv + (None,) * (3 - len(rv)) response_mimetype = self._response_mimetype_based_on_accept_header() if response_mimetype is None: # Return 406, list of available mimetypes in default format. default_formatter = self.response_formatters.get( self.default_mimetype ) available_mimetypes = default_formatter( mimetypes=list(self.response_formatters) ) rv = self.response_class( response=available_mimetypes, status=406, mimetype=self.default_mimetype, ) elif isinstance(rv, dict): formatter = self.response_formatters.get(response_mimetype) rv = self.response_class( response=formatter(**rv), mimetype=response_mimetype, ) return super(ResponsiveFlask, self).make_response( rv=(rv, status, headers) )
python
def make_response(self, rv): """Returns response based on Accept header. If no Accept header field is present, then it is assumed that the client accepts all media types. This way JSON format will be used. If an Accept header field is present, and if the server cannot send a response which is acceptable according to the combined Accept field value, then a 406 (not acceptable) response will be sent. """ status = headers = None if isinstance(rv, tuple): rv, status, headers = rv + (None,) * (3 - len(rv)) response_mimetype = self._response_mimetype_based_on_accept_header() if response_mimetype is None: # Return 406, list of available mimetypes in default format. default_formatter = self.response_formatters.get( self.default_mimetype ) available_mimetypes = default_formatter( mimetypes=list(self.response_formatters) ) rv = self.response_class( response=available_mimetypes, status=406, mimetype=self.default_mimetype, ) elif isinstance(rv, dict): formatter = self.response_formatters.get(response_mimetype) rv = self.response_class( response=formatter(**rv), mimetype=response_mimetype, ) return super(ResponsiveFlask, self).make_response( rv=(rv, status, headers) )
Returns response based on Accept header. If no Accept header field is present, then it is assumed that the client accepts all media types. This way JSON format will be used. If an Accept header field is present, and if the server cannot send a response which is acceptable according to the combined Accept field value, then a 406 (not acceptable) response will be sent.
https://github.com/marselester/flask-api-utils/blob/f633e49e883c2f4e2523941e70b2d79ff4e138dc/api_utils/app.py#L79-L120
gawel/irc3
irc3/dec.py
dcc_event
def dcc_event(regexp, callback=None, iotype='in', venusian_category='irc3.dcc'): """Work like :class:`~irc3.dec.event` but occurs during DCC CHATs""" return event(regexp, callback=callback, iotype='dcc_' + iotype, venusian_category=venusian_category)
python
def dcc_event(regexp, callback=None, iotype='in', venusian_category='irc3.dcc'): """Work like :class:`~irc3.dec.event` but occurs during DCC CHATs""" return event(regexp, callback=callback, iotype='dcc_' + iotype, venusian_category=venusian_category)
Work like :class:`~irc3.dec.event` but occurs during DCC CHATs
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/dec.py#L85-L89
gawel/irc3
irc3/dec.py
extend
def extend(func): """Allow to extend a bot: Create a module with some useful routine: .. literalinclude:: ../examples/myextends.py .. >>> import sys >>> sys.path.append('examples') >>> from irc3 import IrcBot >>> IrcBot.defaults.update(asynchronous=False, testing=True) Now you can use those routine in your bot:: >>> bot = IrcBot() >>> bot.include('myextends') >>> print(bot.my_usefull_function(1)) my_usefull_function(*(1,)) >>> print(bot.my_usefull_method(2)) my_usefull_method(*(2,)) """ def callback(context, name, ob): obj = context.context if info.scope == 'class': f = getattr(obj.get_plugin(ob), func.__name__) else: f = func setattr(obj, f.__name__, f.__get__(obj, obj.__class__)) info = venusian.attach(func, callback, category='irc3.extend') return func
python
def extend(func): """Allow to extend a bot: Create a module with some useful routine: .. literalinclude:: ../examples/myextends.py .. >>> import sys >>> sys.path.append('examples') >>> from irc3 import IrcBot >>> IrcBot.defaults.update(asynchronous=False, testing=True) Now you can use those routine in your bot:: >>> bot = IrcBot() >>> bot.include('myextends') >>> print(bot.my_usefull_function(1)) my_usefull_function(*(1,)) >>> print(bot.my_usefull_method(2)) my_usefull_method(*(2,)) """ def callback(context, name, ob): obj = context.context if info.scope == 'class': f = getattr(obj.get_plugin(ob), func.__name__) else: f = func setattr(obj, f.__name__, f.__get__(obj, obj.__class__)) info = venusian.attach(func, callback, category='irc3.extend') return func
Allow to extend a bot: Create a module with some useful routine: .. literalinclude:: ../examples/myextends.py .. >>> import sys >>> sys.path.append('examples') >>> from irc3 import IrcBot >>> IrcBot.defaults.update(asynchronous=False, testing=True) Now you can use those routine in your bot:: >>> bot = IrcBot() >>> bot.include('myextends') >>> print(bot.my_usefull_function(1)) my_usefull_function(*(1,)) >>> print(bot.my_usefull_method(2)) my_usefull_method(*(2,))
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/dec.py#L92-L122
gawel/irc3
irc3d/__init__.py
IrcServer.notice
def notice(self, client, message): """send a notice to client""" if client and message: messages = utils.split_message(message, self.config.max_length) for msg in messages: client.fwrite(':{c.srv} NOTICE {c.nick} :{msg}', msg=msg)
python
def notice(self, client, message): """send a notice to client""" if client and message: messages = utils.split_message(message, self.config.max_length) for msg in messages: client.fwrite(':{c.srv} NOTICE {c.nick} :{msg}', msg=msg)
send a notice to client
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3d/__init__.py#L168-L173
marselester/flask-api-utils
api_utils/auth.py
Hawk.client_key_loader
def client_key_loader(self, f): """Registers a function to be called to find a client key. Function you set has to take a client id and return a client key:: @hawk.client_key_loader def get_client_key(client_id): if client_id == 'Alice': return 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn' else: raise LookupError() :param f: The callback for retrieving a client key. """ @wraps(f) def wrapped_f(client_id): client_key = f(client_id) return { 'id': client_id, 'key': client_key, 'algorithm': current_app.config['HAWK_ALGORITHM'] } self._client_key_loader_func = wrapped_f return wrapped_f
python
def client_key_loader(self, f): """Registers a function to be called to find a client key. Function you set has to take a client id and return a client key:: @hawk.client_key_loader def get_client_key(client_id): if client_id == 'Alice': return 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn' else: raise LookupError() :param f: The callback for retrieving a client key. """ @wraps(f) def wrapped_f(client_id): client_key = f(client_id) return { 'id': client_id, 'key': client_key, 'algorithm': current_app.config['HAWK_ALGORITHM'] } self._client_key_loader_func = wrapped_f return wrapped_f
Registers a function to be called to find a client key. Function you set has to take a client id and return a client key:: @hawk.client_key_loader def get_client_key(client_id): if client_id == 'Alice': return 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn' else: raise LookupError() :param f: The callback for retrieving a client key.
https://github.com/marselester/flask-api-utils/blob/f633e49e883c2f4e2523941e70b2d79ff4e138dc/api_utils/auth.py#L50-L75
marselester/flask-api-utils
api_utils/auth.py
Hawk.auth_required
def auth_required(self, view_func): """Decorator that provides an access to view function for authenticated users only. Note that we don't run authentication when `HAWK_ENABLED` is `False`. """ @wraps(view_func) def wrapped_view_func(*args, **kwargs): if current_app.config['HAWK_ENABLED']: if current_app.config['HAWK_ALLOW_COOKIE_AUTH'] and session: self._auth_by_cookie() else: self._auth_by_signature() return view_func(*args, **kwargs) return wrapped_view_func
python
def auth_required(self, view_func): """Decorator that provides an access to view function for authenticated users only. Note that we don't run authentication when `HAWK_ENABLED` is `False`. """ @wraps(view_func) def wrapped_view_func(*args, **kwargs): if current_app.config['HAWK_ENABLED']: if current_app.config['HAWK_ALLOW_COOKIE_AUTH'] and session: self._auth_by_cookie() else: self._auth_by_signature() return view_func(*args, **kwargs) return wrapped_view_func
Decorator that provides an access to view function for authenticated users only. Note that we don't run authentication when `HAWK_ENABLED` is `False`.
https://github.com/marselester/flask-api-utils/blob/f633e49e883c2f4e2523941e70b2d79ff4e138dc/api_utils/auth.py#L77-L93
marselester/flask-api-utils
api_utils/auth.py
Hawk._sign_response
def _sign_response(self, response): """Signs a response if it's possible.""" if 'Authorization' not in request.headers: return response try: mohawk_receiver = mohawk.Receiver( credentials_map=self._client_key_loader_func, request_header=request.headers['Authorization'], url=request.url, method=request.method, content=request.get_data(), content_type=request.mimetype, accept_untrusted_content=current_app.config['HAWK_ACCEPT_UNTRUSTED_CONTENT'], localtime_offset_in_seconds=current_app.config['HAWK_LOCALTIME_OFFSET_IN_SECONDS'], timestamp_skew_in_seconds=current_app.config['HAWK_TIMESTAMP_SKEW_IN_SECONDS'] ) except mohawk.exc.HawkFail: return response response.headers['Server-Authorization'] = mohawk_receiver.respond( content=response.data, content_type=response.mimetype ) return response
python
def _sign_response(self, response): """Signs a response if it's possible.""" if 'Authorization' not in request.headers: return response try: mohawk_receiver = mohawk.Receiver( credentials_map=self._client_key_loader_func, request_header=request.headers['Authorization'], url=request.url, method=request.method, content=request.get_data(), content_type=request.mimetype, accept_untrusted_content=current_app.config['HAWK_ACCEPT_UNTRUSTED_CONTENT'], localtime_offset_in_seconds=current_app.config['HAWK_LOCALTIME_OFFSET_IN_SECONDS'], timestamp_skew_in_seconds=current_app.config['HAWK_TIMESTAMP_SKEW_IN_SECONDS'] ) except mohawk.exc.HawkFail: return response response.headers['Server-Authorization'] = mohawk_receiver.respond( content=response.data, content_type=response.mimetype ) return response
Signs a response if it's possible.
https://github.com/marselester/flask-api-utils/blob/f633e49e883c2f4e2523941e70b2d79ff4e138dc/api_utils/auth.py#L133-L157
gawel/irc3
irc3/dcc/manager.py
DCCManager.create
def create(self, name_or_class, mask, filepath=None, **kwargs): """Create a new DCC connection. Return an ``asyncio.Protocol``""" if isinstance(name_or_class, type): name = name_or_class.type protocol = name_or_class else: name = name_or_class protocol = self.protocols[name] assert name in DCC_TYPES if filepath: kwargs.setdefault('limit_rate', self.config['send_limit_rate']) kwargs['filepath'] = filepath if protocol.type == DCCSend.type: kwargs.setdefault('offset', 0) kwargs.update( filename_safe=slugify(os.path.basename(filepath)), filesize=os.path.getsize(filepath), ) elif protocol.type == DCCGet.type: try: offset = os.path.getsize(filepath) except OSError: offset = 0 kwargs.setdefault('offset', offset) kwargs.setdefault('resume', False) kwargs.setdefault('port', None) f = protocol( mask=mask, ip=int(self.bot.ip), bot=self.bot, loop=self.loop, **kwargs) if kwargs['port']: if self.bot.config.get('dcc_sock_factory'): sock_factory = maybedotted(self.bot.config.dcc_sock_factory) args = dict(sock=sock_factory(self.bot, f.host, f.port)) else: args = dict(host=f.host, port=f.port) task = self.bot.create_task( self.loop.create_connection(f.factory, **args)) task.add_done_callback(partial(self.created, f)) else: task = self.bot.create_task( self.loop.create_server( f.factory, '0.0.0.0', 0, backlog=1)) task.add_done_callback(partial(self.created, f)) return f
python
def create(self, name_or_class, mask, filepath=None, **kwargs): """Create a new DCC connection. Return an ``asyncio.Protocol``""" if isinstance(name_or_class, type): name = name_or_class.type protocol = name_or_class else: name = name_or_class protocol = self.protocols[name] assert name in DCC_TYPES if filepath: kwargs.setdefault('limit_rate', self.config['send_limit_rate']) kwargs['filepath'] = filepath if protocol.type == DCCSend.type: kwargs.setdefault('offset', 0) kwargs.update( filename_safe=slugify(os.path.basename(filepath)), filesize=os.path.getsize(filepath), ) elif protocol.type == DCCGet.type: try: offset = os.path.getsize(filepath) except OSError: offset = 0 kwargs.setdefault('offset', offset) kwargs.setdefault('resume', False) kwargs.setdefault('port', None) f = protocol( mask=mask, ip=int(self.bot.ip), bot=self.bot, loop=self.loop, **kwargs) if kwargs['port']: if self.bot.config.get('dcc_sock_factory'): sock_factory = maybedotted(self.bot.config.dcc_sock_factory) args = dict(sock=sock_factory(self.bot, f.host, f.port)) else: args = dict(host=f.host, port=f.port) task = self.bot.create_task( self.loop.create_connection(f.factory, **args)) task.add_done_callback(partial(self.created, f)) else: task = self.bot.create_task( self.loop.create_server( f.factory, '0.0.0.0', 0, backlog=1)) task.add_done_callback(partial(self.created, f)) return f
Create a new DCC connection. Return an ``asyncio.Protocol``
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/dcc/manager.py#L67-L112
gawel/irc3
irc3/dcc/manager.py
DCCManager.resume
def resume(self, mask, filename, port, pos): """Resume a DCC send""" self.connections['send']['masks'][mask][port].offset = pos message = 'DCC ACCEPT %s %d %d' % (filename, port, pos) self.bot.ctcp(mask, message)
python
def resume(self, mask, filename, port, pos): """Resume a DCC send""" self.connections['send']['masks'][mask][port].offset = pos message = 'DCC ACCEPT %s %d %d' % (filename, port, pos) self.bot.ctcp(mask, message)
Resume a DCC send
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/dcc/manager.py#L114-L118
gawel/irc3
irc3/dcc/manager.py
DCCManager.is_allowed
def is_allowed(self, name_or_class, mask): # pragma: no cover """Return True is a new connection is allowed""" if isinstance(name_or_class, type): name = name_or_class.type else: name = name_or_class info = self.connections[name] limit = self.config[name + '_limit'] if limit and info['total'] >= limit: msg = ( "Sorry, there is too much DCC %s active. Please try again " "later.") % name.upper() self.bot.notice(mask, msg) return False if mask not in info['masks']: return True limit = self.config[name + '_user_limit'] if limit and info['masks'][mask] >= limit: msg = ( "Sorry, you have too many DCC %s active. Close the other " "connection(s) or wait a few seconds and try again." ) % name.upper() self.bot.notice(mask, msg) return False return True
python
def is_allowed(self, name_or_class, mask): # pragma: no cover """Return True is a new connection is allowed""" if isinstance(name_or_class, type): name = name_or_class.type else: name = name_or_class info = self.connections[name] limit = self.config[name + '_limit'] if limit and info['total'] >= limit: msg = ( "Sorry, there is too much DCC %s active. Please try again " "later.") % name.upper() self.bot.notice(mask, msg) return False if mask not in info['masks']: return True limit = self.config[name + '_user_limit'] if limit and info['masks'][mask] >= limit: msg = ( "Sorry, you have too many DCC %s active. Close the other " "connection(s) or wait a few seconds and try again." ) % name.upper() self.bot.notice(mask, msg) return False return True
Return True is a new connection is allowed
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/dcc/manager.py#L120-L144
gawel/irc3
irc3/utils.py
split_message
def split_message(message, max_length): """Split long messages""" if len(message) > max_length: for message in textwrap.wrap(message, max_length): yield message else: yield message.rstrip(STRIPPED_CHARS)
python
def split_message(message, max_length): """Split long messages""" if len(message) > max_length: for message in textwrap.wrap(message, max_length): yield message else: yield message.rstrip(STRIPPED_CHARS)
Split long messages
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L167-L173
gawel/irc3
irc3/utils.py
parse_config
def parse_config(main_section, *filenames): """parse config files""" filename = filenames[-1] filename = os.path.abspath(filename) here = os.path.dirname(filename) defaults = dict(here=here, hash='#') defaults['#'] = '#' config = configparser.ConfigParser( defaults, allow_no_value=False, interpolation=configparser.ExtendedInterpolation(), ) config.optionxform = str config.read([os.path.expanduser('~/.irc3/passwd.ini')] + list(filenames)) value = {} for s in config.sections(): items = {} for k, v in config.items(s): if '\n' in v: v = as_list(v) elif v.isdigit(): v = int(v) elif v.replace('.', '').isdigit() and v.count('.') == 1: v = float(v) elif v in ('true', 'false'): v = v == 'true' and True or False items[k] = v if s == main_section: value.update(items) else: for k in ('here', 'config'): items.pop(k, '') value[s] = items value.update(defaults) value['configfiles'] = filenames return value
python
def parse_config(main_section, *filenames): """parse config files""" filename = filenames[-1] filename = os.path.abspath(filename) here = os.path.dirname(filename) defaults = dict(here=here, hash='#') defaults['#'] = '#' config = configparser.ConfigParser( defaults, allow_no_value=False, interpolation=configparser.ExtendedInterpolation(), ) config.optionxform = str config.read([os.path.expanduser('~/.irc3/passwd.ini')] + list(filenames)) value = {} for s in config.sections(): items = {} for k, v in config.items(s): if '\n' in v: v = as_list(v) elif v.isdigit(): v = int(v) elif v.replace('.', '').isdigit() and v.count('.') == 1: v = float(v) elif v in ('true', 'false'): v = v == 'true' and True or False items[k] = v if s == main_section: value.update(items) else: for k in ('here', 'config'): items.pop(k, '') value[s] = items value.update(defaults) value['configfiles'] = filenames return value
parse config files
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L190-L226
gawel/irc3
irc3/utils.py
extract_config
def extract_config(config, prefix): """return all keys with the same prefix without the prefix""" prefix = prefix.strip('.') + '.' plen = len(prefix) value = {} for k, v in config.items(): if k.startswith(prefix): value[k[plen:]] = v return value
python
def extract_config(config, prefix): """return all keys with the same prefix without the prefix""" prefix = prefix.strip('.') + '.' plen = len(prefix) value = {} for k, v in config.items(): if k.startswith(prefix): value[k[plen:]] = v return value
return all keys with the same prefix without the prefix
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L229-L237
gawel/irc3
irc3/utils.py
as_list
def as_list(value): """clever string spliting: .. code-block:: python >>> print(as_list('value')) ['value'] >>> print(as_list('v1 v2')) ['v1', 'v2'] >>> print(as_list(None)) [] >>> print(as_list(['v1'])) ['v1'] """ if isinstance(value, (list, tuple)): return value if not value: return [] for c in '\n ': if c in value: value = value.split(c) return [v.strip() for v in value if v.strip()] return [value]
python
def as_list(value): """clever string spliting: .. code-block:: python >>> print(as_list('value')) ['value'] >>> print(as_list('v1 v2')) ['v1', 'v2'] >>> print(as_list(None)) [] >>> print(as_list(['v1'])) ['v1'] """ if isinstance(value, (list, tuple)): return value if not value: return [] for c in '\n ': if c in value: value = value.split(c) return [v.strip() for v in value if v.strip()] return [value]
clever string spliting: .. code-block:: python >>> print(as_list('value')) ['value'] >>> print(as_list('v1 v2')) ['v1', 'v2'] >>> print(as_list(None)) [] >>> print(as_list(['v1'])) ['v1']
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L240-L262
gawel/irc3
irc3/utils.py
parse_modes
def parse_modes(modes, targets=None, noargs=''): """Parse channel modes: .. code-block:: python >>> parse_modes('+c-n', noargs='cn') [('+', 'c', None), ('-', 'n', None)] >>> parse_modes('+c-v', ['gawel'], noargs='c') [('+', 'c', None), ('-', 'v', 'gawel')] """ if not targets: targets = [] cleaned = [] for mode in modes: if mode in '-+': char = mode continue target = targets.pop(0) if mode not in noargs else None cleaned.append((char, mode, target)) return cleaned
python
def parse_modes(modes, targets=None, noargs=''): """Parse channel modes: .. code-block:: python >>> parse_modes('+c-n', noargs='cn') [('+', 'c', None), ('-', 'n', None)] >>> parse_modes('+c-v', ['gawel'], noargs='c') [('+', 'c', None), ('-', 'v', 'gawel')] """ if not targets: targets = [] cleaned = [] for mode in modes: if mode in '-+': char = mode continue target = targets.pop(0) if mode not in noargs else None cleaned.append((char, mode, target)) return cleaned
Parse channel modes: .. code-block:: python >>> parse_modes('+c-n', noargs='cn') [('+', 'c', None), ('-', 'n', None)] >>> parse_modes('+c-v', ['gawel'], noargs='c') [('+', 'c', None), ('-', 'v', 'gawel')]
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L282-L301
gawel/irc3
irc3/utils.py
wraps_with_context
def wraps_with_context(func, context): """Return a wrapped partial(func, context)""" wrapped = functools.partial(func, context) wrapped = functools.wraps(func)(wrapped) if asyncio.iscoroutinefunction(func): wrapped = asyncio.coroutine(wrapped) return wrapped
python
def wraps_with_context(func, context): """Return a wrapped partial(func, context)""" wrapped = functools.partial(func, context) wrapped = functools.wraps(func)(wrapped) if asyncio.iscoroutinefunction(func): wrapped = asyncio.coroutine(wrapped) return wrapped
Return a wrapped partial(func, context)
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L304-L310
gawel/irc3
irc3/utils.py
maybedotted
def maybedotted(name): """Resolve dotted names: .. code-block:: python >>> maybedotted('irc3.config') <module 'irc3.config' from '...'> >>> maybedotted('irc3.utils.IrcString') <class 'irc3.utils.IrcString'> .. """ if not name: raise LookupError( 'Not able to resolve %s' % name) if not hasattr(name, '__name__'): try: mod = importlib.import_module(name) except ImportError: attr = None if '.' in name: names = name.split('.') attr = names.pop(-1) try: mod = maybedotted('.'.join(names)) except LookupError: attr = None else: attr = getattr(mod, attr, None) if attr is not None: return attr raise LookupError( 'Not able to resolve %s' % name) else: return mod return name
python
def maybedotted(name): """Resolve dotted names: .. code-block:: python >>> maybedotted('irc3.config') <module 'irc3.config' from '...'> >>> maybedotted('irc3.utils.IrcString') <class 'irc3.utils.IrcString'> .. """ if not name: raise LookupError( 'Not able to resolve %s' % name) if not hasattr(name, '__name__'): try: mod = importlib.import_module(name) except ImportError: attr = None if '.' in name: names = name.split('.') attr = names.pop(-1) try: mod = maybedotted('.'.join(names)) except LookupError: attr = None else: attr = getattr(mod, attr, None) if attr is not None: return attr raise LookupError( 'Not able to resolve %s' % name) else: return mod return name
Resolve dotted names: .. code-block:: python >>> maybedotted('irc3.config') <module 'irc3.config' from '...'> >>> maybedotted('irc3.utils.IrcString') <class 'irc3.utils.IrcString'> ..
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L313-L348
gawel/irc3
irc3/utils.py
IrcString.nick
def nick(self): """return nick name: .. code-block:: py >>> print(IrcString('foo').nick) foo >>> print(IrcString('foo!user@host').nick) foo >>> IrcString('#foo').nick is None True >>> IrcString('irc.freenode.net').nick is None True """ if '!' in self: return self.split('!', 1)[0] if not self.is_channel and not self.is_server: return self
python
def nick(self): """return nick name: .. code-block:: py >>> print(IrcString('foo').nick) foo >>> print(IrcString('foo!user@host').nick) foo >>> IrcString('#foo').nick is None True >>> IrcString('irc.freenode.net').nick is None True """ if '!' in self: return self.split('!', 1)[0] if not self.is_channel and not self.is_server: return self
return nick name: .. code-block:: py >>> print(IrcString('foo').nick) foo >>> print(IrcString('foo!user@host').nick) foo >>> IrcString('#foo').nick is None True >>> IrcString('irc.freenode.net').nick is None True
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L34-L51
gawel/irc3
irc3/utils.py
IrcString.tagdict
def tagdict(self): """return a dict converted from this string interpreted as a tag-string .. code-block:: py >>> from pprint import pprint >>> dict_ = IrcString('aaa=bbb;ccc;example.com/ddd=eee').tagdict >>> pprint({str(k): str(v) for k, v in dict_.items()}) {'aaa': 'bbb', 'ccc': 'None', 'example.com/ddd': 'eee'} """ tagdict = getattr(self, '_tagdict', None) if tagdict is None: try: self._tagdict = tags.decode(self) except ValueError: self._tagdict = {} return self._tagdict
python
def tagdict(self): """return a dict converted from this string interpreted as a tag-string .. code-block:: py >>> from pprint import pprint >>> dict_ = IrcString('aaa=bbb;ccc;example.com/ddd=eee').tagdict >>> pprint({str(k): str(v) for k, v in dict_.items()}) {'aaa': 'bbb', 'ccc': 'None', 'example.com/ddd': 'eee'} """ tagdict = getattr(self, '_tagdict', None) if tagdict is None: try: self._tagdict = tags.decode(self) except ValueError: self._tagdict = {} return self._tagdict
return a dict converted from this string interpreted as a tag-string .. code-block:: py >>> from pprint import pprint >>> dict_ = IrcString('aaa=bbb;ccc;example.com/ddd=eee').tagdict >>> pprint({str(k): str(v) for k, v in dict_.items()}) {'aaa': 'bbb', 'ccc': 'None', 'example.com/ddd': 'eee'}
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L145-L161
gawel/irc3
irc3/utils.py
Logger.set_irc_targets
def set_irc_targets(self, bot, *targets): """Add a irc Handler using bot and log to targets (can be nicks or channels: .. >>> bot = None .. code-block:: python >>> log = logging.getLogger('irc.mymodule') >>> log.set_irc_targets(bot, '#chan', 'admin') """ # get formatter initialized by config (usualy on a NullHandler) ll = logging.getLogger('irc') formatter = ll.handlers[0].formatter # add a handler for the sub logger handler = Handler(bot, *targets) handler.setFormatter(formatter) self.addHandler(handler)
python
def set_irc_targets(self, bot, *targets): """Add a irc Handler using bot and log to targets (can be nicks or channels: .. >>> bot = None .. code-block:: python >>> log = logging.getLogger('irc.mymodule') >>> log.set_irc_targets(bot, '#chan', 'admin') """ # get formatter initialized by config (usualy on a NullHandler) ll = logging.getLogger('irc') formatter = ll.handlers[0].formatter # add a handler for the sub logger handler = Handler(bot, *targets) handler.setFormatter(formatter) self.addHandler(handler)
Add a irc Handler using bot and log to targets (can be nicks or channels: .. >>> bot = None .. code-block:: python >>> log = logging.getLogger('irc.mymodule') >>> log.set_irc_targets(bot, '#chan', 'admin')
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/utils.py#L370-L388
gawel/irc3
irc3/__init__.py
IrcBot.send_line
def send_line(self, data, nowait=False): """send a line to the server. replace CR by spaces""" data = data.replace('\n', ' ').replace('\r', ' ') f = asyncio.Future(loop=self.loop) if self.queue is not None and nowait is False: self.queue.put_nowait((f, data)) else: self.send(data.replace('\n', ' ').replace('\r', ' ')) f.set_result(True) return f
python
def send_line(self, data, nowait=False): """send a line to the server. replace CR by spaces""" data = data.replace('\n', ' ').replace('\r', ' ') f = asyncio.Future(loop=self.loop) if self.queue is not None and nowait is False: self.queue.put_nowait((f, data)) else: self.send(data.replace('\n', ' ').replace('\r', ' ')) f.set_result(True) return f
send a line to the server. replace CR by spaces
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L180-L189
gawel/irc3
irc3/__init__.py
IrcBot.privmsg
def privmsg(self, target, message, nowait=False): """send a privmsg to target""" if message: messages = utils.split_message(message, self.config.max_length) if isinstance(target, DCCChat): for message in messages: target.send_line(message) elif target: f = None for message in messages: f = self.send_line('PRIVMSG %s :%s' % (target, message), nowait=nowait) return f
python
def privmsg(self, target, message, nowait=False): """send a privmsg to target""" if message: messages = utils.split_message(message, self.config.max_length) if isinstance(target, DCCChat): for message in messages: target.send_line(message) elif target: f = None for message in messages: f = self.send_line('PRIVMSG %s :%s' % (target, message), nowait=nowait) return f
send a privmsg to target
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L226-L238
gawel/irc3
irc3/__init__.py
IrcBot.ctcp
def ctcp(self, target, message, nowait=False): """send a ctcp to target""" if target and message: messages = utils.split_message(message, self.config.max_length) f = None for message in messages: f = self.send_line('PRIVMSG %s :\x01%s\x01' % (target, message), nowait=nowait) return f
python
def ctcp(self, target, message, nowait=False): """send a ctcp to target""" if target and message: messages = utils.split_message(message, self.config.max_length) f = None for message in messages: f = self.send_line('PRIVMSG %s :\x01%s\x01' % (target, message), nowait=nowait) return f
send a ctcp to target
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L258-L267
gawel/irc3
irc3/__init__.py
IrcBot.mode
def mode(self, target, *data): """set user or channel mode""" self.send_line('MODE %s %s' % (target, ' '.join(data)), nowait=True)
python
def mode(self, target, *data): """set user or channel mode""" self.send_line('MODE %s %s' % (target, ' '.join(data)), nowait=True)
set user or channel mode
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L279-L281
gawel/irc3
irc3/__init__.py
IrcBot.join
def join(self, target): """join a channel""" password = self.config.passwords.get( target.strip(self.server_config['CHANTYPES'])) if password: target += ' ' + password self.send_line('JOIN %s' % target)
python
def join(self, target): """join a channel""" password = self.config.passwords.get( target.strip(self.server_config['CHANTYPES'])) if password: target += ' ' + password self.send_line('JOIN %s' % target)
join a channel
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L283-L289
gawel/irc3
irc3/__init__.py
IrcBot.part
def part(self, target, reason=None): """quit a channel""" if reason: target += ' :' + reason self.send_line('PART %s' % target)
python
def part(self, target, reason=None): """quit a channel""" if reason: target += ' :' + reason self.send_line('PART %s' % target)
quit a channel
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L291-L295
gawel/irc3
irc3/__init__.py
IrcBot.kick
def kick(self, channel, target, reason=None): """kick target from channel""" if reason: target += ' :' + reason self.send_line('KICK %s %s' % (channel, target), nowait=True)
python
def kick(self, channel, target, reason=None): """kick target from channel""" if reason: target += ' :' + reason self.send_line('KICK %s %s' % (channel, target), nowait=True)
kick target from channel
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L297-L301
gawel/irc3
irc3/__init__.py
IrcBot.topic
def topic(self, channel, topic=None): """change or request the topic of a channel""" if topic: channel += ' :' + topic self.send_line('TOPIC %s' % channel)
python
def topic(self, channel, topic=None): """change or request the topic of a channel""" if topic: channel += ' :' + topic self.send_line('TOPIC %s' % channel)
change or request the topic of a channel
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L307-L311
gawel/irc3
irc3/__init__.py
IrcBot.away
def away(self, message=None): """mark ourself as away""" cmd = 'AWAY' if message: cmd += ' :' + message self.send_line(cmd)
python
def away(self, message=None): """mark ourself as away""" cmd = 'AWAY' if message: cmd += ' :' + message self.send_line(cmd)
mark ourself as away
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L313-L318
gawel/irc3
irc3/__init__.py
IrcBot.quit
def quit(self, reason=None): """disconnect""" if not reason: reason = 'bye' else: reason = reason self.send_line('QUIT :%s' % reason)
python
def quit(self, reason=None): """disconnect""" if not reason: reason = 'bye' else: reason = reason self.send_line('QUIT :%s' % reason)
disconnect
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L324-L330
gawel/irc3
irc3/__init__.py
IrcBot.ip
def ip(self): """return bot's ip as an ``ip_address`` object""" if not self._ip: if 'ip' in self.config: ip = self.config['ip'] else: ip = self.protocol.transport.get_extra_info('sockname')[0] ip = ip_address(ip) if ip.version == 4: self._ip = ip else: # pragma: no cover response = urlopen('http://ipv4.icanhazip.com/') ip = response.read().strip().decode() ip = ip_address(ip) self._ip = ip return self._ip
python
def ip(self): """return bot's ip as an ``ip_address`` object""" if not self._ip: if 'ip' in self.config: ip = self.config['ip'] else: ip = self.protocol.transport.get_extra_info('sockname')[0] ip = ip_address(ip) if ip.version == 4: self._ip = ip else: # pragma: no cover response = urlopen('http://ipv4.icanhazip.com/') ip = response.read().strip().decode() ip = ip_address(ip) self._ip = ip return self._ip
return bot's ip as an ``ip_address`` object
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L341-L356
gawel/irc3
irc3/__init__.py
IrcBot.dcc
def dcc(self): """return the :class:`~irc3.dcc.DCCManager`""" if self._dcc is None: self._dcc = DCCManager(self) return self._dcc
python
def dcc(self): """return the :class:`~irc3.dcc.DCCManager`""" if self._dcc is None: self._dcc = DCCManager(self) return self._dcc
return the :class:`~irc3.dcc.DCCManager`
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L359-L363
gawel/irc3
irc3/__init__.py
IrcBot.dcc_chat
def dcc_chat(self, mask, host=None, port=None): """Open a DCC CHAT whith mask. If host/port are specified then connect to a server. Else create a server""" return self.dcc.create( 'chat', mask, host=host, port=port).ready
python
def dcc_chat(self, mask, host=None, port=None): """Open a DCC CHAT whith mask. If host/port are specified then connect to a server. Else create a server""" return self.dcc.create( 'chat', mask, host=host, port=port).ready
Open a DCC CHAT whith mask. If host/port are specified then connect to a server. Else create a server
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L366-L370
gawel/irc3
irc3/__init__.py
IrcBot.dcc_get
def dcc_get(self, mask, host, port, filepath, filesize=None): """DCC GET a file from mask. filepath must be an absolute path with an existing directory. filesize is the expected file size.""" return self.dcc.create( 'get', mask, filepath=filepath, filesize=filesize, host=host, port=port).ready
python
def dcc_get(self, mask, host, port, filepath, filesize=None): """DCC GET a file from mask. filepath must be an absolute path with an existing directory. filesize is the expected file size.""" return self.dcc.create( 'get', mask, filepath=filepath, filesize=filesize, host=host, port=port).ready
DCC GET a file from mask. filepath must be an absolute path with an existing directory. filesize is the expected file size.
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L373-L378
gawel/irc3
irc3/__init__.py
IrcBot.dcc_send
def dcc_send(self, mask, filepath): """DCC SEND a file to mask. filepath must be an absolute path to existing file""" return self.dcc.create('send', mask, filepath=filepath).ready
python
def dcc_send(self, mask, filepath): """DCC SEND a file to mask. filepath must be an absolute path to existing file""" return self.dcc.create('send', mask, filepath=filepath).ready
DCC SEND a file to mask. filepath must be an absolute path to existing file
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L381-L384
gawel/irc3
irc3/__init__.py
IrcBot.dcc_accept
def dcc_accept(self, mask, filepath, port, pos): """accept a DCC RESUME for an axisting DCC SEND. filepath is the filename to sent. port is the port opened on the server. pos is the expected offset""" return self.dcc.resume(mask, filepath, port, pos)
python
def dcc_accept(self, mask, filepath, port, pos): """accept a DCC RESUME for an axisting DCC SEND. filepath is the filename to sent. port is the port opened on the server. pos is the expected offset""" return self.dcc.resume(mask, filepath, port, pos)
accept a DCC RESUME for an axisting DCC SEND. filepath is the filename to sent. port is the port opened on the server. pos is the expected offset
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/__init__.py#L387-L391
gawel/irc3
irc3/tags.py
encode
def encode(tags): '''Encodes a dictionary of tags to fit into an IRC-message. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from collections import OrderedDict >>> encode({'key': 'value'}) 'key=value' >>> d = {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> encode(d_ordered) 'aaa=bbb;ccc;example.com/ddd=eee' >>> d = {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> print(encode(d_ordered)) key=value\\:with\\sspecial\\\characters;key2=with=equals >>> print(encode({'key': r'\\something'})) key=\\\\something ''' tagstrings = [] for key, value in tags.items(): if not _valid_key.match(key): raise ValueError("dictionary key is invalid as tag key: " + key) # if no value, just append the key if value: tagstrings.append(key + "=" + _escape(value)) else: tagstrings.append(key) return ";".join(tagstrings)
python
def encode(tags): '''Encodes a dictionary of tags to fit into an IRC-message. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from collections import OrderedDict >>> encode({'key': 'value'}) 'key=value' >>> d = {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> encode(d_ordered) 'aaa=bbb;ccc;example.com/ddd=eee' >>> d = {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> print(encode(d_ordered)) key=value\\:with\\sspecial\\\characters;key2=with=equals >>> print(encode({'key': r'\\something'})) key=\\\\something ''' tagstrings = [] for key, value in tags.items(): if not _valid_key.match(key): raise ValueError("dictionary key is invalid as tag key: " + key) # if no value, just append the key if value: tagstrings.append(key + "=" + _escape(value)) else: tagstrings.append(key) return ";".join(tagstrings)
Encodes a dictionary of tags to fit into an IRC-message. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from collections import OrderedDict >>> encode({'key': 'value'}) 'key=value' >>> d = {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> encode(d_ordered) 'aaa=bbb;ccc;example.com/ddd=eee' >>> d = {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> print(encode(d_ordered)) key=value\\:with\\sspecial\\\characters;key2=with=equals >>> print(encode({'key': r'\\something'})) key=\\\\something
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/tags.py#L53-L84
gawel/irc3
irc3/tags.py
decode
def decode(tagstring): '''Decodes a tag-string from an IRC-message into a python dictionary. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from pprint import pprint >>> pprint(decode('key=value')) {'key': 'value'} >>> pprint(decode('aaa=bbb;ccc;example.com/ddd=eee')) {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> s = r'key=value\\:with\\sspecial\\\\characters;key2=with=equals' >>> pprint(decode(s)) {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> print(decode(s)['key']) value;with special\\characters >>> print(decode(r'key=\\\\something')['key']) \\something ''' if not tagstring: # None/empty = no tags return {} tags = {} for tag in tagstring.split(";"): # value is either everything after "=", or None key, value = (tag.split("=", 1) + [None])[:2] if not _valid_key.match(key): raise ValueError("invalid tag key: " + key) if value: if not _valid_escaped_value.match(value): raise ValueError("invalid escaped tag value: " + value) value = _unescape(value) tags[key] = value return tags
python
def decode(tagstring): '''Decodes a tag-string from an IRC-message into a python dictionary. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from pprint import pprint >>> pprint(decode('key=value')) {'key': 'value'} >>> pprint(decode('aaa=bbb;ccc;example.com/ddd=eee')) {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> s = r'key=value\\:with\\sspecial\\\\characters;key2=with=equals' >>> pprint(decode(s)) {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> print(decode(s)['key']) value;with special\\characters >>> print(decode(r'key=\\\\something')['key']) \\something ''' if not tagstring: # None/empty = no tags return {} tags = {} for tag in tagstring.split(";"): # value is either everything after "=", or None key, value = (tag.split("=", 1) + [None])[:2] if not _valid_key.match(key): raise ValueError("invalid tag key: " + key) if value: if not _valid_escaped_value.match(value): raise ValueError("invalid escaped tag value: " + value) value = _unescape(value) tags[key] = value return tags
Decodes a tag-string from an IRC-message into a python dictionary. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from pprint import pprint >>> pprint(decode('key=value')) {'key': 'value'} >>> pprint(decode('aaa=bbb;ccc;example.com/ddd=eee')) {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> s = r'key=value\\:with\\sspecial\\\\characters;key2=with=equals' >>> pprint(decode(s)) {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> print(decode(s)['key']) value;with special\\characters >>> print(decode(r'key=\\\\something')['key']) \\something
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/tags.py#L87-L125
gawel/irc3
irc3/plugins/quakenet.py
challenge_auth
def challenge_auth(username, password, challenge, lower, digest='sha256'): """Calculates quakenet's challenge auth hash .. code-block:: python >>> challenge_auth("mooking", "0000000000", ... "12345678901234567890123456789012", str.lower, "md5") '2ed1a1f1d2cd5487d2e18f27213286b9' """ def hdig(x): return fdigest(x).hexdigest() fdigest = get_digest(digest) luser = lower(username) tpass = password[:10].encode("ascii") hvalue = hdig("{0}:{1}".format(luser, hdig(tpass)).encode("ascii")) bhvalue = hvalue.encode("ascii") bchallenge = challenge.encode("ascii") return hmac.HMAC(bhvalue, bchallenge, digestmod=fdigest).hexdigest()
python
def challenge_auth(username, password, challenge, lower, digest='sha256'): """Calculates quakenet's challenge auth hash .. code-block:: python >>> challenge_auth("mooking", "0000000000", ... "12345678901234567890123456789012", str.lower, "md5") '2ed1a1f1d2cd5487d2e18f27213286b9' """ def hdig(x): return fdigest(x).hexdigest() fdigest = get_digest(digest) luser = lower(username) tpass = password[:10].encode("ascii") hvalue = hdig("{0}:{1}".format(luser, hdig(tpass)).encode("ascii")) bhvalue = hvalue.encode("ascii") bchallenge = challenge.encode("ascii") return hmac.HMAC(bhvalue, bchallenge, digestmod=fdigest).hexdigest()
Calculates quakenet's challenge auth hash .. code-block:: python >>> challenge_auth("mooking", "0000000000", ... "12345678901234567890123456789012", str.lower, "md5") '2ed1a1f1d2cd5487d2e18f27213286b9'
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/quakenet.py#L54-L72
gawel/irc3
examples/freenode_irc3.py
auto_retweet
def auto_retweet(bot): """retweet author tweets about irc3 and pypi releases""" conn = bot.get_social_connection(id='twitter') dirname = os.path.expanduser('~/.irc3/twitter/{nick}'.format(**bot.config)) if not os.path.isdir(dirname): os.makedirs(dirname) filename = os.path.join(dirname, 'retweeted') if os.path.isfile(filename): with open(filename) as fd: retweeted = [i.strip() for i in fd.readlines()] else: retweeted = [] for user in ('pypi', 'gawel_'): results = conn.search.tweets( q=user + ' AND irc3', result_type='recent') for item in results.get('statuses', []): if item['user']['screen_name'] == user: if item['id_str'] not in retweeted: res = conn(getattr(conn.statuses.retweet, item['id_str'])) if 'id' in res: with open(filename, 'a+') as fd: fd.write(item['id_str'] + '\n')
python
def auto_retweet(bot): """retweet author tweets about irc3 and pypi releases""" conn = bot.get_social_connection(id='twitter') dirname = os.path.expanduser('~/.irc3/twitter/{nick}'.format(**bot.config)) if not os.path.isdir(dirname): os.makedirs(dirname) filename = os.path.join(dirname, 'retweeted') if os.path.isfile(filename): with open(filename) as fd: retweeted = [i.strip() for i in fd.readlines()] else: retweeted = [] for user in ('pypi', 'gawel_'): results = conn.search.tweets( q=user + ' AND irc3', result_type='recent') for item in results.get('statuses', []): if item['user']['screen_name'] == user: if item['id_str'] not in retweeted: res = conn(getattr(conn.statuses.retweet, item['id_str'])) if 'id' in res: with open(filename, 'a+') as fd: fd.write(item['id_str'] + '\n')
retweet author tweets about irc3 and pypi releases
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/examples/freenode_irc3.py#L57-L82
gawel/irc3
examples/freenode_irc3.py
FeedsHook.filter_travis
def filter_travis(self, entry): """Only show the latest entry iif this entry is in a new state""" fstate = entry.filename + '.state' if os.path.isfile(fstate): with open(fstate) as fd: state = fd.read().strip() else: state = None if 'failed' in entry.summary: nstate = 'failed' else: nstate = 'success' with open(fstate, 'w') as fd: fd.write(nstate) if state != nstate: build = entry.title.split('#')[1] entry['title'] = 'Build #{0} {1}'.format(build, nstate) return True
python
def filter_travis(self, entry): """Only show the latest entry iif this entry is in a new state""" fstate = entry.filename + '.state' if os.path.isfile(fstate): with open(fstate) as fd: state = fd.read().strip() else: state = None if 'failed' in entry.summary: nstate = 'failed' else: nstate = 'success' with open(fstate, 'w') as fd: fd.write(nstate) if state != nstate: build = entry.title.split('#')[1] entry['title'] = 'Build #{0} {1}'.format(build, nstate) return True
Only show the latest entry iif this entry is in a new state
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/examples/freenode_irc3.py#L17-L34
gawel/irc3
examples/freenode_irc3.py
FeedsHook.filter_pypi
def filter_pypi(self, entry): """Show only usefull packages""" for package in self.packages: if entry.title.lower().startswith(package): return entry
python
def filter_pypi(self, entry): """Show only usefull packages""" for package in self.packages: if entry.title.lower().startswith(package): return entry
Show only usefull packages
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/examples/freenode_irc3.py#L36-L40
gawel/irc3
irc3/plugins/async.py
Whois.process_results
def process_results(self, results=None, **value): """take results list of all events and put them in a dict""" channels = [] for res in results: channels.extend(res.pop('channels', '').split()) value.update(res) value['channels'] = channels value['success'] = value.get('retcode') == '318' return value
python
def process_results(self, results=None, **value): """take results list of all events and put them in a dict""" channels = [] for res in results: channels.extend(res.pop('channels', '').split()) value.update(res) value['channels'] = channels value['success'] = value.get('retcode') == '318' return value
take results list of all events and put them in a dict
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/async.py#L92-L100
gawel/irc3
irc3/plugins/async.py
CTCP.process_results
def process_results(self, results=None, **value): """take results list of all events and return first dict""" for res in results: if 'mask' in res: res['mask'] = utils.IrcString(res['mask']) value['success'] = res.pop('retcode', None) != '486' value.update(res) return value
python
def process_results(self, results=None, **value): """take results list of all events and return first dict""" for res in results: if 'mask' in res: res['mask'] = utils.IrcString(res['mask']) value['success'] = res.pop('retcode', None) != '486' value.update(res) return value
take results list of all events and return first dict
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/async.py#L277-L284
gawel/irc3
irc3/plugins/command.py
ping
def ping(bot, mask, target, args): """ping/pong %%ping """ bot.send('NOTICE %(nick)s :PONG %(nick)s!' % dict(nick=mask.nick))
python
def ping(bot, mask, target, args): """ping/pong %%ping """ bot.send('NOTICE %(nick)s :PONG %(nick)s!' % dict(nick=mask.nick))
ping/pong %%ping
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/command.py#L453-L458
gawel/irc3
irc3/plugins/command.py
quote
def quote(bot, mask, target, args): """send quote to the server %%quote <args>... """ msg = ' '.join(args['<args>']) bot.log.info('quote> %r', msg) bot.send(msg)
python
def quote(bot, mask, target, args): """send quote to the server %%quote <args>... """ msg = ' '.join(args['<args>']) bot.log.info('quote> %r', msg) bot.send(msg)
send quote to the server %%quote <args>...
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/command.py#L462-L469
gawel/irc3
irc3/plugins/command.py
reconnect
def reconnect(bot, mask, target, args): """force reconnect %%reconnect """ plugin = bot.get_plugin(utils.maybedotted('irc3.plugins.core.Core')) bot.loop.call_soon(plugin.reconnect)
python
def reconnect(bot, mask, target, args): """force reconnect %%reconnect """ plugin = bot.get_plugin(utils.maybedotted('irc3.plugins.core.Core')) bot.loop.call_soon(plugin.reconnect)
force reconnect %%reconnect
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/command.py#L473-L479
gawel/irc3
irc3/plugins/command.py
print_help_page
def print_help_page(bot, file=sys.stdout): """print help page""" def p(text): print(text, file=file) plugin = bot.get_plugin(Commands) title = "Available Commands for {nick} at {host}".format(**bot.config) p("=" * len(title)) p(title) p("=" * len(title)) p('') p('.. contents::') p('') modules = {} for name, (predicates, callback) in plugin.items(): commands = modules.setdefault(callback.__module__, []) commands.append((name, callback, predicates)) for module in sorted(modules): p(module) p('=' * len(module)) p('') for name, callback, predicates in sorted(modules[module]): p(name) p('-' * len(name)) p('') doc = callback.__doc__ doc = doc.replace('%%', bot.config.cmd) for line in doc.split('\n'): line = line.strip() if line.startswith(bot.config.cmd): line = ' ``{}``'.format(line) p(line) if 'permission' in predicates: p('*Require {0[permission]} permission.*'.format(predicates)) if predicates.get('public', True) is False: p('*Only available in private.*') p('')
python
def print_help_page(bot, file=sys.stdout): """print help page""" def p(text): print(text, file=file) plugin = bot.get_plugin(Commands) title = "Available Commands for {nick} at {host}".format(**bot.config) p("=" * len(title)) p(title) p("=" * len(title)) p('') p('.. contents::') p('') modules = {} for name, (predicates, callback) in plugin.items(): commands = modules.setdefault(callback.__module__, []) commands.append((name, callback, predicates)) for module in sorted(modules): p(module) p('=' * len(module)) p('') for name, callback, predicates in sorted(modules[module]): p(name) p('-' * len(name)) p('') doc = callback.__doc__ doc = doc.replace('%%', bot.config.cmd) for line in doc.split('\n'): line = line.strip() if line.startswith(bot.config.cmd): line = ' ``{}``'.format(line) p(line) if 'permission' in predicates: p('*Require {0[permission]} permission.*'.format(predicates)) if predicates.get('public', True) is False: p('*Only available in private.*') p('')
print help page
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/command.py#L483-L519
gawel/irc3
irc3/plugins/core.py
Core.connected
def connected(self, **kwargs): """triger the server_ready event""" self.bot.log.info('Server config: %r', self.bot.server_config) # recompile when I'm sure of my nickname self.bot.config['nick'] = kwargs['me'] self.bot.recompile() # Let all plugins know that server can handle commands self.bot.notify('server_ready') # detach useless events self.bot.detach_events(*self.before_connect_events)
python
def connected(self, **kwargs): """triger the server_ready event""" self.bot.log.info('Server config: %r', self.bot.server_config) # recompile when I'm sure of my nickname self.bot.config['nick'] = kwargs['me'] self.bot.recompile() # Let all plugins know that server can handle commands self.bot.notify('server_ready') # detach useless events self.bot.detach_events(*self.before_connect_events)
triger the server_ready event
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/core.py#L50-L62
gawel/irc3
irc3/plugins/core.py
Core.pong
def pong(self, event='PONG', data='', **kw): # pragma: no cover """P0NG/PING""" self.bot.log.debug('%s ping-pong (%s)', event, data) if self.reconn_handle is not None: self.reconn_handle.cancel() self.reconn_handle = self.bot.loop.call_later(self.timeout, self.reconnect) if self.ping_handle is not None: self.ping_handle.cancel() self.ping_handle = self.bot.loop.call_later( self.timeout - self.max_lag, self.bot.send, 'PING :%s' % int(self.bot.loop.time()))
python
def pong(self, event='PONG', data='', **kw): # pragma: no cover """P0NG/PING""" self.bot.log.debug('%s ping-pong (%s)', event, data) if self.reconn_handle is not None: self.reconn_handle.cancel() self.reconn_handle = self.bot.loop.call_later(self.timeout, self.reconnect) if self.ping_handle is not None: self.ping_handle.cancel() self.ping_handle = self.bot.loop.call_later( self.timeout - self.max_lag, self.bot.send, 'PING :%s' % int(self.bot.loop.time()))
P0NG/PING
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/core.py#L74-L85
gawel/irc3
irc3/plugins/core.py
Core.ping
def ping(self, data): """PING reply""" self.bot.send('PONG :' + data) self.pong(event='PING', data=data)
python
def ping(self, data): """PING reply""" self.bot.send('PONG :' + data) self.pong(event='PING', data=data)
PING reply
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/core.py#L88-L91
gawel/irc3
irc3/plugins/core.py
Core.recompile
def recompile(self, nick=None, new_nick=None, **kw): """recompile regexp on new nick""" if self.bot.nick == nick.nick: self.bot.config['nick'] = new_nick self.bot.recompile()
python
def recompile(self, nick=None, new_nick=None, **kw): """recompile regexp on new nick""" if self.bot.nick == nick.nick: self.bot.config['nick'] = new_nick self.bot.recompile()
recompile regexp on new nick
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/core.py#L94-L98
gawel/irc3
irc3/plugins/core.py
Core.badnick
def badnick(self, me=None, nick=None, **kw): """Use alt nick on nick error""" if me == '*': self.bot.set_nick(self.bot.nick + '_') self.bot.log.debug('Trying to regain nickname in 30s...') self.nick_handle = self.bot.loop.call_later( 30, self.bot.set_nick, self.bot.original_nick)
python
def badnick(self, me=None, nick=None, **kw): """Use alt nick on nick error""" if me == '*': self.bot.set_nick(self.bot.nick + '_') self.bot.log.debug('Trying to regain nickname in 30s...') self.nick_handle = self.bot.loop.call_later( 30, self.bot.set_nick, self.bot.original_nick)
Use alt nick on nick error
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/core.py#L101-L107
gawel/irc3
irc3/plugins/core.py
Core.set_config
def set_config(self, data=None, **kwargs): """Store server config""" config = self.bot.config['server_config'] for opt in data.split(' '): if '=' in opt: opt, value = opt.split('=', 1) else: value = True if opt.isupper(): config[opt] = value
python
def set_config(self, data=None, **kwargs): """Store server config""" config = self.bot.config['server_config'] for opt in data.split(' '): if '=' in opt: opt, value = opt.split('=', 1) else: value = True if opt.isupper(): config[opt] = value
Store server config
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/core.py#L109-L118
gawel/irc3
irc3/plugins/feeds.py
fetch
def fetch(args): """fetch a feed""" session = args['session'] for feed, filename in zip(args['feeds'], args['filenames']): try: resp = session.get(feed, timeout=5) content = resp.content except Exception: # pragma: no cover pass else: with open(filename, 'wb') as fd: fd.write(content) return args['name']
python
def fetch(args): """fetch a feed""" session = args['session'] for feed, filename in zip(args['feeds'], args['filenames']): try: resp = session.get(feed, timeout=5) content = resp.content except Exception: # pragma: no cover pass else: with open(filename, 'wb') as fd: fd.write(content) return args['name']
fetch a feed
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/feeds.py#L79-L91
gawel/irc3
irc3/plugins/feeds.py
parse
def parse(feedparser, args): """parse a feed using feedparser""" entries = [] args = irc3.utils.Config(args) max_date = datetime.datetime.now() - datetime.timedelta(days=2) for filename in args['filenames']: try: with open(filename + '.updated') as fd: updated = fd.read().strip() except (OSError, IOError): updated = '0' feed = feedparser.parse(filename) for e in feed.entries: if e.updated <= updated: # skip already sent entries continue try: updated_parsed = e.updated_parsed except AttributeError: continue if datetime.datetime(*updated_parsed[:7]) < max_date: # skip entries older than 2 days continue e['filename'] = filename e['feed'] = args entries.append((e.updated, e)) if entries: entries = sorted(entries, key=itemgetter(0)) with open(filename + '.updated', 'w') as fd: fd.write(str(entries[-1][0])) return entries
python
def parse(feedparser, args): """parse a feed using feedparser""" entries = [] args = irc3.utils.Config(args) max_date = datetime.datetime.now() - datetime.timedelta(days=2) for filename in args['filenames']: try: with open(filename + '.updated') as fd: updated = fd.read().strip() except (OSError, IOError): updated = '0' feed = feedparser.parse(filename) for e in feed.entries: if e.updated <= updated: # skip already sent entries continue try: updated_parsed = e.updated_parsed except AttributeError: continue if datetime.datetime(*updated_parsed[:7]) < max_date: # skip entries older than 2 days continue e['filename'] = filename e['feed'] = args entries.append((e.updated, e)) if entries: entries = sorted(entries, key=itemgetter(0)) with open(filename + '.updated', 'w') as fd: fd.write(str(entries[-1][0])) return entries
parse a feed using feedparser
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/feeds.py#L94-L126
gawel/irc3
irc3/dcc/client.py
DCCChat.data_received
def data_received(self, data): """data received""" self.set_timeout() data = self.decode(data) if self.queue: data = self.queue.popleft() + data lines = data.replace('\r', '').split('\n') self.queue.append(lines.pop(-1)) for line in lines: self.bot.dispatch(line, iotype='dcc_in', client=self)
python
def data_received(self, data): """data received""" self.set_timeout() data = self.decode(data) if self.queue: data = self.queue.popleft() + data lines = data.replace('\r', '').split('\n') self.queue.append(lines.pop(-1)) for line in lines: self.bot.dispatch(line, iotype='dcc_in', client=self)
data received
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/dcc/client.py#L81-L90
gawel/irc3
irc3d/dec.py
extend
def extend(func): """same as :func:`~irc3.dec.extend` but for servers""" def callback(context, name, ob): obj = context.context if info.scope == 'class': @functools.wraps(func) def f(self, *args, **kwargs): plugin = obj.get_plugin(ob) return getattr(plugin, func.__name__)(*args, **kwargs) setattr(obj, func.__name__, f.__get__(obj, obj.__class__)) else: setattr(obj, func.__name__, func.__get__(obj, obj.__class__)) info = venusian.attach(func, callback, category='irc3d.extend') return func
python
def extend(func): """same as :func:`~irc3.dec.extend` but for servers""" def callback(context, name, ob): obj = context.context if info.scope == 'class': @functools.wraps(func) def f(self, *args, **kwargs): plugin = obj.get_plugin(ob) return getattr(plugin, func.__name__)(*args, **kwargs) setattr(obj, func.__name__, f.__get__(obj, obj.__class__)) else: setattr(obj, func.__name__, func.__get__(obj, obj.__class__)) info = venusian.attach(func, callback, category='irc3d.extend') return func
same as :func:`~irc3.dec.extend` but for servers
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3d/dec.py#L23-L36
gawel/irc3
irc3/base.py
IrcObject.attach_events
def attach_events(self, *events, **kwargs): """Attach one or more events to the bot instance""" reg = self.registry insert = 'insert' in kwargs for e in events: cregexp = e.compile(self.config) regexp = getattr(e.regexp, 're', e.regexp) if regexp not in reg.events[e.iotype]: if insert: reg.events_re[e.iotype].insert(0, (regexp, cregexp)) else: reg.events_re[e.iotype].append((regexp, cregexp)) if insert: reg.events[e.iotype][regexp].insert(0, e) else: reg.events[e.iotype][regexp].append(e)
python
def attach_events(self, *events, **kwargs): """Attach one or more events to the bot instance""" reg = self.registry insert = 'insert' in kwargs for e in events: cregexp = e.compile(self.config) regexp = getattr(e.regexp, 're', e.regexp) if regexp not in reg.events[e.iotype]: if insert: reg.events_re[e.iotype].insert(0, (regexp, cregexp)) else: reg.events_re[e.iotype].append((regexp, cregexp)) if insert: reg.events[e.iotype][regexp].insert(0, e) else: reg.events[e.iotype][regexp].append(e)
Attach one or more events to the bot instance
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/base.py#L156-L171
gawel/irc3
irc3/base.py
IrcObject.detach_events
def detach_events(self, *events): """Detach one or more events from the bot instance""" reg = self.registry delete = defaultdict(list) # remove from self.events all_events = reg.events for e in events: regexp = getattr(e.regexp, 're', e.regexp) iotype = e.iotype if e in all_events[iotype].get(regexp, []): all_events[iotype][regexp].remove(e) if not all_events[iotype][regexp]: del all_events[iotype][regexp] # need to delete from self.events_re delete[iotype].append(regexp) # delete from events_re for iotype, regexps in delete.items(): reg.events_re[iotype] = [r for r in reg.events_re[iotype] if r[0] not in regexps]
python
def detach_events(self, *events): """Detach one or more events from the bot instance""" reg = self.registry delete = defaultdict(list) # remove from self.events all_events = reg.events for e in events: regexp = getattr(e.regexp, 're', e.regexp) iotype = e.iotype if e in all_events[iotype].get(regexp, []): all_events[iotype][regexp].remove(e) if not all_events[iotype][regexp]: del all_events[iotype][regexp] # need to delete from self.events_re delete[iotype].append(regexp) # delete from events_re for iotype, regexps in delete.items(): reg.events_re[iotype] = [r for r in reg.events_re[iotype] if r[0] not in regexps]
Detach one or more events from the bot instance
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/base.py#L173-L193
gawel/irc3
irc3/base.py
IrcObject.reload
def reload(self, *modules): """Reload one or more plugins""" self.notify('before_reload') if 'configfiles' in self.config: # reload configfiles self.log.info('Reloading configuration...') cfg = utils.parse_config( self.server and 'server' or 'bot', *self.config['configfiles']) self.config.update(cfg) self.log.info('Reloading python code...') if not modules: modules = self.registry.includes scanned = list(reversed(self.registry.scanned)) # reset includes and events self.registry.reset() to_scan = [] for module_name, categories in scanned: if module_name in modules: module = utils.maybedotted(module_name) reload_module(module) to_scan.append((module_name, categories)) # rescan all modules for module_name, categories in to_scan: self.include(module_name, venusian_categories=categories) self.registry.reloading = {} self.notify('after_reload')
python
def reload(self, *modules): """Reload one or more plugins""" self.notify('before_reload') if 'configfiles' in self.config: # reload configfiles self.log.info('Reloading configuration...') cfg = utils.parse_config( self.server and 'server' or 'bot', *self.config['configfiles']) self.config.update(cfg) self.log.info('Reloading python code...') if not modules: modules = self.registry.includes scanned = list(reversed(self.registry.scanned)) # reset includes and events self.registry.reset() to_scan = [] for module_name, categories in scanned: if module_name in modules: module = utils.maybedotted(module_name) reload_module(module) to_scan.append((module_name, categories)) # rescan all modules for module_name, categories in to_scan: self.include(module_name, venusian_categories=categories) self.registry.reloading = {} self.notify('after_reload')
Reload one or more plugins
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/base.py#L230-L262
gawel/irc3
irc3/base.py
IrcObject.call_many
def call_many(self, callback, args): """callback is run with each arg but run a call per second""" if isinstance(callback, str): callback = getattr(self, callback) f = None for arg in args: f = callback(*arg) return f
python
def call_many(self, callback, args): """callback is run with each arg but run a call per second""" if isinstance(callback, str): callback = getattr(self, callback) f = None for arg in args: f = callback(*arg) return f
callback is run with each arg but run a call per second
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/base.py#L295-L302
gawel/irc3
irc3/base.py
IrcObject.add_signal_handlers
def add_signal_handlers(self): """Register handlers for UNIX signals (SIGHUP/SIGINT)""" try: self.loop.add_signal_handler(signal.SIGHUP, self.SIGHUP) except (RuntimeError, AttributeError): # pragma: no cover # windows pass try: self.loop.add_signal_handler(signal.SIGINT, self.SIGINT) except (RuntimeError, NotImplementedError): # pragma: no cover # annaconda pass
python
def add_signal_handlers(self): """Register handlers for UNIX signals (SIGHUP/SIGINT)""" try: self.loop.add_signal_handler(signal.SIGHUP, self.SIGHUP) except (RuntimeError, AttributeError): # pragma: no cover # windows pass try: self.loop.add_signal_handler(signal.SIGINT, self.SIGINT) except (RuntimeError, NotImplementedError): # pragma: no cover # annaconda pass
Register handlers for UNIX signals (SIGHUP/SIGINT)
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/base.py#L352-L363
gawel/irc3
irc3/base.py
IrcObject.run
def run(self, forever=True): """start the bot""" loop = self.create_connection() self.add_signal_handlers() if forever: loop.run_forever()
python
def run(self, forever=True): """start the bot""" loop = self.create_connection() self.add_signal_handlers() if forever: loop.run_forever()
start the bot
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/base.py#L365-L370