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
|
---|---|---|---|---|---|---|---|
jaywink/federation | federation/utils/diaspora.py | retrieve_and_parse_profile | def retrieve_and_parse_profile(handle):
"""
Retrieve the remote user and return a Profile object.
:arg handle: User handle in [email protected] format
:returns: ``federation.entities.Profile`` instance or None
"""
hcard = retrieve_diaspora_hcard(handle)
if not hcard:
return None
profile = parse_profile_from_hcard(hcard, handle)
try:
profile.validate()
except ValueError as ex:
logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s",
profile, ex)
return None
return profile | python | def retrieve_and_parse_profile(handle):
"""
Retrieve the remote user and return a Profile object.
:arg handle: User handle in [email protected] format
:returns: ``federation.entities.Profile`` instance or None
"""
hcard = retrieve_diaspora_hcard(handle)
if not hcard:
return None
profile = parse_profile_from_hcard(hcard, handle)
try:
profile.validate()
except ValueError as ex:
logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s",
profile, ex)
return None
return profile | Retrieve the remote user and return a Profile object.
:arg handle: User handle in [email protected] format
:returns: ``federation.entities.Profile`` instance or None | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L201-L218 |
jaywink/federation | federation/utils/diaspora.py | get_private_endpoint | def get_private_endpoint(id: str, guid: str) -> str:
"""Get remote endpoint for delivering private payloads."""
_username, domain = id.split("@")
return "https://%s/receive/users/%s" % (domain, guid) | python | def get_private_endpoint(id: str, guid: str) -> str:
"""Get remote endpoint for delivering private payloads."""
_username, domain = id.split("@")
return "https://%s/receive/users/%s" % (domain, guid) | Get remote endpoint for delivering private payloads. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L235-L238 |
jaywink/federation | federation/entities/diaspora/utils.py | ensure_timezone | def ensure_timezone(dt, tz=None):
"""
Make sure the datetime <dt> has a timezone set, using timezone <tz> if it
doesn't. <tz> defaults to the local timezone.
"""
if dt.tzinfo is None:
return dt.replace(tzinfo=tz or tzlocal())
else:
return dt | python | def ensure_timezone(dt, tz=None):
"""
Make sure the datetime <dt> has a timezone set, using timezone <tz> if it
doesn't. <tz> defaults to the local timezone.
"""
if dt.tzinfo is None:
return dt.replace(tzinfo=tz or tzlocal())
else:
return dt | Make sure the datetime <dt> has a timezone set, using timezone <tz> if it
doesn't. <tz> defaults to the local timezone. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/utils.py#L5-L13 |
jaywink/federation | federation/entities/diaspora/utils.py | struct_to_xml | def struct_to_xml(node, struct):
"""
Turn a list of dicts into XML nodes with tag names taken from the dict
keys and element text taken from dict values. This is a list of dicts
so that the XML nodes can be ordered in the XML output.
"""
for obj in struct:
for k, v in obj.items():
etree.SubElement(node, k).text = v | python | def struct_to_xml(node, struct):
"""
Turn a list of dicts into XML nodes with tag names taken from the dict
keys and element text taken from dict values. This is a list of dicts
so that the XML nodes can be ordered in the XML output.
"""
for obj in struct:
for k, v in obj.items():
etree.SubElement(node, k).text = v | Turn a list of dicts into XML nodes with tag names taken from the dict
keys and element text taken from dict values. This is a list of dicts
so that the XML nodes can be ordered in the XML output. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/utils.py#L25-L33 |
jaywink/federation | federation/entities/diaspora/utils.py | get_full_xml_representation | def get_full_xml_representation(entity, private_key):
"""Get full XML representation of an entity.
This contains the <XML><post>..</post></XML> wrapper.
Accepts either a Base entity or a Diaspora entity.
Author `private_key` must be given so that certain entities can be signed.
"""
from federation.entities.diaspora.mappers import get_outbound_entity
diaspora_entity = get_outbound_entity(entity, private_key)
xml = diaspora_entity.to_xml()
return "<XML><post>%s</post></XML>" % etree.tostring(xml).decode("utf-8") | python | def get_full_xml_representation(entity, private_key):
"""Get full XML representation of an entity.
This contains the <XML><post>..</post></XML> wrapper.
Accepts either a Base entity or a Diaspora entity.
Author `private_key` must be given so that certain entities can be signed.
"""
from federation.entities.diaspora.mappers import get_outbound_entity
diaspora_entity = get_outbound_entity(entity, private_key)
xml = diaspora_entity.to_xml()
return "<XML><post>%s</post></XML>" % etree.tostring(xml).decode("utf-8") | Get full XML representation of an entity.
This contains the <XML><post>..</post></XML> wrapper.
Accepts either a Base entity or a Diaspora entity.
Author `private_key` must be given so that certain entities can be signed. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/utils.py#L36-L48 |
jaywink/federation | federation/entities/diaspora/utils.py | add_element_to_doc | def add_element_to_doc(doc, tag, value):
"""Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist."""
element = doc.find(".//%s" % tag)
if element is None:
element = etree.SubElement(doc, tag)
element.text = value | python | def add_element_to_doc(doc, tag, value):
"""Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist."""
element = doc.find(".//%s" % tag)
if element is None:
element = etree.SubElement(doc, tag)
element.text = value | Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/utils.py#L51-L56 |
jaywink/federation | federation/hostmeta/generators.py | generate_host_meta | def generate_host_meta(template=None, *args, **kwargs):
"""Generate a host-meta XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str)
"""
if template == "diaspora":
hostmeta = DiasporaHostMeta(*args, **kwargs)
else:
hostmeta = BaseHostMeta(*args, **kwargs)
return hostmeta.render() | python | def generate_host_meta(template=None, *args, **kwargs):
"""Generate a host-meta XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str)
"""
if template == "diaspora":
hostmeta = DiasporaHostMeta(*args, **kwargs)
else:
hostmeta = BaseHostMeta(*args, **kwargs)
return hostmeta.render() | Generate a host-meta XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str) | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/generators.py#L14-L26 |
jaywink/federation | federation/hostmeta/generators.py | generate_legacy_webfinger | def generate_legacy_webfinger(template=None, *args, **kwargs):
"""Generate a legacy webfinger XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str)
"""
if template == "diaspora":
webfinger = DiasporaWebFinger(*args, **kwargs)
else:
webfinger = BaseLegacyWebFinger(*args, **kwargs)
return webfinger.render() | python | def generate_legacy_webfinger(template=None, *args, **kwargs):
"""Generate a legacy webfinger XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str)
"""
if template == "diaspora":
webfinger = DiasporaWebFinger(*args, **kwargs)
else:
webfinger = BaseLegacyWebFinger(*args, **kwargs)
return webfinger.render() | Generate a legacy webfinger XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str) | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/generators.py#L29-L41 |
jaywink/federation | federation/hostmeta/generators.py | generate_nodeinfo2_document | def generate_nodeinfo2_document(**kwargs):
"""
Generate a NodeInfo2 document.
Pass in a dictionary as per NodeInfo2 1.0 schema:
https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json
Minimum required schema:
{server:
baseUrl
name
software
version
}
openRegistrations
Protocols default will match what this library supports, ie "diaspora" currently.
:return: dict
:raises: KeyError on missing required items
"""
return {
"version": "1.0",
"server": {
"baseUrl": kwargs['server']['baseUrl'],
"name": kwargs['server']['name'],
"software": kwargs['server']['software'],
"version": kwargs['server']['version'],
},
"organization": {
"name": kwargs.get('organization', {}).get('name', None),
"contact": kwargs.get('organization', {}).get('contact', None),
"account": kwargs.get('organization', {}).get('account', None),
},
"protocols": kwargs.get('protocols', ["diaspora"]),
"relay": kwargs.get('relay', ''),
"services": {
"inbound": kwargs.get('service', {}).get('inbound', []),
"outbound": kwargs.get('service', {}).get('outbound', []),
},
"openRegistrations": kwargs['openRegistrations'],
"usage": {
"users": {
"total": kwargs.get('usage', {}).get('users', {}).get('total'),
"activeHalfyear": kwargs.get('usage', {}).get('users', {}).get('activeHalfyear'),
"activeMonth": kwargs.get('usage', {}).get('users', {}).get('activeMonth'),
"activeWeek": kwargs.get('usage', {}).get('users', {}).get('activeWeek'),
},
"localPosts": kwargs.get('usage', {}).get('localPosts'),
"localComments": kwargs.get('usage', {}).get('localComments'),
}
} | python | def generate_nodeinfo2_document(**kwargs):
"""
Generate a NodeInfo2 document.
Pass in a dictionary as per NodeInfo2 1.0 schema:
https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json
Minimum required schema:
{server:
baseUrl
name
software
version
}
openRegistrations
Protocols default will match what this library supports, ie "diaspora" currently.
:return: dict
:raises: KeyError on missing required items
"""
return {
"version": "1.0",
"server": {
"baseUrl": kwargs['server']['baseUrl'],
"name": kwargs['server']['name'],
"software": kwargs['server']['software'],
"version": kwargs['server']['version'],
},
"organization": {
"name": kwargs.get('organization', {}).get('name', None),
"contact": kwargs.get('organization', {}).get('contact', None),
"account": kwargs.get('organization', {}).get('account', None),
},
"protocols": kwargs.get('protocols', ["diaspora"]),
"relay": kwargs.get('relay', ''),
"services": {
"inbound": kwargs.get('service', {}).get('inbound', []),
"outbound": kwargs.get('service', {}).get('outbound', []),
},
"openRegistrations": kwargs['openRegistrations'],
"usage": {
"users": {
"total": kwargs.get('usage', {}).get('users', {}).get('total'),
"activeHalfyear": kwargs.get('usage', {}).get('users', {}).get('activeHalfyear'),
"activeMonth": kwargs.get('usage', {}).get('users', {}).get('activeMonth'),
"activeWeek": kwargs.get('usage', {}).get('users', {}).get('activeWeek'),
},
"localPosts": kwargs.get('usage', {}).get('localPosts'),
"localComments": kwargs.get('usage', {}).get('localComments'),
}
} | Generate a NodeInfo2 document.
Pass in a dictionary as per NodeInfo2 1.0 schema:
https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json
Minimum required schema:
{server:
baseUrl
name
software
version
}
openRegistrations
Protocols default will match what this library supports, ie "diaspora" currently.
:return: dict
:raises: KeyError on missing required items | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/generators.py#L44-L95 |
jaywink/federation | federation/hostmeta/generators.py | generate_hcard | def generate_hcard(template=None, **kwargs):
"""Generate a hCard document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: HTML document (str)
"""
if template == "diaspora":
hcard = DiasporaHCard(**kwargs)
else:
raise NotImplementedError()
return hcard.render() | python | def generate_hcard(template=None, **kwargs):
"""Generate a hCard document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: HTML document (str)
"""
if template == "diaspora":
hcard = DiasporaHCard(**kwargs)
else:
raise NotImplementedError()
return hcard.render() | Generate a hCard document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: HTML document (str) | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/generators.py#L98-L110 |
jaywink/federation | federation/fetchers.py | retrieve_remote_content | def retrieve_remote_content(
id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None,
):
"""Retrieve remote content and return an Entity object.
Currently, due to no other protocols supported, always use the Diaspora protocol.
:param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used
to fetch the profile and the key. Function must take handle as only parameter and return a public key.
:returns: Entity class instance or ``None``
"""
# TODO add support for AP
protocol_name = "diaspora"
if not guid:
guid = id
utils = importlib.import_module("federation.utils.%s" % protocol_name)
return utils.retrieve_and_parse_content(
guid=guid, handle=handle, entity_type=entity_type, sender_key_fetcher=sender_key_fetcher,
) | python | def retrieve_remote_content(
id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None,
):
"""Retrieve remote content and return an Entity object.
Currently, due to no other protocols supported, always use the Diaspora protocol.
:param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used
to fetch the profile and the key. Function must take handle as only parameter and return a public key.
:returns: Entity class instance or ``None``
"""
# TODO add support for AP
protocol_name = "diaspora"
if not guid:
guid = id
utils = importlib.import_module("federation.utils.%s" % protocol_name)
return utils.retrieve_and_parse_content(
guid=guid, handle=handle, entity_type=entity_type, sender_key_fetcher=sender_key_fetcher,
) | Retrieve remote content and return an Entity object.
Currently, due to no other protocols supported, always use the Diaspora protocol.
:param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used
to fetch the profile and the key. Function must take handle as only parameter and return a public key.
:returns: Entity class instance or ``None`` | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/fetchers.py#L11-L29 |
jaywink/federation | federation/fetchers.py | retrieve_remote_profile | def retrieve_remote_profile(id: str) -> Optional[Profile]:
"""High level retrieve profile method.
Retrieve the profile from a remote location, using protocol based on the given ID.
"""
protocol = identify_protocol_by_id(id)
utils = importlib.import_module(f"federation.utils.{protocol.PROTOCOL_NAME}")
return utils.retrieve_and_parse_profile(id) | python | def retrieve_remote_profile(id: str) -> Optional[Profile]:
"""High level retrieve profile method.
Retrieve the profile from a remote location, using protocol based on the given ID.
"""
protocol = identify_protocol_by_id(id)
utils = importlib.import_module(f"federation.utils.{protocol.PROTOCOL_NAME}")
return utils.retrieve_and_parse_profile(id) | High level retrieve profile method.
Retrieve the profile from a remote location, using protocol based on the given ID. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/fetchers.py#L32-L39 |
jaywink/federation | federation/inbound.py | handle_receive | def handle_receive(
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False
) -> Tuple[str, str, List]:
"""Takes a request and passes it to the correct protocol.
Returns a tuple of:
- sender id
- protocol name
- list of entities
NOTE! The returned sender is NOT necessarily the *author* of the entity. By sender here we're
talking about the sender of the *request*. If this object is being relayed by the sender, the author
could actually be a different identity.
:arg request: Request object of type RequestType - note not a HTTP request even though the structure is similar
:arg user: User that will be passed to `protocol.receive` (only required on private encrypted content)
MUST have a `private_key` and `id` if given.
:arg sender_key_fetcher: Function that accepts sender handle and returns public key (optional)
:arg skip_author_verification: Don't verify sender (test purposes, false default)
:returns: Tuple of sender id, protocol name and list of entity objects
"""
logger.debug("handle_receive: processing request: %s", request)
found_protocol = identify_protocol_by_request(request)
logger.debug("handle_receive: using protocol %s", found_protocol.PROTOCOL_NAME)
protocol = found_protocol.Protocol()
sender, message = protocol.receive(
request, user, sender_key_fetcher, skip_author_verification=skip_author_verification)
logger.debug("handle_receive: sender %s, message %s", sender, message)
mappers = importlib.import_module("federation.entities.%s.mappers" % found_protocol.PROTOCOL_NAME)
entities = mappers.message_to_objects(message, sender, sender_key_fetcher, user)
logger.debug("handle_receive: entities %s", entities)
return sender, found_protocol.PROTOCOL_NAME, entities | python | def handle_receive(
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False
) -> Tuple[str, str, List]:
"""Takes a request and passes it to the correct protocol.
Returns a tuple of:
- sender id
- protocol name
- list of entities
NOTE! The returned sender is NOT necessarily the *author* of the entity. By sender here we're
talking about the sender of the *request*. If this object is being relayed by the sender, the author
could actually be a different identity.
:arg request: Request object of type RequestType - note not a HTTP request even though the structure is similar
:arg user: User that will be passed to `protocol.receive` (only required on private encrypted content)
MUST have a `private_key` and `id` if given.
:arg sender_key_fetcher: Function that accepts sender handle and returns public key (optional)
:arg skip_author_verification: Don't verify sender (test purposes, false default)
:returns: Tuple of sender id, protocol name and list of entity objects
"""
logger.debug("handle_receive: processing request: %s", request)
found_protocol = identify_protocol_by_request(request)
logger.debug("handle_receive: using protocol %s", found_protocol.PROTOCOL_NAME)
protocol = found_protocol.Protocol()
sender, message = protocol.receive(
request, user, sender_key_fetcher, skip_author_verification=skip_author_verification)
logger.debug("handle_receive: sender %s, message %s", sender, message)
mappers = importlib.import_module("federation.entities.%s.mappers" % found_protocol.PROTOCOL_NAME)
entities = mappers.message_to_objects(message, sender, sender_key_fetcher, user)
logger.debug("handle_receive: entities %s", entities)
return sender, found_protocol.PROTOCOL_NAME, entities | Takes a request and passes it to the correct protocol.
Returns a tuple of:
- sender id
- protocol name
- list of entities
NOTE! The returned sender is NOT necessarily the *author* of the entity. By sender here we're
talking about the sender of the *request*. If this object is being relayed by the sender, the author
could actually be a different identity.
:arg request: Request object of type RequestType - note not a HTTP request even though the structure is similar
:arg user: User that will be passed to `protocol.receive` (only required on private encrypted content)
MUST have a `private_key` and `id` if given.
:arg sender_key_fetcher: Function that accepts sender handle and returns public key (optional)
:arg skip_author_verification: Don't verify sender (test purposes, false default)
:returns: Tuple of sender id, protocol name and list of entity objects | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/inbound.py#L11-L48 |
jaywink/federation | federation/protocols/activitypub/protocol.py | identify_id | def identify_id(id: str) -> bool:
"""
Try to identify whether this is an ActivityPub ID.
"""
return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None | python | def identify_id(id: str) -> bool:
"""
Try to identify whether this is an ActivityPub ID.
"""
return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None | Try to identify whether this is an ActivityPub ID. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L19-L23 |
jaywink/federation | federation/protocols/activitypub/protocol.py | identify_request | def identify_request(request: RequestType) -> bool:
"""
Try to identify whether this is an ActivityPub request.
"""
# noinspection PyBroadException
try:
data = json.loads(decode_if_bytes(request.body))
if "@context" in data:
return True
except Exception:
pass
return False | python | def identify_request(request: RequestType) -> bool:
"""
Try to identify whether this is an ActivityPub request.
"""
# noinspection PyBroadException
try:
data = json.loads(decode_if_bytes(request.body))
if "@context" in data:
return True
except Exception:
pass
return False | Try to identify whether this is an ActivityPub request. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L26-L37 |
jaywink/federation | federation/protocols/activitypub/protocol.py | Protocol.build_send | def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]:
"""
Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
:returns: dict or string depending on if private or public payload.
"""
if hasattr(entity, "outbound_doc") and entity.outbound_doc is not None:
# Use pregenerated outbound document
rendered = entity.outbound_doc
else:
rendered = entity.to_as2()
return rendered | python | def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]:
"""
Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
:returns: dict or string depending on if private or public payload.
"""
if hasattr(entity, "outbound_doc") and entity.outbound_doc is not None:
# Use pregenerated outbound document
rendered = entity.outbound_doc
else:
rendered = entity.to_as2()
return rendered | Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
:returns: dict or string depending on if private or public payload. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L47-L61 |
jaywink/federation | federation/protocols/activitypub/protocol.py | Protocol.receive | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, dict]:
"""
Receive a request.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified.
"""
self.user = user
self.get_contact_key = sender_key_fetcher
self.payload = json.loads(decode_if_bytes(request.body))
self.request = request
self.extract_actor()
# Verify the message is from who it claims to be
if not skip_author_verification:
self.verify_signature()
return self.actor, self.payload | python | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, dict]:
"""
Receive a request.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified.
"""
self.user = user
self.get_contact_key = sender_key_fetcher
self.payload = json.loads(decode_if_bytes(request.body))
self.request = request
self.extract_actor()
# Verify the message is from who it claims to be
if not skip_author_verification:
self.verify_signature()
return self.actor, self.payload | Receive a request.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L69-L88 |
jaywink/federation | federation/utils/django.py | get_configuration | def get_configuration():
"""
Combine defaults with the Django configuration.
"""
configuration = {
"get_object_function": None,
"hcard_path": "/hcard/users/",
"nodeinfo2_function": None,
"process_payload_function": None,
"search_path": None,
# TODO remove or default to True once AP support is more ready
"activitypub": False,
}
configuration.update(settings.FEDERATION)
if not all([
"get_private_key_function" in configuration,
"get_profile_function" in configuration,
"base_url" in configuration,
]):
raise ImproperlyConfigured("Missing required FEDERATION settings, please check documentation.")
return configuration | python | def get_configuration():
"""
Combine defaults with the Django configuration.
"""
configuration = {
"get_object_function": None,
"hcard_path": "/hcard/users/",
"nodeinfo2_function": None,
"process_payload_function": None,
"search_path": None,
# TODO remove or default to True once AP support is more ready
"activitypub": False,
}
configuration.update(settings.FEDERATION)
if not all([
"get_private_key_function" in configuration,
"get_profile_function" in configuration,
"base_url" in configuration,
]):
raise ImproperlyConfigured("Missing required FEDERATION settings, please check documentation.")
return configuration | Combine defaults with the Django configuration. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/django.py#L7-L27 |
jaywink/federation | federation/utils/django.py | get_function_from_config | def get_function_from_config(item):
"""
Import the function to get profile by handle.
"""
config = get_configuration()
func_path = config.get(item)
module_path, func_name = func_path.rsplit(".", 1)
module = importlib.import_module(module_path)
func = getattr(module, func_name)
return func | python | def get_function_from_config(item):
"""
Import the function to get profile by handle.
"""
config = get_configuration()
func_path = config.get(item)
module_path, func_name = func_path.rsplit(".", 1)
module = importlib.import_module(module_path)
func = getattr(module, func_name)
return func | Import the function to get profile by handle. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/django.py#L30-L39 |
jaywink/federation | federation/entities/activitypub/entities.py | ActivitypubFollow.post_receive | def post_receive(self) -> None:
"""
Post receive hook - send back follow ack.
"""
from federation.utils.activitypub import retrieve_and_parse_profile # Circulars
try:
from federation.utils.django import get_function_from_config
except ImportError:
logger.warning("ActivitypubFollow.post_receive - Unable to send automatic Accept back, only supported on "
"Django currently")
return
get_private_key_function = get_function_from_config("get_private_key_function")
key = get_private_key_function(self.target_id)
if not key:
logger.warning("ActivitypubFollow.post_receive - Failed to send automatic Accept back: could not find "
"profile to sign it with")
return
accept = ActivitypubAccept(
activity_id=f"{self.target_id}#accept-{uuid.uuid4()}",
actor_id=self.target_id,
target_id=self.activity_id,
)
try:
profile = retrieve_and_parse_profile(self.actor_id)
except Exception:
profile = None
if not profile:
logger.warning("ActivitypubFollow.post_receive - Failed to fetch remote profile for sending back Accept")
return
try:
handle_send(
accept,
UserType(id=self.target_id, private_key=key),
recipients=[{
"fid": profile.inboxes["private"],
"protocol": "activitypub",
"public": False,
}],
)
except Exception:
logger.exception("ActivitypubFollow.post_receive - Failed to send Accept back") | python | def post_receive(self) -> None:
"""
Post receive hook - send back follow ack.
"""
from federation.utils.activitypub import retrieve_and_parse_profile # Circulars
try:
from federation.utils.django import get_function_from_config
except ImportError:
logger.warning("ActivitypubFollow.post_receive - Unable to send automatic Accept back, only supported on "
"Django currently")
return
get_private_key_function = get_function_from_config("get_private_key_function")
key = get_private_key_function(self.target_id)
if not key:
logger.warning("ActivitypubFollow.post_receive - Failed to send automatic Accept back: could not find "
"profile to sign it with")
return
accept = ActivitypubAccept(
activity_id=f"{self.target_id}#accept-{uuid.uuid4()}",
actor_id=self.target_id,
target_id=self.activity_id,
)
try:
profile = retrieve_and_parse_profile(self.actor_id)
except Exception:
profile = None
if not profile:
logger.warning("ActivitypubFollow.post_receive - Failed to fetch remote profile for sending back Accept")
return
try:
handle_send(
accept,
UserType(id=self.target_id, private_key=key),
recipients=[{
"fid": profile.inboxes["private"],
"protocol": "activitypub",
"public": False,
}],
)
except Exception:
logger.exception("ActivitypubFollow.post_receive - Failed to send Accept back") | Post receive hook - send back follow ack. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/entities.py#L35-L75 |
jaywink/federation | federation/utils/activitypub.py | retrieve_and_parse_document | def retrieve_and_parse_document(fid: str) -> Optional[Any]:
"""
Retrieve remote document by ID and return the entity.
"""
document, status_code, ex = fetch_document(fid, extra_headers={'accept': 'application/activity+json'})
if document:
document = json.loads(decode_if_bytes(document))
entities = message_to_objects(document, fid)
if entities:
return entities[0] | python | def retrieve_and_parse_document(fid: str) -> Optional[Any]:
"""
Retrieve remote document by ID and return the entity.
"""
document, status_code, ex = fetch_document(fid, extra_headers={'accept': 'application/activity+json'})
if document:
document = json.loads(decode_if_bytes(document))
entities = message_to_objects(document, fid)
if entities:
return entities[0] | Retrieve remote document by ID and return the entity. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/activitypub.py#L13-L22 |
jaywink/federation | federation/utils/activitypub.py | retrieve_and_parse_profile | def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile]:
"""
Retrieve the remote fid and return a Profile object.
"""
profile = retrieve_and_parse_document(fid)
if not profile:
return
try:
profile.validate()
except ValueError as ex:
logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s",
profile, ex)
return
return profile | python | def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile]:
"""
Retrieve the remote fid and return a Profile object.
"""
profile = retrieve_and_parse_document(fid)
if not profile:
return
try:
profile.validate()
except ValueError as ex:
logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s",
profile, ex)
return
return profile | Retrieve the remote fid and return a Profile object. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/activitypub.py#L25-L38 |
jaywink/federation | federation/__init__.py | identify_protocol | def identify_protocol(method, value):
# type: (str, Union[str, RequestType]) -> str
"""
Loop through protocols, import the protocol module and try to identify the id or request.
"""
for protocol_name in PROTOCOLS:
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol")
if getattr(protocol, f"identify_{method}")(value):
return protocol
else:
raise NoSuitableProtocolFoundError() | python | def identify_protocol(method, value):
# type: (str, Union[str, RequestType]) -> str
"""
Loop through protocols, import the protocol module and try to identify the id or request.
"""
for protocol_name in PROTOCOLS:
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol")
if getattr(protocol, f"identify_{method}")(value):
return protocol
else:
raise NoSuitableProtocolFoundError() | Loop through protocols, import the protocol module and try to identify the id or request. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/__init__.py#L17-L27 |
jaywink/federation | federation/protocols/diaspora/protocol.py | identify_request | def identify_request(request: RequestType):
"""Try to identify whether this is a Diaspora request.
Try first public message. Then private message. The check if this is a legacy payload.
"""
# Private encrypted JSON payload
try:
data = json.loads(decode_if_bytes(request.body))
if "encrypted_magic_envelope" in data:
return True
except Exception:
pass
# Public XML payload
try:
xml = etree.fromstring(encode_if_text(request.body))
if xml.tag == MAGIC_ENV_TAG:
return True
except Exception:
pass
return False | python | def identify_request(request: RequestType):
"""Try to identify whether this is a Diaspora request.
Try first public message. Then private message. The check if this is a legacy payload.
"""
# Private encrypted JSON payload
try:
data = json.loads(decode_if_bytes(request.body))
if "encrypted_magic_envelope" in data:
return True
except Exception:
pass
# Public XML payload
try:
xml = etree.fromstring(encode_if_text(request.body))
if xml.tag == MAGIC_ENV_TAG:
return True
except Exception:
pass
return False | Try to identify whether this is a Diaspora request.
Try first public message. Then private message. The check if this is a legacy payload. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L33-L52 |
jaywink/federation | federation/protocols/diaspora/protocol.py | Protocol.get_json_payload_magic_envelope | def get_json_payload_magic_envelope(self, payload):
"""Encrypted JSON payload"""
private_key = self._get_user_key()
return EncryptedPayload.decrypt(payload=payload, private_key=private_key) | python | def get_json_payload_magic_envelope(self, payload):
"""Encrypted JSON payload"""
private_key = self._get_user_key()
return EncryptedPayload.decrypt(payload=payload, private_key=private_key) | Encrypted JSON payload | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L66-L69 |
jaywink/federation | federation/protocols/diaspora/protocol.py | Protocol.store_magic_envelope_doc | def store_magic_envelope_doc(self, payload):
"""Get the Magic Envelope, trying JSON first."""
try:
json_payload = json.loads(decode_if_bytes(payload))
except ValueError:
# XML payload
xml = unquote(decode_if_bytes(payload))
xml = xml.lstrip().encode("utf-8")
logger.debug("diaspora.protocol.store_magic_envelope_doc: xml payload: %s", xml)
self.doc = etree.fromstring(xml)
else:
logger.debug("diaspora.protocol.store_magic_envelope_doc: json payload: %s", json_payload)
self.doc = self.get_json_payload_magic_envelope(json_payload) | python | def store_magic_envelope_doc(self, payload):
"""Get the Magic Envelope, trying JSON first."""
try:
json_payload = json.loads(decode_if_bytes(payload))
except ValueError:
# XML payload
xml = unquote(decode_if_bytes(payload))
xml = xml.lstrip().encode("utf-8")
logger.debug("diaspora.protocol.store_magic_envelope_doc: xml payload: %s", xml)
self.doc = etree.fromstring(xml)
else:
logger.debug("diaspora.protocol.store_magic_envelope_doc: json payload: %s", json_payload)
self.doc = self.get_json_payload_magic_envelope(json_payload) | Get the Magic Envelope, trying JSON first. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L71-L83 |
jaywink/federation | federation/protocols/diaspora/protocol.py | Protocol.receive | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, str]:
"""Receive a payload.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified."""
self.user = user
self.get_contact_key = sender_key_fetcher
self.store_magic_envelope_doc(request.body)
# Open payload and get actual message
self.content = self.get_message_content()
# Get sender handle
self.sender_handle = self.get_sender()
# Verify the message is from who it claims to be
if not skip_author_verification:
self.verify_signature()
return self.sender_handle, self.content | python | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, str]:
"""Receive a payload.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified."""
self.user = user
self.get_contact_key = sender_key_fetcher
self.store_magic_envelope_doc(request.body)
# Open payload and get actual message
self.content = self.get_message_content()
# Get sender handle
self.sender_handle = self.get_sender()
# Verify the message is from who it claims to be
if not skip_author_verification:
self.verify_signature()
return self.sender_handle, self.content | Receive a payload.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L85-L104 |
jaywink/federation | federation/protocols/diaspora/protocol.py | Protocol.get_message_content | def get_message_content(self):
"""
Given the Slap XML, extract out the payload.
"""
body = self.doc.find(
".//{http://salmon-protocol.org/ns/magic-env}data").text
body = urlsafe_b64decode(body.encode("ascii"))
logger.debug("diaspora.protocol.get_message_content: %s", body)
return body | python | def get_message_content(self):
"""
Given the Slap XML, extract out the payload.
"""
body = self.doc.find(
".//{http://salmon-protocol.org/ns/magic-env}data").text
body = urlsafe_b64decode(body.encode("ascii"))
logger.debug("diaspora.protocol.get_message_content: %s", body)
return body | Given the Slap XML, extract out the payload. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L114-L124 |
jaywink/federation | federation/protocols/diaspora/protocol.py | Protocol.verify_signature | def verify_signature(self):
"""
Verify the signed XML elements to have confidence that the claimed
author did actually generate this message.
"""
if self.get_contact_key:
sender_key = self.get_contact_key(self.sender_handle)
else:
sender_key = fetch_public_key(self.sender_handle)
if not sender_key:
raise NoSenderKeyFoundError("Could not find a sender contact to retrieve key")
MagicEnvelope(doc=self.doc, public_key=sender_key, verify=True) | python | def verify_signature(self):
"""
Verify the signed XML elements to have confidence that the claimed
author did actually generate this message.
"""
if self.get_contact_key:
sender_key = self.get_contact_key(self.sender_handle)
else:
sender_key = fetch_public_key(self.sender_handle)
if not sender_key:
raise NoSenderKeyFoundError("Could not find a sender contact to retrieve key")
MagicEnvelope(doc=self.doc, public_key=sender_key, verify=True) | Verify the signed XML elements to have confidence that the claimed
author did actually generate this message. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L126-L137 |
jaywink/federation | federation/protocols/diaspora/protocol.py | Protocol.build_send | def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]:
"""
Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
:returns: dict or string depending on if private or public payload.
"""
if entity.outbound_doc is not None:
# Use pregenerated outbound document
xml = entity.outbound_doc
else:
xml = entity.to_xml()
me = MagicEnvelope(etree.tostring(xml), private_key=from_user.private_key, author_handle=from_user.handle)
rendered = me.render()
if to_user_key:
return EncryptedPayload.encrypt(rendered, to_user_key)
return rendered | python | def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]:
"""
Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
:returns: dict or string depending on if private or public payload.
"""
if entity.outbound_doc is not None:
# Use pregenerated outbound document
xml = entity.outbound_doc
else:
xml = entity.to_xml()
me = MagicEnvelope(etree.tostring(xml), private_key=from_user.private_key, author_handle=from_user.handle)
rendered = me.render()
if to_user_key:
return EncryptedPayload.encrypt(rendered, to_user_key)
return rendered | Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
:returns: dict or string depending on if private or public payload. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L139-L157 |
jaywink/federation | federation/entities/base.py | Reaction.validate_reaction | def validate_reaction(self):
"""Ensure reaction is of a certain type.
Mainly for future expansion.
"""
if self.reaction not in self._reaction_valid_values:
raise ValueError("reaction should be one of: {valid}".format(
valid=", ".join(self._reaction_valid_values)
)) | python | def validate_reaction(self):
"""Ensure reaction is of a certain type.
Mainly for future expansion.
"""
if self.reaction not in self._reaction_valid_values:
raise ValueError("reaction should be one of: {valid}".format(
valid=", ".join(self._reaction_valid_values)
)) | Ensure reaction is of a certain type.
Mainly for future expansion. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/base.py#L72-L80 |
jaywink/federation | federation/entities/base.py | Relationship.validate_relationship | def validate_relationship(self):
"""Ensure relationship is of a certain type."""
if self.relationship not in self._relationship_valid_values:
raise ValueError("relationship should be one of: {valid}".format(
valid=", ".join(self._relationship_valid_values)
)) | python | def validate_relationship(self):
"""Ensure relationship is of a certain type."""
if self.relationship not in self._relationship_valid_values:
raise ValueError("relationship should be one of: {valid}".format(
valid=", ".join(self._relationship_valid_values)
)) | Ensure relationship is of a certain type. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/base.py#L93-L98 |
jaywink/federation | federation/entities/activitypub/django/views.py | activitypub_object_view | def activitypub_object_view(func):
"""
Generic ActivityPub object view decorator.
Takes an ID and fetches it using the provided function. Renders the ActivityPub object
in JSON if the object is found. Falls back to decorated view, if the content
type doesn't match.
"""
def inner(request, *args, **kwargs):
def get(request, *args, **kwargs):
# TODO remove once AP support is more ready
config = get_configuration()
if not config.get("activitypub"):
return func(request, *args, **kwargs)
fallback = True
accept = request.META.get('HTTP_ACCEPT', '')
for content_type in (
'application/json', 'application/activity+json', 'application/ld+json',
):
if accept.find(content_type) > -1:
fallback = False
break
if fallback:
return func(request, *args, **kwargs)
get_object_function = get_function_from_config('get_object_function')
obj = get_object_function(request)
if not obj:
return HttpResponseNotFound()
as2_obj = obj.as_protocol('activitypub')
return JsonResponse(as2_obj.to_as2(), content_type='application/activity+json')
def post(request, *args, **kwargs):
process_payload_function = get_function_from_config('process_payload_function')
result = process_payload_function(request)
if result:
return JsonResponse({}, content_type='application/json', status=202)
else:
return JsonResponse({"result": "error"}, content_type='application/json', status=400)
if request.method == 'GET':
return get(request, *args, **kwargs)
elif request.method == 'POST' and request.path.endswith('/inbox/'):
return post(request, *args, **kwargs)
return HttpResponse(status=405)
return inner | python | def activitypub_object_view(func):
"""
Generic ActivityPub object view decorator.
Takes an ID and fetches it using the provided function. Renders the ActivityPub object
in JSON if the object is found. Falls back to decorated view, if the content
type doesn't match.
"""
def inner(request, *args, **kwargs):
def get(request, *args, **kwargs):
# TODO remove once AP support is more ready
config = get_configuration()
if not config.get("activitypub"):
return func(request, *args, **kwargs)
fallback = True
accept = request.META.get('HTTP_ACCEPT', '')
for content_type in (
'application/json', 'application/activity+json', 'application/ld+json',
):
if accept.find(content_type) > -1:
fallback = False
break
if fallback:
return func(request, *args, **kwargs)
get_object_function = get_function_from_config('get_object_function')
obj = get_object_function(request)
if not obj:
return HttpResponseNotFound()
as2_obj = obj.as_protocol('activitypub')
return JsonResponse(as2_obj.to_as2(), content_type='application/activity+json')
def post(request, *args, **kwargs):
process_payload_function = get_function_from_config('process_payload_function')
result = process_payload_function(request)
if result:
return JsonResponse({}, content_type='application/json', status=202)
else:
return JsonResponse({"result": "error"}, content_type='application/json', status=400)
if request.method == 'GET':
return get(request, *args, **kwargs)
elif request.method == 'POST' and request.path.endswith('/inbox/'):
return post(request, *args, **kwargs)
return HttpResponse(status=405)
return inner | Generic ActivityPub object view decorator.
Takes an ID and fetches it using the provided function. Renders the ActivityPub object
in JSON if the object is found. Falls back to decorated view, if the content
type doesn't match. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/django/views.py#L6-L56 |
jaywink/federation | federation/entities/activitypub/mappers.py | element_to_objects | def element_to_objects(payload: Dict) -> List:
"""
Transform an Element to a list of entities recursively.
"""
entities = []
cls = MAPPINGS.get(payload.get('type'))
if not cls:
return []
transformed = transform_attributes(payload, cls)
entity = cls(**transformed)
if hasattr(entity, "post_receive"):
entity.post_receive()
entities.append(entity)
return entities | python | def element_to_objects(payload: Dict) -> List:
"""
Transform an Element to a list of entities recursively.
"""
entities = []
cls = MAPPINGS.get(payload.get('type'))
if not cls:
return []
transformed = transform_attributes(payload, cls)
entity = cls(**transformed)
if hasattr(entity, "post_receive"):
entity.post_receive()
entities.append(entity)
return entities | Transform an Element to a list of entities recursively. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/mappers.py#L15-L32 |
jaywink/federation | federation/entities/activitypub/mappers.py | get_outbound_entity | def get_outbound_entity(entity: BaseEntity, private_key):
"""Get the correct outbound entity for this protocol.
We might have to look at entity values to decide the correct outbound entity.
If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol.
Private key of author is needed to be passed for signing the outbound entity.
:arg entity: An entity instance which can be of a base or protocol entity class.
:arg private_key: Private key of sender in str format
:returns: Protocol specific entity class instance.
:raises ValueError: If conversion cannot be done.
"""
if getattr(entity, "outbound_doc", None):
# If the entity already has an outbound doc, just return the entity as is
return entity
outbound = None
cls = entity.__class__
if cls in [ActivitypubAccept, ActivitypubFollow, ActivitypubProfile]:
# Already fine
outbound = entity
elif cls == Accept:
outbound = ActivitypubAccept.from_base(entity)
elif cls == Follow:
outbound = ActivitypubFollow.from_base(entity)
elif cls == Profile:
outbound = ActivitypubProfile.from_base(entity)
if not outbound:
raise ValueError("Don't know how to convert this base entity to ActivityPub protocol entities.")
# TODO LDS signing
# if isinstance(outbound, DiasporaRelayableMixin) and not outbound.signature:
# # Sign by author if not signed yet. We don't want to overwrite any existing signature in the case
# # that this is being sent by the parent author
# outbound.sign(private_key)
# # If missing, also add same signature to `parent_author_signature`. This is required at the moment
# # in all situations but is apparently being removed.
# # TODO: remove this once Diaspora removes the extra signature
# outbound.parent_signature = outbound.signature
return outbound | python | def get_outbound_entity(entity: BaseEntity, private_key):
"""Get the correct outbound entity for this protocol.
We might have to look at entity values to decide the correct outbound entity.
If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol.
Private key of author is needed to be passed for signing the outbound entity.
:arg entity: An entity instance which can be of a base or protocol entity class.
:arg private_key: Private key of sender in str format
:returns: Protocol specific entity class instance.
:raises ValueError: If conversion cannot be done.
"""
if getattr(entity, "outbound_doc", None):
# If the entity already has an outbound doc, just return the entity as is
return entity
outbound = None
cls = entity.__class__
if cls in [ActivitypubAccept, ActivitypubFollow, ActivitypubProfile]:
# Already fine
outbound = entity
elif cls == Accept:
outbound = ActivitypubAccept.from_base(entity)
elif cls == Follow:
outbound = ActivitypubFollow.from_base(entity)
elif cls == Profile:
outbound = ActivitypubProfile.from_base(entity)
if not outbound:
raise ValueError("Don't know how to convert this base entity to ActivityPub protocol entities.")
# TODO LDS signing
# if isinstance(outbound, DiasporaRelayableMixin) and not outbound.signature:
# # Sign by author if not signed yet. We don't want to overwrite any existing signature in the case
# # that this is being sent by the parent author
# outbound.sign(private_key)
# # If missing, also add same signature to `parent_author_signature`. This is required at the moment
# # in all situations but is apparently being removed.
# # TODO: remove this once Diaspora removes the extra signature
# outbound.parent_signature = outbound.signature
return outbound | Get the correct outbound entity for this protocol.
We might have to look at entity values to decide the correct outbound entity.
If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol.
Private key of author is needed to be passed for signing the outbound entity.
:arg entity: An entity instance which can be of a base or protocol entity class.
:arg private_key: Private key of sender in str format
:returns: Protocol specific entity class instance.
:raises ValueError: If conversion cannot be done. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/mappers.py#L35-L73 |
jaywink/federation | federation/entities/activitypub/mappers.py | message_to_objects | def message_to_objects(
message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None,
) -> List:
"""
Takes in a message extracted by a protocol and maps it to entities.
"""
# We only really expect one element here for ActivityPub.
return element_to_objects(message) | python | def message_to_objects(
message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None,
) -> List:
"""
Takes in a message extracted by a protocol and maps it to entities.
"""
# We only really expect one element here for ActivityPub.
return element_to_objects(message) | Takes in a message extracted by a protocol and maps it to entities. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/mappers.py#L76-L83 |
jaywink/federation | federation/entities/mixins.py | BaseEntity.validate | def validate(self):
"""Do validation.
1) Check `_required` have been given
2) Make sure all attrs in required have a non-empty value
3) Loop through attributes and call their `validate_<attr>` methods, if any.
4) Validate allowed children
5) Validate signatures
"""
attributes = []
validates = []
# Collect attributes and validation methods
for attr in dir(self):
if not attr.startswith("_"):
attr_type = type(getattr(self, attr))
if attr_type != "method":
if getattr(self, "validate_{attr}".format(attr=attr), None):
validates.append(getattr(self, "validate_{attr}".format(attr=attr)))
attributes.append(attr)
self._validate_empty_attributes(attributes)
self._validate_required(attributes)
self._validate_attributes(validates)
self._validate_children()
self._validate_signatures() | python | def validate(self):
"""Do validation.
1) Check `_required` have been given
2) Make sure all attrs in required have a non-empty value
3) Loop through attributes and call their `validate_<attr>` methods, if any.
4) Validate allowed children
5) Validate signatures
"""
attributes = []
validates = []
# Collect attributes and validation methods
for attr in dir(self):
if not attr.startswith("_"):
attr_type = type(getattr(self, attr))
if attr_type != "method":
if getattr(self, "validate_{attr}".format(attr=attr), None):
validates.append(getattr(self, "validate_{attr}".format(attr=attr)))
attributes.append(attr)
self._validate_empty_attributes(attributes)
self._validate_required(attributes)
self._validate_attributes(validates)
self._validate_children()
self._validate_signatures() | Do validation.
1) Check `_required` have been given
2) Make sure all attrs in required have a non-empty value
3) Loop through attributes and call their `validate_<attr>` methods, if any.
4) Validate allowed children
5) Validate signatures | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L48-L71 |
jaywink/federation | federation/entities/mixins.py | BaseEntity._validate_required | def _validate_required(self, attributes):
"""Ensure required attributes are present."""
required_fulfilled = set(self._required).issubset(set(attributes))
if not required_fulfilled:
raise ValueError(
"Not all required attributes fulfilled. Required: {required}".format(required=set(self._required))
) | python | def _validate_required(self, attributes):
"""Ensure required attributes are present."""
required_fulfilled = set(self._required).issubset(set(attributes))
if not required_fulfilled:
raise ValueError(
"Not all required attributes fulfilled. Required: {required}".format(required=set(self._required))
) | Ensure required attributes are present. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L73-L79 |
jaywink/federation | federation/entities/mixins.py | BaseEntity._validate_empty_attributes | def _validate_empty_attributes(self, attributes):
"""Check that required attributes are not empty."""
attrs_to_check = set(self._required) & set(attributes)
for attr in attrs_to_check:
value = getattr(self, attr) # We should always have a value here
if value is None or value == "":
raise ValueError(
"Attribute %s cannot be None or an empty string since it is required." % attr
) | python | def _validate_empty_attributes(self, attributes):
"""Check that required attributes are not empty."""
attrs_to_check = set(self._required) & set(attributes)
for attr in attrs_to_check:
value = getattr(self, attr) # We should always have a value here
if value is None or value == "":
raise ValueError(
"Attribute %s cannot be None or an empty string since it is required." % attr
) | Check that required attributes are not empty. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L86-L94 |
jaywink/federation | federation/entities/mixins.py | BaseEntity._validate_children | def _validate_children(self):
"""Check that the children we have are allowed here."""
for child in self._children:
if child.__class__ not in self._allowed_children:
raise ValueError(
"Child %s is not allowed as a children for this %s type entity." % (
child, self.__class__
)
) | python | def _validate_children(self):
"""Check that the children we have are allowed here."""
for child in self._children:
if child.__class__ not in self._allowed_children:
raise ValueError(
"Child %s is not allowed as a children for this %s type entity." % (
child, self.__class__
)
) | Check that the children we have are allowed here. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L96-L104 |
jaywink/federation | federation/entities/mixins.py | ParticipationMixin.validate_participation | def validate_participation(self):
"""Ensure participation is of a certain type."""
if self.participation not in self._participation_valid_values:
raise ValueError("participation should be one of: {valid}".format(
valid=", ".join(self._participation_valid_values)
)) | python | def validate_participation(self):
"""Ensure participation is of a certain type."""
if self.participation not in self._participation_valid_values:
raise ValueError("participation should be one of: {valid}".format(
valid=", ".join(self._participation_valid_values)
)) | Ensure participation is of a certain type. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L147-L152 |
jaywink/federation | federation/entities/mixins.py | RawContentMixin.tags | def tags(self):
"""Returns a `set` of unique tags contained in `raw_content`."""
if not self.raw_content:
return set()
return {word.strip("#").lower() for word in self.raw_content.split() if word.startswith("#") and len(word) > 1} | python | def tags(self):
"""Returns a `set` of unique tags contained in `raw_content`."""
if not self.raw_content:
return set()
return {word.strip("#").lower() for word in self.raw_content.split() if word.startswith("#") and len(word) > 1} | Returns a `set` of unique tags contained in `raw_content`. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L173-L177 |
jaywink/federation | federation/outbound.py | handle_create_payload | def handle_create_payload(
entity: BaseEntity,
author_user: UserType,
protocol_name: str,
to_user_key: RsaKey = None,
parent_user: UserType = None,
) -> str:
"""Create a payload with the given protocol.
Any given user arguments must have ``private_key`` and ``handle`` attributes.
:arg entity: Entity object to send. Can be a base entity or a protocol specific one.
:arg author_user: User authoring the object.
:arg protocol_name: Protocol to create payload for.
:arg to_user_key: Public key of user private payload is being sent to, required for private payloads.
:arg parent_user: (Optional) User object of the parent object, if there is one. This must be given for the
Diaspora protocol if a parent object exists, so that a proper ``parent_author_signature`` can
be generated. If given, the payload will be sent as this user.
:returns: Built payload message (str)
"""
mappers = importlib.import_module(f"federation.entities.{protocol_name}.mappers")
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol")
protocol = protocol.Protocol()
outbound_entity = mappers.get_outbound_entity(entity, author_user.private_key)
if parent_user:
outbound_entity.sign_with_parent(parent_user.private_key)
send_as_user = parent_user if parent_user else author_user
data = protocol.build_send(entity=outbound_entity, from_user=send_as_user, to_user_key=to_user_key)
return data | python | def handle_create_payload(
entity: BaseEntity,
author_user: UserType,
protocol_name: str,
to_user_key: RsaKey = None,
parent_user: UserType = None,
) -> str:
"""Create a payload with the given protocol.
Any given user arguments must have ``private_key`` and ``handle`` attributes.
:arg entity: Entity object to send. Can be a base entity or a protocol specific one.
:arg author_user: User authoring the object.
:arg protocol_name: Protocol to create payload for.
:arg to_user_key: Public key of user private payload is being sent to, required for private payloads.
:arg parent_user: (Optional) User object of the parent object, if there is one. This must be given for the
Diaspora protocol if a parent object exists, so that a proper ``parent_author_signature`` can
be generated. If given, the payload will be sent as this user.
:returns: Built payload message (str)
"""
mappers = importlib.import_module(f"federation.entities.{protocol_name}.mappers")
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol")
protocol = protocol.Protocol()
outbound_entity = mappers.get_outbound_entity(entity, author_user.private_key)
if parent_user:
outbound_entity.sign_with_parent(parent_user.private_key)
send_as_user = parent_user if parent_user else author_user
data = protocol.build_send(entity=outbound_entity, from_user=send_as_user, to_user_key=to_user_key)
return data | Create a payload with the given protocol.
Any given user arguments must have ``private_key`` and ``handle`` attributes.
:arg entity: Entity object to send. Can be a base entity or a protocol specific one.
:arg author_user: User authoring the object.
:arg protocol_name: Protocol to create payload for.
:arg to_user_key: Public key of user private payload is being sent to, required for private payloads.
:arg parent_user: (Optional) User object of the parent object, if there is one. This must be given for the
Diaspora protocol if a parent object exists, so that a proper ``parent_author_signature`` can
be generated. If given, the payload will be sent as this user.
:returns: Built payload message (str) | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/outbound.py#L17-L45 |
jaywink/federation | federation/outbound.py | handle_send | def handle_send(
entity: BaseEntity,
author_user: UserType,
recipients: List[Dict],
parent_user: UserType = None,
) -> None:
"""Send an entity to remote servers.
Using this we will build a list of payloads per protocol. After that, each recipient will get the generated
protocol payload delivered. Delivery to the same endpoint will only be done once so it's ok to include
the same endpoint as a receiver multiple times.
Any given user arguments must have ``private_key`` and ``fid`` attributes.
:arg entity: Entity object to send. Can be a base entity or a protocol specific one.
:arg author_user: User authoring the object.
:arg recipients: A list of recipients to delivery to. Each recipient is a dict
containing at minimum the "fid", "public" and "protocol" keys.
For ActivityPub and Diaspora payloads, "fid" should be an URL of the endpoint to deliver to.
The "protocol" should be a protocol name that is known for this recipient.
The "public" value should be a boolean to indicate whether the payload should be flagged as a
public payload.
TODO: support guessing the protocol over networks? Would need caching of results
For private deliveries to Diaspora protocol recipients, "public_key" is also required.
For example
[
{
"fid": "https://domain.tld/receive/users/1234-5678-0123-4567",
"protocol": "diaspora",
"public": False,
"public_key": <RSAPublicKey object>,
},
{
"fid": "https://domain2.tld/receive/public",
"protocol": "diaspora",
"public": True,
},
{
"fid": "https://domain4.tld/sharedinbox/",
"protocol": "activitypub",
"public": True,
},
{
"fid": "https://domain4.tld/profiles/jill",
"protocol": "activitypub",
"public": False,
},
]
:arg parent_user: (Optional) User object of the parent object, if there is one. This must be given for the
Diaspora protocol if a parent object exists, so that a proper ``parent_author_signature`` can
be generated. If given, the payload will be sent as this user.
"""
payloads = []
public_payloads = {
"activitypub": {
"auth": None,
"payload": None,
"urls": set(),
},
"diaspora": {
"auth": None,
"payload": None,
"urls": set(),
},
}
# Flatten to unique recipients
unique_recipients = unique_everseen(recipients)
# Generate payloads and collect urls
for recipient in unique_recipients:
fid = recipient["fid"]
public_key = recipient.get("public_key")
protocol = recipient["protocol"]
public = recipient["public"]
if protocol == "activitypub":
try:
payload = handle_create_payload(entity, author_user, protocol, parent_user=parent_user)
if public:
payload["to"] = "https://www.w3.org/ns/activitystreams#Public"
else:
payload["to"] = fid
payload = json.dumps(payload).encode("utf-8")
except Exception as ex:
logger.error("handle_send - failed to generate private payload for %s: %s", fid, ex)
continue
payloads.append({
"auth": get_http_authentication(author_user.private_key, f"{author_user.id}#main-key"),
"payload": payload,
"content_type": 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
"urls": {fid},
})
elif protocol == "diaspora":
if public:
if public_key:
raise ValueError("handle_send - Diaspora recipient cannot be public and use encrypted delivery")
if not public_payloads[protocol]["payload"]:
public_payloads[protocol]["payload"] = handle_create_payload(
entity, author_user, protocol, parent_user=parent_user,
)
public_payloads["diaspora"]["urls"].add(fid)
else:
if not public_key:
raise ValueError("handle_send - Diaspora recipient cannot be private without a public key for "
"encrypted delivery")
# Private payload
try:
payload = handle_create_payload(
entity, author_user, "diaspora", to_user_key=public_key, parent_user=parent_user,
)
payload = json.dumps(payload)
except Exception as ex:
logger.error("handle_send - failed to generate private payload for %s: %s", fid, ex)
continue
payloads.append({
"urls": {fid}, "payload": payload, "content_type": "application/json", "auth": None,
})
# Add public diaspora payload
if public_payloads["diaspora"]["payload"]:
payloads.append({
"urls": public_payloads["diaspora"]["urls"], "payload": public_payloads["diaspora"]["payload"],
"content_type": "application/magic-envelope+xml", "auth": None,
})
logger.debug("handle_send - %s", payloads)
# Do actual sending
for payload in payloads:
for url in payload["urls"]:
try:
send_document(
url,
payload["payload"],
auth=payload["auth"],
headers={"Content-Type": payload["content_type"]},
)
except Exception as ex:
logger.error("handle_send - failed to send payload to %s: %s, payload: %s", url, ex, payload["payload"]) | python | def handle_send(
entity: BaseEntity,
author_user: UserType,
recipients: List[Dict],
parent_user: UserType = None,
) -> None:
"""Send an entity to remote servers.
Using this we will build a list of payloads per protocol. After that, each recipient will get the generated
protocol payload delivered. Delivery to the same endpoint will only be done once so it's ok to include
the same endpoint as a receiver multiple times.
Any given user arguments must have ``private_key`` and ``fid`` attributes.
:arg entity: Entity object to send. Can be a base entity or a protocol specific one.
:arg author_user: User authoring the object.
:arg recipients: A list of recipients to delivery to. Each recipient is a dict
containing at minimum the "fid", "public" and "protocol" keys.
For ActivityPub and Diaspora payloads, "fid" should be an URL of the endpoint to deliver to.
The "protocol" should be a protocol name that is known for this recipient.
The "public" value should be a boolean to indicate whether the payload should be flagged as a
public payload.
TODO: support guessing the protocol over networks? Would need caching of results
For private deliveries to Diaspora protocol recipients, "public_key" is also required.
For example
[
{
"fid": "https://domain.tld/receive/users/1234-5678-0123-4567",
"protocol": "diaspora",
"public": False,
"public_key": <RSAPublicKey object>,
},
{
"fid": "https://domain2.tld/receive/public",
"protocol": "diaspora",
"public": True,
},
{
"fid": "https://domain4.tld/sharedinbox/",
"protocol": "activitypub",
"public": True,
},
{
"fid": "https://domain4.tld/profiles/jill",
"protocol": "activitypub",
"public": False,
},
]
:arg parent_user: (Optional) User object of the parent object, if there is one. This must be given for the
Diaspora protocol if a parent object exists, so that a proper ``parent_author_signature`` can
be generated. If given, the payload will be sent as this user.
"""
payloads = []
public_payloads = {
"activitypub": {
"auth": None,
"payload": None,
"urls": set(),
},
"diaspora": {
"auth": None,
"payload": None,
"urls": set(),
},
}
# Flatten to unique recipients
unique_recipients = unique_everseen(recipients)
# Generate payloads and collect urls
for recipient in unique_recipients:
fid = recipient["fid"]
public_key = recipient.get("public_key")
protocol = recipient["protocol"]
public = recipient["public"]
if protocol == "activitypub":
try:
payload = handle_create_payload(entity, author_user, protocol, parent_user=parent_user)
if public:
payload["to"] = "https://www.w3.org/ns/activitystreams#Public"
else:
payload["to"] = fid
payload = json.dumps(payload).encode("utf-8")
except Exception as ex:
logger.error("handle_send - failed to generate private payload for %s: %s", fid, ex)
continue
payloads.append({
"auth": get_http_authentication(author_user.private_key, f"{author_user.id}#main-key"),
"payload": payload,
"content_type": 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
"urls": {fid},
})
elif protocol == "diaspora":
if public:
if public_key:
raise ValueError("handle_send - Diaspora recipient cannot be public and use encrypted delivery")
if not public_payloads[protocol]["payload"]:
public_payloads[protocol]["payload"] = handle_create_payload(
entity, author_user, protocol, parent_user=parent_user,
)
public_payloads["diaspora"]["urls"].add(fid)
else:
if not public_key:
raise ValueError("handle_send - Diaspora recipient cannot be private without a public key for "
"encrypted delivery")
# Private payload
try:
payload = handle_create_payload(
entity, author_user, "diaspora", to_user_key=public_key, parent_user=parent_user,
)
payload = json.dumps(payload)
except Exception as ex:
logger.error("handle_send - failed to generate private payload for %s: %s", fid, ex)
continue
payloads.append({
"urls": {fid}, "payload": payload, "content_type": "application/json", "auth": None,
})
# Add public diaspora payload
if public_payloads["diaspora"]["payload"]:
payloads.append({
"urls": public_payloads["diaspora"]["urls"], "payload": public_payloads["diaspora"]["payload"],
"content_type": "application/magic-envelope+xml", "auth": None,
})
logger.debug("handle_send - %s", payloads)
# Do actual sending
for payload in payloads:
for url in payload["urls"]:
try:
send_document(
url,
payload["payload"],
auth=payload["auth"],
headers={"Content-Type": payload["content_type"]},
)
except Exception as ex:
logger.error("handle_send - failed to send payload to %s: %s, payload: %s", url, ex, payload["payload"]) | Send an entity to remote servers.
Using this we will build a list of payloads per protocol. After that, each recipient will get the generated
protocol payload delivered. Delivery to the same endpoint will only be done once so it's ok to include
the same endpoint as a receiver multiple times.
Any given user arguments must have ``private_key`` and ``fid`` attributes.
:arg entity: Entity object to send. Can be a base entity or a protocol specific one.
:arg author_user: User authoring the object.
:arg recipients: A list of recipients to delivery to. Each recipient is a dict
containing at minimum the "fid", "public" and "protocol" keys.
For ActivityPub and Diaspora payloads, "fid" should be an URL of the endpoint to deliver to.
The "protocol" should be a protocol name that is known for this recipient.
The "public" value should be a boolean to indicate whether the payload should be flagged as a
public payload.
TODO: support guessing the protocol over networks? Would need caching of results
For private deliveries to Diaspora protocol recipients, "public_key" is also required.
For example
[
{
"fid": "https://domain.tld/receive/users/1234-5678-0123-4567",
"protocol": "diaspora",
"public": False,
"public_key": <RSAPublicKey object>,
},
{
"fid": "https://domain2.tld/receive/public",
"protocol": "diaspora",
"public": True,
},
{
"fid": "https://domain4.tld/sharedinbox/",
"protocol": "activitypub",
"public": True,
},
{
"fid": "https://domain4.tld/profiles/jill",
"protocol": "activitypub",
"public": False,
},
]
:arg parent_user: (Optional) User object of the parent object, if there is one. This must be given for the
Diaspora protocol if a parent object exists, so that a proper ``parent_author_signature`` can
be generated. If given, the payload will be sent as this user. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/outbound.py#L48-L193 |
jaywink/federation | federation/protocols/diaspora/magic_envelope.py | MagicEnvelope.get_sender | def get_sender(doc):
"""Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle.
:param doc: ElementTree document
:returns: Diaspora handle
"""
key_id = doc.find(".//{%s}sig" % NAMESPACE).get("key_id")
return urlsafe_b64decode(key_id).decode("utf-8") | python | def get_sender(doc):
"""Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle.
:param doc: ElementTree document
:returns: Diaspora handle
"""
key_id = doc.find(".//{%s}sig" % NAMESPACE).get("key_id")
return urlsafe_b64decode(key_id).decode("utf-8") | Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle.
:param doc: ElementTree document
:returns: Diaspora handle | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L81-L88 |
jaywink/federation | federation/protocols/diaspora/magic_envelope.py | MagicEnvelope.create_payload | def create_payload(self):
"""Create the payload doc.
Returns:
str
"""
doc = etree.fromstring(self.message)
self.payload = etree.tostring(doc, encoding="utf-8")
self.payload = urlsafe_b64encode(self.payload).decode("ascii")
return self.payload | python | def create_payload(self):
"""Create the payload doc.
Returns:
str
"""
doc = etree.fromstring(self.message)
self.payload = etree.tostring(doc, encoding="utf-8")
self.payload = urlsafe_b64encode(self.payload).decode("ascii")
return self.payload | Create the payload doc.
Returns:
str | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L103-L112 |
jaywink/federation | federation/protocols/diaspora/magic_envelope.py | MagicEnvelope._build_signature | def _build_signature(self):
"""Create the signature using the private key."""
sig_contents = \
self.payload + "." + \
b64encode(b"application/xml").decode("ascii") + "." + \
b64encode(b"base64url").decode("ascii") + "." + \
b64encode(b"RSA-SHA256").decode("ascii")
sig_hash = SHA256.new(sig_contents.encode("ascii"))
cipher = PKCS1_v1_5.new(self.private_key)
sig = urlsafe_b64encode(cipher.sign(sig_hash))
key_id = urlsafe_b64encode(bytes(self.author_handle, encoding="utf-8"))
return sig, key_id | python | def _build_signature(self):
"""Create the signature using the private key."""
sig_contents = \
self.payload + "." + \
b64encode(b"application/xml").decode("ascii") + "." + \
b64encode(b"base64url").decode("ascii") + "." + \
b64encode(b"RSA-SHA256").decode("ascii")
sig_hash = SHA256.new(sig_contents.encode("ascii"))
cipher = PKCS1_v1_5.new(self.private_key)
sig = urlsafe_b64encode(cipher.sign(sig_hash))
key_id = urlsafe_b64encode(bytes(self.author_handle, encoding="utf-8"))
return sig, key_id | Create the signature using the private key. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L114-L125 |
jaywink/federation | federation/protocols/diaspora/magic_envelope.py | MagicEnvelope.verify | def verify(self):
"""Verify Magic Envelope document against public key."""
if not self.public_key:
self.fetch_public_key()
data = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text
sig = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text
sig_contents = '.'.join([
data,
b64encode(b"application/xml").decode("ascii"),
b64encode(b"base64url").decode("ascii"),
b64encode(b"RSA-SHA256").decode("ascii")
])
sig_hash = SHA256.new(sig_contents.encode("ascii"))
cipher = PKCS1_v1_5.new(RSA.importKey(self.public_key))
if not cipher.verify(sig_hash, urlsafe_b64decode(sig)):
raise SignatureVerificationError("Signature cannot be verified using the given public key") | python | def verify(self):
"""Verify Magic Envelope document against public key."""
if not self.public_key:
self.fetch_public_key()
data = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text
sig = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text
sig_contents = '.'.join([
data,
b64encode(b"application/xml").decode("ascii"),
b64encode(b"base64url").decode("ascii"),
b64encode(b"RSA-SHA256").decode("ascii")
])
sig_hash = SHA256.new(sig_contents.encode("ascii"))
cipher = PKCS1_v1_5.new(RSA.importKey(self.public_key))
if not cipher.verify(sig_hash, urlsafe_b64decode(sig)):
raise SignatureVerificationError("Signature cannot be verified using the given public key") | Verify Magic Envelope document against public key. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L142-L157 |
jaywink/federation | federation/entities/diaspora/mixins.py | DiasporaEntityMixin.extract_mentions | def extract_mentions(self):
"""
Extract mentions from an entity with ``raw_content``.
:return: set
"""
if not hasattr(self, "raw_content"):
return set()
mentions = re.findall(r'@{[^;]+; [\w.-]+@[^}]+}', self.raw_content)
if not mentions:
return set()
mentions = {s.split(';')[1].strip(' }') for s in mentions}
mentions = {s for s in mentions}
return mentions | python | def extract_mentions(self):
"""
Extract mentions from an entity with ``raw_content``.
:return: set
"""
if not hasattr(self, "raw_content"):
return set()
mentions = re.findall(r'@{[^;]+; [\w.-]+@[^}]+}', self.raw_content)
if not mentions:
return set()
mentions = {s.split(';')[1].strip(' }') for s in mentions}
mentions = {s for s in mentions}
return mentions | Extract mentions from an entity with ``raw_content``.
:return: set | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/mixins.py#L17-L30 |
jaywink/federation | federation/utils/network.py | fetch_country_by_ip | def fetch_country_by_ip(ip):
"""
Fetches country code by IP
Returns empty string if the request fails in non-200 code.
Uses the ipdata.co service which has the following rules:
* Max 1500 requests per day
See: https://ipdata.co/docs.html#python-library
"""
iplookup = ipdata.ipdata()
data = iplookup.lookup(ip)
if data.get('status') != 200:
return ''
return data.get('response', {}).get('country_code', '') | python | def fetch_country_by_ip(ip):
"""
Fetches country code by IP
Returns empty string if the request fails in non-200 code.
Uses the ipdata.co service which has the following rules:
* Max 1500 requests per day
See: https://ipdata.co/docs.html#python-library
"""
iplookup = ipdata.ipdata()
data = iplookup.lookup(ip)
if data.get('status') != 200:
return ''
return data.get('response', {}).get('country_code', '') | Fetches country code by IP
Returns empty string if the request fails in non-200 code.
Uses the ipdata.co service which has the following rules:
* Max 1500 requests per day
See: https://ipdata.co/docs.html#python-library | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L21-L38 |
jaywink/federation | federation/utils/network.py | fetch_document | def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None):
"""Helper method to fetch remote document.
Must be given either the ``url`` or ``host``.
If ``url`` is given, only that will be tried without falling back to http from https.
If ``host`` given, `path` will be added to it. Will fall back to http on non-success status code.
:arg url: Full url to fetch, including protocol
:arg host: Domain part only without path or protocol
:arg path: Path without domain (defaults to "/")
:arg timeout: Seconds to wait for response (defaults to 10)
:arg raise_ssl_errors: Pass False if you want to try HTTP even for sites with SSL errors (default True)
:returns: Tuple of document (str or None), status code (int or None) and error (an exception class instance or None)
:raises ValueError: If neither url nor host are given as parameters
"""
if not url and not host:
raise ValueError("Need url or host.")
logger.debug("fetch_document: url=%s, host=%s, path=%s, timeout=%s, raise_ssl_errors=%s",
url, host, path, timeout, raise_ssl_errors)
headers = {'user-agent': USER_AGENT}
if extra_headers:
headers.update(extra_headers)
if url:
# Use url since it was given
logger.debug("fetch_document: trying %s", url)
try:
response = requests.get(url, timeout=timeout, headers=headers)
logger.debug("fetch_document: found document, code %s", response.status_code)
return response.text, response.status_code, None
except RequestException as ex:
logger.debug("fetch_document: exception %s", ex)
return None, None, ex
# Build url with some little sanitizing
host_string = host.replace("http://", "").replace("https://", "").strip("/")
path_string = path if path.startswith("/") else "/%s" % path
url = "https://%s%s" % (host_string, path_string)
logger.debug("fetch_document: trying %s", url)
try:
response = requests.get(url, timeout=timeout, headers=headers)
logger.debug("fetch_document: found document, code %s", response.status_code)
response.raise_for_status()
return response.text, response.status_code, None
except (HTTPError, SSLError, ConnectionError) as ex:
if isinstance(ex, SSLError) and raise_ssl_errors:
logger.debug("fetch_document: exception %s", ex)
return None, None, ex
# Try http then
url = url.replace("https://", "http://")
logger.debug("fetch_document: trying %s", url)
try:
response = requests.get(url, timeout=timeout, headers=headers)
logger.debug("fetch_document: found document, code %s", response.status_code)
response.raise_for_status()
return response.text, response.status_code, None
except RequestException as ex:
logger.debug("fetch_document: exception %s", ex)
return None, None, ex
except RequestException as ex:
logger.debug("fetch_document: exception %s", ex)
return None, None, ex | python | def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None):
"""Helper method to fetch remote document.
Must be given either the ``url`` or ``host``.
If ``url`` is given, only that will be tried without falling back to http from https.
If ``host`` given, `path` will be added to it. Will fall back to http on non-success status code.
:arg url: Full url to fetch, including protocol
:arg host: Domain part only without path or protocol
:arg path: Path without domain (defaults to "/")
:arg timeout: Seconds to wait for response (defaults to 10)
:arg raise_ssl_errors: Pass False if you want to try HTTP even for sites with SSL errors (default True)
:returns: Tuple of document (str or None), status code (int or None) and error (an exception class instance or None)
:raises ValueError: If neither url nor host are given as parameters
"""
if not url and not host:
raise ValueError("Need url or host.")
logger.debug("fetch_document: url=%s, host=%s, path=%s, timeout=%s, raise_ssl_errors=%s",
url, host, path, timeout, raise_ssl_errors)
headers = {'user-agent': USER_AGENT}
if extra_headers:
headers.update(extra_headers)
if url:
# Use url since it was given
logger.debug("fetch_document: trying %s", url)
try:
response = requests.get(url, timeout=timeout, headers=headers)
logger.debug("fetch_document: found document, code %s", response.status_code)
return response.text, response.status_code, None
except RequestException as ex:
logger.debug("fetch_document: exception %s", ex)
return None, None, ex
# Build url with some little sanitizing
host_string = host.replace("http://", "").replace("https://", "").strip("/")
path_string = path if path.startswith("/") else "/%s" % path
url = "https://%s%s" % (host_string, path_string)
logger.debug("fetch_document: trying %s", url)
try:
response = requests.get(url, timeout=timeout, headers=headers)
logger.debug("fetch_document: found document, code %s", response.status_code)
response.raise_for_status()
return response.text, response.status_code, None
except (HTTPError, SSLError, ConnectionError) as ex:
if isinstance(ex, SSLError) and raise_ssl_errors:
logger.debug("fetch_document: exception %s", ex)
return None, None, ex
# Try http then
url = url.replace("https://", "http://")
logger.debug("fetch_document: trying %s", url)
try:
response = requests.get(url, timeout=timeout, headers=headers)
logger.debug("fetch_document: found document, code %s", response.status_code)
response.raise_for_status()
return response.text, response.status_code, None
except RequestException as ex:
logger.debug("fetch_document: exception %s", ex)
return None, None, ex
except RequestException as ex:
logger.debug("fetch_document: exception %s", ex)
return None, None, ex | Helper method to fetch remote document.
Must be given either the ``url`` or ``host``.
If ``url`` is given, only that will be tried without falling back to http from https.
If ``host`` given, `path` will be added to it. Will fall back to http on non-success status code.
:arg url: Full url to fetch, including protocol
:arg host: Domain part only without path or protocol
:arg path: Path without domain (defaults to "/")
:arg timeout: Seconds to wait for response (defaults to 10)
:arg raise_ssl_errors: Pass False if you want to try HTTP even for sites with SSL errors (default True)
:returns: Tuple of document (str or None), status code (int or None) and error (an exception class instance or None)
:raises ValueError: If neither url nor host are given as parameters | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L41-L101 |
jaywink/federation | federation/utils/network.py | fetch_host_ip | def fetch_host_ip(host: str) -> str:
"""
Fetch ip by host
"""
try:
ip = socket.gethostbyname(host)
except socket.gaierror:
return ''
return ip | python | def fetch_host_ip(host: str) -> str:
"""
Fetch ip by host
"""
try:
ip = socket.gethostbyname(host)
except socket.gaierror:
return ''
return ip | Fetch ip by host | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L104-L113 |
jaywink/federation | federation/utils/network.py | fetch_host_ip_and_country | def fetch_host_ip_and_country(host: str) -> Tuple:
"""
Fetch ip and country by host
"""
ip = fetch_host_ip(host)
if not host:
return '', ''
country = fetch_country_by_ip(ip)
return ip, country | python | def fetch_host_ip_and_country(host: str) -> Tuple:
"""
Fetch ip and country by host
"""
ip = fetch_host_ip(host)
if not host:
return '', ''
country = fetch_country_by_ip(ip)
return ip, country | Fetch ip and country by host | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L116-L126 |
jaywink/federation | federation/utils/network.py | parse_http_date | def parse_http_date(date):
"""
Parse a date format as specified by HTTP RFC7231 section 7.1.1.1.
The three formats allowed by the RFC are accepted, even if only the first
one is still in widespread use.
Return an integer expressed in seconds since the epoch, in UTC.
Implementation copied from Django.
https://github.com/django/django/blob/master/django/utils/http.py#L157
License: BSD 3-clause
"""
MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split()
__D = r'(?P<day>\d{2})'
__D2 = r'(?P<day>[ \d]\d)'
__M = r'(?P<mon>\w{3})'
__Y = r'(?P<year>\d{4})'
__Y2 = r'(?P<year>\d{2})'
__T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})'
RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T))
RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
# email.utils.parsedate() does the job for RFC1123 dates; unfortunately
# RFC7231 makes it mandatory to support RFC850 dates too. So we roll
# our own RFC-compliant parsing.
for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
m = regex.match(date)
if m is not None:
break
else:
raise ValueError("%r is not in a valid HTTP date format" % date)
try:
year = int(m.group('year'))
if year < 100:
if year < 70:
year += 2000
else:
year += 1900
month = MONTHS.index(m.group('mon').lower()) + 1
day = int(m.group('day'))
hour = int(m.group('hour'))
min = int(m.group('min'))
sec = int(m.group('sec'))
result = datetime.datetime(year, month, day, hour, min, sec)
return calendar.timegm(result.utctimetuple())
except Exception as exc:
raise ValueError("%r is not a valid date" % date) from exc | python | def parse_http_date(date):
"""
Parse a date format as specified by HTTP RFC7231 section 7.1.1.1.
The three formats allowed by the RFC are accepted, even if only the first
one is still in widespread use.
Return an integer expressed in seconds since the epoch, in UTC.
Implementation copied from Django.
https://github.com/django/django/blob/master/django/utils/http.py#L157
License: BSD 3-clause
"""
MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split()
__D = r'(?P<day>\d{2})'
__D2 = r'(?P<day>[ \d]\d)'
__M = r'(?P<mon>\w{3})'
__Y = r'(?P<year>\d{4})'
__Y2 = r'(?P<year>\d{2})'
__T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})'
RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T))
RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
# email.utils.parsedate() does the job for RFC1123 dates; unfortunately
# RFC7231 makes it mandatory to support RFC850 dates too. So we roll
# our own RFC-compliant parsing.
for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
m = regex.match(date)
if m is not None:
break
else:
raise ValueError("%r is not in a valid HTTP date format" % date)
try:
year = int(m.group('year'))
if year < 100:
if year < 70:
year += 2000
else:
year += 1900
month = MONTHS.index(m.group('mon').lower()) + 1
day = int(m.group('day'))
hour = int(m.group('hour'))
min = int(m.group('min'))
sec = int(m.group('sec'))
result = datetime.datetime(year, month, day, hour, min, sec)
return calendar.timegm(result.utctimetuple())
except Exception as exc:
raise ValueError("%r is not a valid date" % date) from exc | Parse a date format as specified by HTTP RFC7231 section 7.1.1.1.
The three formats allowed by the RFC are accepted, even if only the first
one is still in widespread use.
Return an integer expressed in seconds since the epoch, in UTC.
Implementation copied from Django.
https://github.com/django/django/blob/master/django/utils/http.py#L157
License: BSD 3-clause | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L129-L176 |
jaywink/federation | federation/utils/network.py | send_document | def send_document(url, data, timeout=10, *args, **kwargs):
"""Helper method to send a document via POST.
Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``.
:arg url: Full url to send to, including protocol
:arg data: Dictionary (will be form-encoded), bytes, or file-like object to send in the body
:arg timeout: Seconds to wait for response (defaults to 10)
:returns: Tuple of status code (int or None) and error (exception class instance or None)
"""
logger.debug("send_document: url=%s, data=%s, timeout=%s", url, data, timeout)
headers = CaseInsensitiveDict({
'User-Agent': USER_AGENT,
})
if "headers" in kwargs:
# Update from kwargs
headers.update(kwargs.get("headers"))
kwargs.update({
"data": data, "timeout": timeout, "headers": headers
})
try:
response = requests.post(url, *args, **kwargs)
logger.debug("send_document: response status code %s", response.status_code)
return response.status_code, None
except RequestException as ex:
logger.debug("send_document: exception %s", ex)
return None, ex | python | def send_document(url, data, timeout=10, *args, **kwargs):
"""Helper method to send a document via POST.
Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``.
:arg url: Full url to send to, including protocol
:arg data: Dictionary (will be form-encoded), bytes, or file-like object to send in the body
:arg timeout: Seconds to wait for response (defaults to 10)
:returns: Tuple of status code (int or None) and error (exception class instance or None)
"""
logger.debug("send_document: url=%s, data=%s, timeout=%s", url, data, timeout)
headers = CaseInsensitiveDict({
'User-Agent': USER_AGENT,
})
if "headers" in kwargs:
# Update from kwargs
headers.update(kwargs.get("headers"))
kwargs.update({
"data": data, "timeout": timeout, "headers": headers
})
try:
response = requests.post(url, *args, **kwargs)
logger.debug("send_document: response status code %s", response.status_code)
return response.status_code, None
except RequestException as ex:
logger.debug("send_document: exception %s", ex)
return None, ex | Helper method to send a document via POST.
Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``.
:arg url: Full url to send to, including protocol
:arg data: Dictionary (will be form-encoded), bytes, or file-like object to send in the body
:arg timeout: Seconds to wait for response (defaults to 10)
:returns: Tuple of status code (int or None) and error (exception class instance or None) | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L179-L205 |
jaywink/federation | federation/protocols/activitypub/signing.py | get_http_authentication | def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
"""
Get HTTP signature authentication for a request.
"""
key = private_key.exportKey()
return HTTPSignatureHeaderAuth(
headers=["(request-target)", "user-agent", "host", "date"],
algorithm="rsa-sha256",
key=key,
key_id=private_key_id,
) | python | def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
"""
Get HTTP signature authentication for a request.
"""
key = private_key.exportKey()
return HTTPSignatureHeaderAuth(
headers=["(request-target)", "user-agent", "host", "date"],
algorithm="rsa-sha256",
key=key,
key_id=private_key_id,
) | Get HTTP signature authentication for a request. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/signing.py#L21-L31 |
jaywink/federation | federation/protocols/activitypub/signing.py | verify_request_signature | def verify_request_signature(request: RequestType, public_key: Union[str, bytes]):
"""
Verify HTTP signature in request against a public key.
"""
key = encode_if_text(public_key)
date_header = request.headers.get("Date")
if not date_header:
raise ValueError("Rquest Date header is missing")
ts = parse_http_date(date_header)
dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
delta = datetime.timedelta(seconds=30)
now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
if dt < now - delta or dt > now + delta:
raise ValueError("Request Date is too far in future or past")
HTTPSignatureHeaderAuth.verify(request, key_resolver=lambda **kwargs: key) | python | def verify_request_signature(request: RequestType, public_key: Union[str, bytes]):
"""
Verify HTTP signature in request against a public key.
"""
key = encode_if_text(public_key)
date_header = request.headers.get("Date")
if not date_header:
raise ValueError("Rquest Date header is missing")
ts = parse_http_date(date_header)
dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
delta = datetime.timedelta(seconds=30)
now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
if dt < now - delta or dt > now + delta:
raise ValueError("Request Date is too far in future or past")
HTTPSignatureHeaderAuth.verify(request, key_resolver=lambda **kwargs: key) | Verify HTTP signature in request against a public key. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/signing.py#L34-L50 |
jaywink/federation | federation/entities/diaspora/entities.py | DiasporaPost.to_xml | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"text": self.raw_content},
{"guid": self.guid},
{"author": self.handle},
{"public": "true" if self.public else "false"},
{"created_at": format_dt(self.created_at)},
{"provider_display_name": self.provider_display_name},
])
return element | python | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"text": self.raw_content},
{"guid": self.guid},
{"author": self.handle},
{"public": "true" if self.public else "false"},
{"created_at": format_dt(self.created_at)},
{"provider_display_name": self.provider_display_name},
])
return element | Convert to XML message. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L36-L47 |
jaywink/federation | federation/entities/diaspora/entities.py | DiasporaContact.to_xml | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"recipient": self.target_handle},
{"following": "true" if self.following else "false"},
{"sharing": "true" if self.following else "false"},
])
return element | python | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"recipient": self.target_handle},
{"following": "true" if self.following else "false"},
{"sharing": "true" if self.following else "false"},
])
return element | Convert to XML message. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L77-L86 |
jaywink/federation | federation/entities/diaspora/entities.py | DiasporaProfile.to_xml | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"first_name": self.name},
{"last_name": ""}, # We only have one field - splitting it would be artificial
{"image_url": self.image_urls["large"]},
{"image_url_small": self.image_urls["small"]},
{"image_url_medium": self.image_urls["medium"]},
{"gender": self.gender},
{"bio": self.raw_content},
{"location": self.location},
{"searchable": "true" if self.public else "false"},
{"nsfw": "true" if self.nsfw else "false"},
{"tag_string": " ".join(["#%s" % tag for tag in self.tag_list])},
])
return element | python | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"first_name": self.name},
{"last_name": ""}, # We only have one field - splitting it would be artificial
{"image_url": self.image_urls["large"]},
{"image_url_small": self.image_urls["small"]},
{"image_url_medium": self.image_urls["medium"]},
{"gender": self.gender},
{"bio": self.raw_content},
{"location": self.location},
{"searchable": "true" if self.public else "false"},
{"nsfw": "true" if self.nsfw else "false"},
{"tag_string": " ".join(["#%s" % tag for tag in self.tag_list])},
])
return element | Convert to XML message. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L100-L117 |
jaywink/federation | federation/entities/diaspora/entities.py | DiasporaRetraction.to_xml | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"target_guid": self.target_guid},
{"target_type": DiasporaRetraction.entity_type_to_remote(self.entity_type)},
])
return element | python | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"target_guid": self.target_guid},
{"target_type": DiasporaRetraction.entity_type_to_remote(self.entity_type)},
])
return element | Convert to XML message. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L129-L137 |
jaywink/federation | federation/entities/diaspora/entities.py | DiasporaRetraction.entity_type_to_remote | def entity_type_to_remote(value):
"""Convert entity type between our Entity names and Diaspora names."""
if value in DiasporaRetraction.mapped.values():
values = list(DiasporaRetraction.mapped.values())
index = values.index(value)
return list(DiasporaRetraction.mapped.keys())[index]
return value | python | def entity_type_to_remote(value):
"""Convert entity type between our Entity names and Diaspora names."""
if value in DiasporaRetraction.mapped.values():
values = list(DiasporaRetraction.mapped.values())
index = values.index(value)
return list(DiasporaRetraction.mapped.keys())[index]
return value | Convert entity type between our Entity names and Diaspora names. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L147-L153 |
jaywink/federation | federation/entities/utils.py | get_base_attributes | def get_base_attributes(entity):
"""Build a dict of attributes of an entity.
Returns attributes and their values, ignoring any properties, functions and anything that starts
with an underscore.
"""
attributes = {}
cls = entity.__class__
for attr, _ in inspect.getmembers(cls, lambda o: not isinstance(o, property) and not inspect.isroutine(o)):
if not attr.startswith("_"):
attributes[attr] = getattr(entity, attr)
return attributes | python | def get_base_attributes(entity):
"""Build a dict of attributes of an entity.
Returns attributes and their values, ignoring any properties, functions and anything that starts
with an underscore.
"""
attributes = {}
cls = entity.__class__
for attr, _ in inspect.getmembers(cls, lambda o: not isinstance(o, property) and not inspect.isroutine(o)):
if not attr.startswith("_"):
attributes[attr] = getattr(entity, attr)
return attributes | Build a dict of attributes of an entity.
Returns attributes and their values, ignoring any properties, functions and anything that starts
with an underscore. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/utils.py#L4-L15 |
jaywink/federation | federation/protocols/diaspora/encrypted.py | pkcs7_pad | def pkcs7_pad(inp, block_size):
"""
Using the PKCS#7 padding scheme, pad <inp> to be a multiple of
<block_size> bytes. Ruby's AES encryption pads with this scheme, but
pycrypto doesn't support it.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
val = block_size - len(inp) % block_size
if val == 0:
return inp + (bytes([block_size]) * block_size)
else:
return inp + (bytes([val]) * val) | python | def pkcs7_pad(inp, block_size):
"""
Using the PKCS#7 padding scheme, pad <inp> to be a multiple of
<block_size> bytes. Ruby's AES encryption pads with this scheme, but
pycrypto doesn't support it.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
val = block_size - len(inp) % block_size
if val == 0:
return inp + (bytes([block_size]) * block_size)
else:
return inp + (bytes([val]) * val) | Using the PKCS#7 padding scheme, pad <inp> to be a multiple of
<block_size> bytes. Ruby's AES encryption pads with this scheme, but
pycrypto doesn't support it.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L9-L22 |
jaywink/federation | federation/protocols/diaspora/encrypted.py | pkcs7_unpad | def pkcs7_unpad(data):
"""
Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
if isinstance(data, str):
return data[0:-ord(data[-1])]
else:
return data[0:-data[-1]] | python | def pkcs7_unpad(data):
"""
Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
if isinstance(data, str):
return data[0:-ord(data[-1])]
else:
return data[0:-data[-1]] | Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L25-L35 |
jaywink/federation | federation/protocols/diaspora/encrypted.py | EncryptedPayload.decrypt | def decrypt(payload, private_key):
"""Decrypt an encrypted JSON payload and return the Magic Envelope document inside."""
cipher = PKCS1_v1_5.new(private_key)
aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None)
aes_key = json.loads(aes_key_str.decode("utf-8"))
key = b64decode(aes_key.get("key"))
iv = b64decode(aes_key.get("iv"))
encrypted_magic_envelope = b64decode(payload.get("encrypted_magic_envelope"))
encrypter = AES.new(key, AES.MODE_CBC, iv)
content = encrypter.decrypt(encrypted_magic_envelope)
return etree.fromstring(pkcs7_unpad(content)) | python | def decrypt(payload, private_key):
"""Decrypt an encrypted JSON payload and return the Magic Envelope document inside."""
cipher = PKCS1_v1_5.new(private_key)
aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None)
aes_key = json.loads(aes_key_str.decode("utf-8"))
key = b64decode(aes_key.get("key"))
iv = b64decode(aes_key.get("iv"))
encrypted_magic_envelope = b64decode(payload.get("encrypted_magic_envelope"))
encrypter = AES.new(key, AES.MODE_CBC, iv)
content = encrypter.decrypt(encrypted_magic_envelope)
return etree.fromstring(pkcs7_unpad(content)) | Decrypt an encrypted JSON payload and return the Magic Envelope document inside. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L42-L52 |
jaywink/federation | federation/protocols/diaspora/encrypted.py | EncryptedPayload.encrypt | def encrypt(payload, public_key):
"""
Encrypt a payload using an encrypted JSON wrapper.
See: https://diaspora.github.io/diaspora_federation/federation/encryption.html
:param payload: Payload document as a string.
:param public_key: Public key of recipient as an RSA object.
:return: Encrypted JSON wrapper as dict.
"""
iv, key, encrypter = EncryptedPayload.get_iv_key_encrypter()
aes_key_json = EncryptedPayload.get_aes_key_json(iv, key)
cipher = PKCS1_v1_5.new(public_key)
aes_key = b64encode(cipher.encrypt(aes_key_json))
padded_payload = pkcs7_pad(payload.encode("utf-8"), AES.block_size)
encrypted_me = b64encode(encrypter.encrypt(padded_payload))
return {
"aes_key": aes_key.decode("utf-8"),
"encrypted_magic_envelope": encrypted_me.decode("utf8"),
} | python | def encrypt(payload, public_key):
"""
Encrypt a payload using an encrypted JSON wrapper.
See: https://diaspora.github.io/diaspora_federation/federation/encryption.html
:param payload: Payload document as a string.
:param public_key: Public key of recipient as an RSA object.
:return: Encrypted JSON wrapper as dict.
"""
iv, key, encrypter = EncryptedPayload.get_iv_key_encrypter()
aes_key_json = EncryptedPayload.get_aes_key_json(iv, key)
cipher = PKCS1_v1_5.new(public_key)
aes_key = b64encode(cipher.encrypt(aes_key_json))
padded_payload = pkcs7_pad(payload.encode("utf-8"), AES.block_size)
encrypted_me = b64encode(encrypter.encrypt(padded_payload))
return {
"aes_key": aes_key.decode("utf-8"),
"encrypted_magic_envelope": encrypted_me.decode("utf8"),
} | Encrypt a payload using an encrypted JSON wrapper.
See: https://diaspora.github.io/diaspora_federation/federation/encryption.html
:param payload: Payload document as a string.
:param public_key: Public key of recipient as an RSA object.
:return: Encrypted JSON wrapper as dict. | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L69-L88 |
vilmibm/prosaic | prosaic/commands.py | ProsaicArgParser.template | def template(self):
"""Returns the template in JSON form"""
if self._template:
return self._template
template_json = self.read_template(self.args.tmplname)
self._template = loads(template_json)
return self._template | python | def template(self):
"""Returns the template in JSON form"""
if self._template:
return self._template
template_json = self.read_template(self.args.tmplname)
self._template = loads(template_json)
return self._template | Returns the template in JSON form | https://github.com/vilmibm/prosaic/blob/6edb9af836012611e00966b5e05da0a7bddd25f2/prosaic/commands.py#L75-L83 |
vmig/pylogrus | pylogrus/base.py | BaseFormatter.formatTime | def formatTime(self, record, datefmt=None):
"""Return the creation time of the specified LogRecord as formatted text.
If ``datefmt`` (a string) is specified, it is used to format the creation time of the record.
If ``datefmt`` is 'Z' then creation time of the record will be in Zulu Time Zone.
Otherwise, the ISO8601 format is used.
"""
ct = self.converter(record.created)
if datefmt:
if datefmt == 'Z':
t = time.strftime("%Y-%m-%dT%H:%M:%S", ct)
s = "{}.{:03.0f}Z".format(t, record.msecs)
else:
s = time.strftime(datefmt, ct)
else:
t = time.strftime(self.default_time_format, ct)
s = self.default_msec_format % (t, record.msecs)
return s | python | def formatTime(self, record, datefmt=None):
"""Return the creation time of the specified LogRecord as formatted text.
If ``datefmt`` (a string) is specified, it is used to format the creation time of the record.
If ``datefmt`` is 'Z' then creation time of the record will be in Zulu Time Zone.
Otherwise, the ISO8601 format is used.
"""
ct = self.converter(record.created)
if datefmt:
if datefmt == 'Z':
t = time.strftime("%Y-%m-%dT%H:%M:%S", ct)
s = "{}.{:03.0f}Z".format(t, record.msecs)
else:
s = time.strftime(datefmt, ct)
else:
t = time.strftime(self.default_time_format, ct)
s = self.default_msec_format % (t, record.msecs)
return s | Return the creation time of the specified LogRecord as formatted text.
If ``datefmt`` (a string) is specified, it is used to format the creation time of the record.
If ``datefmt`` is 'Z' then creation time of the record will be in Zulu Time Zone.
Otherwise, the ISO8601 format is used. | https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/base.py#L100-L118 |
vmig/pylogrus | pylogrus/base.py | BaseFormatter.override_level_names | def override_level_names(self, mapping):
"""Rename level names.
:param mapping: Mapping level names to new ones
:type mapping: dict
"""
if not isinstance(mapping, dict):
return
for key, val in mapping.items():
if key in self._level_names:
self._level_names[key] = val | python | def override_level_names(self, mapping):
"""Rename level names.
:param mapping: Mapping level names to new ones
:type mapping: dict
"""
if not isinstance(mapping, dict):
return
for key, val in mapping.items():
if key in self._level_names:
self._level_names[key] = val | Rename level names.
:param mapping: Mapping level names to new ones
:type mapping: dict | https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/base.py#L120-L130 |
vmig/pylogrus | pylogrus/text_formatter.py | TextFormatter.override_colors | def override_colors(self, colors):
"""Override default color of elements.
:param colors: New color value for given elements
:type colors: dict
"""
if not isinstance(colors, dict):
return
for key in self._color[True]:
if key in colors:
self._color[True][key] = colors[key] | python | def override_colors(self, colors):
"""Override default color of elements.
:param colors: New color value for given elements
:type colors: dict
"""
if not isinstance(colors, dict):
return
for key in self._color[True]:
if key in colors:
self._color[True][key] = colors[key] | Override default color of elements.
:param colors: New color value for given elements
:type colors: dict | https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/text_formatter.py#L109-L119 |
vmig/pylogrus | pylogrus/json_formatter.py | JsonFormatter.__prepare_record | def __prepare_record(self, record, enabled_fields):
"""Prepare log record with given fields."""
message = record.getMessage()
if hasattr(record, 'prefix'):
message = "{}{}".format((str(record.prefix) + ' ') if record.prefix else '', message)
obj = {
'name': record.name,
'asctime': self.formatTime(record, self.datefmt),
'created': record.created,
'msecs': record.msecs,
'relativeCreated': record.relativeCreated,
'levelno': record.levelno,
'levelname': self._level_names[record.levelname],
'thread': record.thread,
'threadName': record.threadName,
'process': record.process,
'pathname': record.pathname,
'filename': record.filename,
'module': record.module,
'lineno': record.lineno,
'funcName': record.funcName,
'message': message,
'exception': record.exc_info[0].__name__ if record.exc_info else None,
'stacktrace': record.exc_text,
}
if not isinstance(enabled_fields, list):
enabled_fields = [str(enabled_fields)]
ef = {}
for item in enabled_fields:
if not isinstance(item, (str, tuple)):
continue
if not isinstance(item, tuple):
ef[item] = item
else:
ef[item[0]] = item[1]
result = {}
for key, val in obj.items():
if key in ef:
result[ef[key]] = val
return result | python | def __prepare_record(self, record, enabled_fields):
"""Prepare log record with given fields."""
message = record.getMessage()
if hasattr(record, 'prefix'):
message = "{}{}".format((str(record.prefix) + ' ') if record.prefix else '', message)
obj = {
'name': record.name,
'asctime': self.formatTime(record, self.datefmt),
'created': record.created,
'msecs': record.msecs,
'relativeCreated': record.relativeCreated,
'levelno': record.levelno,
'levelname': self._level_names[record.levelname],
'thread': record.thread,
'threadName': record.threadName,
'process': record.process,
'pathname': record.pathname,
'filename': record.filename,
'module': record.module,
'lineno': record.lineno,
'funcName': record.funcName,
'message': message,
'exception': record.exc_info[0].__name__ if record.exc_info else None,
'stacktrace': record.exc_text,
}
if not isinstance(enabled_fields, list):
enabled_fields = [str(enabled_fields)]
ef = {}
for item in enabled_fields:
if not isinstance(item, (str, tuple)):
continue
if not isinstance(item, tuple):
ef[item] = item
else:
ef[item[0]] = item[1]
result = {}
for key, val in obj.items():
if key in ef:
result[ef[key]] = val
return result | Prepare log record with given fields. | https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/json_formatter.py#L33-L77 |
vmig/pylogrus | pylogrus/json_formatter.py | JsonFormatter.__obj2json | def __obj2json(self, obj):
"""Serialize obj to a JSON formatted string.
This is useful for pretty printing log records in the console.
"""
return json.dumps(obj, indent=self._indent, sort_keys=self._sort_keys) | python | def __obj2json(self, obj):
"""Serialize obj to a JSON formatted string.
This is useful for pretty printing log records in the console.
"""
return json.dumps(obj, indent=self._indent, sort_keys=self._sort_keys) | Serialize obj to a JSON formatted string.
This is useful for pretty printing log records in the console. | https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/json_formatter.py#L79-L84 |
denisenkom/pytds | src/pytds/tls.py | validate_host | def validate_host(cert, name):
"""
Validates host name against certificate
@param cert: Certificate returned by host
@param name: Actual host name used for connection
@return: Returns true if host name matches certificate
"""
cn = None
for t, v in cert.get_subject().get_components():
if t == b'CN':
cn = v
break
if cn == name:
return True
# checking SAN
s_name = name.decode('ascii')
for i in range(cert.get_extension_count()):
ext = cert.get_extension(i)
if ext.get_short_name() == b'subjectAltName':
s = str(ext)
# SANs are usually have form like: DNS:hostname
if s.startswith('DNS:') and s[4:] == s_name:
return True
# TODO handle wildcards
return False | python | def validate_host(cert, name):
"""
Validates host name against certificate
@param cert: Certificate returned by host
@param name: Actual host name used for connection
@return: Returns true if host name matches certificate
"""
cn = None
for t, v in cert.get_subject().get_components():
if t == b'CN':
cn = v
break
if cn == name:
return True
# checking SAN
s_name = name.decode('ascii')
for i in range(cert.get_extension_count()):
ext = cert.get_extension(i)
if ext.get_short_name() == b'subjectAltName':
s = str(ext)
# SANs are usually have form like: DNS:hostname
if s.startswith('DNS:') and s[4:] == s_name:
return True
# TODO handle wildcards
return False | Validates host name against certificate
@param cert: Certificate returned by host
@param name: Actual host name used for connection
@return: Returns true if host name matches certificate | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tls.py#L85-L113 |
denisenkom/pytds | src/pytds/tls.py | revert_to_clear | def revert_to_clear(tds_sock):
"""
Reverts connection back to non-encrypted mode
Used when client sent ENCRYPT_OFF flag
@param tds_sock:
@return:
"""
enc_conn = tds_sock.conn.sock
clear_conn = enc_conn._transport
enc_conn.shutdown()
tds_sock.conn.sock = clear_conn
tds_sock._writer._transport = clear_conn
tds_sock._reader._transport = clear_conn | python | def revert_to_clear(tds_sock):
"""
Reverts connection back to non-encrypted mode
Used when client sent ENCRYPT_OFF flag
@param tds_sock:
@return:
"""
enc_conn = tds_sock.conn.sock
clear_conn = enc_conn._transport
enc_conn.shutdown()
tds_sock.conn.sock = clear_conn
tds_sock._writer._transport = clear_conn
tds_sock._reader._transport = clear_conn | Reverts connection back to non-encrypted mode
Used when client sent ENCRYPT_OFF flag
@param tds_sock:
@return: | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tls.py#L164-L176 |
denisenkom/pytds | src/pytds/tds.py | tds7_crypt_pass | def tds7_crypt_pass(password):
""" Mangle password according to tds rules
:param password: Password str
:returns: Byte-string with encoded password
"""
encoded = bytearray(ucs2_codec.encode(password)[0])
for i, ch in enumerate(encoded):
encoded[i] = ((ch << 4) & 0xff | (ch >> 4)) ^ 0xA5
return encoded | python | def tds7_crypt_pass(password):
""" Mangle password according to tds rules
:param password: Password str
:returns: Byte-string with encoded password
"""
encoded = bytearray(ucs2_codec.encode(password)[0])
for i, ch in enumerate(encoded):
encoded[i] = ((ch << 4) & 0xff | (ch >> 4)) ^ 0xA5
return encoded | Mangle password according to tds rules
:param password: Password str
:returns: Byte-string with encoded password | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L77-L86 |
denisenkom/pytds | src/pytds/tds.py | _TdsReader.unpack | def unpack(self, struc):
""" Unpacks given structure from stream
:param struc: A struct.Struct instance
:returns: Result of unpacking
"""
buf, offset = readall_fast(self, struc.size)
return struc.unpack_from(buf, offset) | python | def unpack(self, struc):
""" Unpacks given structure from stream
:param struc: A struct.Struct instance
:returns: Result of unpacking
"""
buf, offset = readall_fast(self, struc.size)
return struc.unpack_from(buf, offset) | Unpacks given structure from stream
:param struc: A struct.Struct instance
:returns: Result of unpacking | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L159-L166 |
denisenkom/pytds | src/pytds/tds.py | _TdsReader.read_ucs2 | def read_ucs2(self, num_chars):
""" Reads num_chars UCS2 string from the stream """
buf = readall(self, num_chars * 2)
return ucs2_codec.decode(buf)[0] | python | def read_ucs2(self, num_chars):
""" Reads num_chars UCS2 string from the stream """
buf = readall(self, num_chars * 2)
return ucs2_codec.decode(buf)[0] | Reads num_chars UCS2 string from the stream | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L200-L203 |
denisenkom/pytds | src/pytds/tds.py | _TdsReader.get_collation | def get_collation(self):
""" Reads :class:`Collation` object from stream """
buf = readall(self, Collation.wire_size)
return Collation.unpack(buf) | python | def get_collation(self):
""" Reads :class:`Collation` object from stream """
buf = readall(self, Collation.wire_size)
return Collation.unpack(buf) | Reads :class:`Collation` object from stream | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L214-L217 |
denisenkom/pytds | src/pytds/tds.py | _TdsReader._read_packet | def _read_packet(self):
""" Reads next TDS packet from the underlying transport
If timeout is happened during reading of packet's header will
cancel current request.
Can only be called when transport's read pointer is at the begining
of the packet.
"""
try:
pos = 0
while pos < _header.size:
received = self._transport.recv_into(self._bufview[pos:_header.size-pos])
if received == 0:
raise tds_base.ClosedConnectionError()
pos += received
except tds_base.TimeoutError:
self._session.put_cancel()
raise
self._pos = _header.size
self._type, self._status, self._size, self._session._spid, _ = _header.unpack_from(self._bufview, 0)
self._have = pos
while pos < self._size:
received = self._transport.recv_into(self._bufview[pos:], self._size - pos)
if received == 0:
raise tds_base.ClosedConnectionError()
pos += received
self._have += received | python | def _read_packet(self):
""" Reads next TDS packet from the underlying transport
If timeout is happened during reading of packet's header will
cancel current request.
Can only be called when transport's read pointer is at the begining
of the packet.
"""
try:
pos = 0
while pos < _header.size:
received = self._transport.recv_into(self._bufview[pos:_header.size-pos])
if received == 0:
raise tds_base.ClosedConnectionError()
pos += received
except tds_base.TimeoutError:
self._session.put_cancel()
raise
self._pos = _header.size
self._type, self._status, self._size, self._session._spid, _ = _header.unpack_from(self._bufview, 0)
self._have = pos
while pos < self._size:
received = self._transport.recv_into(self._bufview[pos:], self._size - pos)
if received == 0:
raise tds_base.ClosedConnectionError()
pos += received
self._have += received | Reads next TDS packet from the underlying transport
If timeout is happened during reading of packet's header will
cancel current request.
Can only be called when transport's read pointer is at the begining
of the packet. | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L219-L245 |
denisenkom/pytds | src/pytds/tds.py | _TdsReader.read_whole_packet | def read_whole_packet(self):
""" Reads single packet and returns bytes payload of the packet
Can only be called when transport's read pointer is at the beginning
of the packet.
"""
self._read_packet()
return readall(self, self._size - _header.size) | python | def read_whole_packet(self):
""" Reads single packet and returns bytes payload of the packet
Can only be called when transport's read pointer is at the beginning
of the packet.
"""
self._read_packet()
return readall(self, self._size - _header.size) | Reads single packet and returns bytes payload of the packet
Can only be called when transport's read pointer is at the beginning
of the packet. | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L247-L254 |
denisenkom/pytds | src/pytds/tds.py | _TdsWriter.write | def write(self, data):
""" Writes given bytes buffer into the stream
Function returns only when entire buffer is written
"""
data_off = 0
while data_off < len(data):
left = len(self._buf) - self._pos
if left <= 0:
self._write_packet(final=False)
else:
to_write = min(left, len(data) - data_off)
self._buf[self._pos:self._pos + to_write] = data[data_off:data_off + to_write]
self._pos += to_write
data_off += to_write | python | def write(self, data):
""" Writes given bytes buffer into the stream
Function returns only when entire buffer is written
"""
data_off = 0
while data_off < len(data):
left = len(self._buf) - self._pos
if left <= 0:
self._write_packet(final=False)
else:
to_write = min(left, len(data) - data_off)
self._buf[self._pos:self._pos + to_write] = data[data_off:data_off + to_write]
self._pos += to_write
data_off += to_write | Writes given bytes buffer into the stream
Function returns only when entire buffer is written | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L344-L358 |
denisenkom/pytds | src/pytds/tds.py | _TdsWriter.write_string | def write_string(self, s, codec):
""" Write string encoding it with codec into stream """
for i in range(0, len(s), self.bufsize):
chunk = s[i:i + self.bufsize]
buf, consumed = codec.encode(chunk)
assert consumed == len(chunk)
self.write(buf) | python | def write_string(self, s, codec):
""" Write string encoding it with codec into stream """
for i in range(0, len(s), self.bufsize):
chunk = s[i:i + self.bufsize]
buf, consumed = codec.encode(chunk)
assert consumed == len(chunk)
self.write(buf) | Write string encoding it with codec into stream | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L368-L374 |
denisenkom/pytds | src/pytds/tds.py | _TdsWriter._write_packet | def _write_packet(self, final):
""" Writes single TDS packet into underlying transport.
Data for the packet is taken from internal buffer.
:param final: True means this is the final packet in substream.
"""
status = 1 if final else 0
_header.pack_into(self._buf, 0, self._type, status, self._pos, 0, self._packet_no)
self._packet_no = (self._packet_no + 1) % 256
self._transport.sendall(self._buf[:self._pos])
self._pos = 8 | python | def _write_packet(self, final):
""" Writes single TDS packet into underlying transport.
Data for the packet is taken from internal buffer.
:param final: True means this is the final packet in substream.
"""
status = 1 if final else 0
_header.pack_into(self._buf, 0, self._type, status, self._pos, 0, self._packet_no)
self._packet_no = (self._packet_no + 1) % 256
self._transport.sendall(self._buf[:self._pos])
self._pos = 8 | Writes single TDS packet into underlying transport.
Data for the packet is taken from internal buffer.
:param final: True means this is the final packet in substream. | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L380-L391 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.raise_db_exception | def raise_db_exception(self):
""" Raises exception from last server message
This function will skip messages: The statement has been terminated
"""
if not self.messages:
raise tds_base.Error("Request failed, server didn't send error message")
msg = None
while True:
msg = self.messages[-1]
if msg['msgno'] == 3621: # the statement has been terminated
self.messages = self.messages[:-1]
else:
break
error_msg = ' '.join(m['message'] for m in self.messages)
ex = _create_exception_by_message(msg, error_msg)
raise ex | python | def raise_db_exception(self):
""" Raises exception from last server message
This function will skip messages: The statement has been terminated
"""
if not self.messages:
raise tds_base.Error("Request failed, server didn't send error message")
msg = None
while True:
msg = self.messages[-1]
if msg['msgno'] == 3621: # the statement has been terminated
self.messages = self.messages[:-1]
else:
break
error_msg = ' '.join(m['message'] for m in self.messages)
ex = _create_exception_by_message(msg, error_msg)
raise ex | Raises exception from last server message
This function will skip messages: The statement has been terminated | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L467-L484 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.get_type_info | def get_type_info(self, curcol):
""" Reads TYPE_INFO structure (http://msdn.microsoft.com/en-us/library/dd358284.aspx)
:param curcol: An instance of :class:`Column` that will receive read information
"""
r = self._reader
# User defined data type of the column
if tds_base.IS_TDS72_PLUS(self):
user_type = r.get_uint()
else:
user_type = r.get_usmallint()
curcol.column_usertype = user_type
curcol.flags = r.get_usmallint() # Flags
type_id = r.get_byte()
serializer_class = self._tds.type_factory.get_type_serializer(type_id)
curcol.serializer = serializer_class.from_stream(r) | python | def get_type_info(self, curcol):
""" Reads TYPE_INFO structure (http://msdn.microsoft.com/en-us/library/dd358284.aspx)
:param curcol: An instance of :class:`Column` that will receive read information
"""
r = self._reader
# User defined data type of the column
if tds_base.IS_TDS72_PLUS(self):
user_type = r.get_uint()
else:
user_type = r.get_usmallint()
curcol.column_usertype = user_type
curcol.flags = r.get_usmallint() # Flags
type_id = r.get_byte()
serializer_class = self._tds.type_factory.get_type_serializer(type_id)
curcol.serializer = serializer_class.from_stream(r) | Reads TYPE_INFO structure (http://msdn.microsoft.com/en-us/library/dd358284.aspx)
:param curcol: An instance of :class:`Column` that will receive read information | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L486-L501 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.tds7_process_result | def tds7_process_result(self):
""" Reads and processes COLMETADATA stream
This stream contains a list of returned columns.
Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx
"""
self.log_response_message('got COLMETADATA')
r = self._reader
# read number of columns and allocate the columns structure
num_cols = r.get_smallint()
# This can be a DUMMY results token from a cursor fetch
if num_cols == -1:
return
self.param_info = None
self.has_status = False
self.ret_status = None
self.skipped_to_status = False
self.rows_affected = tds_base.TDS_NO_COUNT
self.more_rows = True
self.row = [None] * num_cols
self.res_info = info = _Results()
#
# loop through the columns populating COLINFO struct from
# server response
#
header_tuple = []
for col in range(num_cols):
curcol = tds_base.Column()
info.columns.append(curcol)
self.get_type_info(curcol)
curcol.column_name = r.read_ucs2(r.get_byte())
precision = curcol.serializer.precision
scale = curcol.serializer.scale
size = curcol.serializer.size
header_tuple.append(
(curcol.column_name,
curcol.serializer.get_typeid(),
None,
size,
precision,
scale,
curcol.flags & tds_base.Column.fNullable))
info.description = tuple(header_tuple)
return info | python | def tds7_process_result(self):
""" Reads and processes COLMETADATA stream
This stream contains a list of returned columns.
Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx
"""
self.log_response_message('got COLMETADATA')
r = self._reader
# read number of columns and allocate the columns structure
num_cols = r.get_smallint()
# This can be a DUMMY results token from a cursor fetch
if num_cols == -1:
return
self.param_info = None
self.has_status = False
self.ret_status = None
self.skipped_to_status = False
self.rows_affected = tds_base.TDS_NO_COUNT
self.more_rows = True
self.row = [None] * num_cols
self.res_info = info = _Results()
#
# loop through the columns populating COLINFO struct from
# server response
#
header_tuple = []
for col in range(num_cols):
curcol = tds_base.Column()
info.columns.append(curcol)
self.get_type_info(curcol)
curcol.column_name = r.read_ucs2(r.get_byte())
precision = curcol.serializer.precision
scale = curcol.serializer.scale
size = curcol.serializer.size
header_tuple.append(
(curcol.column_name,
curcol.serializer.get_typeid(),
None,
size,
precision,
scale,
curcol.flags & tds_base.Column.fNullable))
info.description = tuple(header_tuple)
return info | Reads and processes COLMETADATA stream
This stream contains a list of returned columns.
Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L503-L553 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.process_param | def process_param(self):
""" Reads and processes RETURNVALUE stream.
This stream is used to send OUTPUT parameters from RPC to client.
Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx
"""
self.log_response_message('got RETURNVALUE message')
r = self._reader
if tds_base.IS_TDS72_PLUS(self):
ordinal = r.get_usmallint()
else:
r.get_usmallint() # ignore size
ordinal = self._out_params_indexes[self.return_value_index]
name = r.read_ucs2(r.get_byte())
r.get_byte() # 1 - OUTPUT of sp, 2 - result of udf
param = tds_base.Column()
param.column_name = name
self.get_type_info(param)
param.value = param.serializer.read(r)
self.output_params[ordinal] = param
self.return_value_index += 1 | python | def process_param(self):
""" Reads and processes RETURNVALUE stream.
This stream is used to send OUTPUT parameters from RPC to client.
Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx
"""
self.log_response_message('got RETURNVALUE message')
r = self._reader
if tds_base.IS_TDS72_PLUS(self):
ordinal = r.get_usmallint()
else:
r.get_usmallint() # ignore size
ordinal = self._out_params_indexes[self.return_value_index]
name = r.read_ucs2(r.get_byte())
r.get_byte() # 1 - OUTPUT of sp, 2 - result of udf
param = tds_base.Column()
param.column_name = name
self.get_type_info(param)
param.value = param.serializer.read(r)
self.output_params[ordinal] = param
self.return_value_index += 1 | Reads and processes RETURNVALUE stream.
This stream is used to send OUTPUT parameters from RPC to client.
Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L555-L575 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.process_cancel | def process_cancel(self):
"""
Process the incoming token stream until it finds
an end token DONE with the cancel flag set.
At that point the connection should be ready to handle a new query.
In case when no cancel request is pending this function does nothing.
"""
self.log_response_message('got CANCEL message')
# silly cases, nothing to do
if not self.in_cancel:
return
while True:
token_id = self.get_token_id()
self.process_token(token_id)
if not self.in_cancel:
return | python | def process_cancel(self):
"""
Process the incoming token stream until it finds
an end token DONE with the cancel flag set.
At that point the connection should be ready to handle a new query.
In case when no cancel request is pending this function does nothing.
"""
self.log_response_message('got CANCEL message')
# silly cases, nothing to do
if not self.in_cancel:
return
while True:
token_id = self.get_token_id()
self.process_token(token_id)
if not self.in_cancel:
return | Process the incoming token stream until it finds
an end token DONE with the cancel flag set.
At that point the connection should be ready to handle a new query.
In case when no cancel request is pending this function does nothing. | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L577-L594 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.process_msg | def process_msg(self, marker):
""" Reads and processes ERROR/INFO streams
Stream formats:
- ERROR: http://msdn.microsoft.com/en-us/library/dd304156.aspx
- INFO: http://msdn.microsoft.com/en-us/library/dd303398.aspx
:param marker: TDS_ERROR_TOKEN or TDS_INFO_TOKEN
"""
self.log_response_message('got ERROR/INFO message')
r = self._reader
r.get_smallint() # size
msg = {'marker': marker, 'msgno': r.get_int(), 'state': r.get_byte(), 'severity': r.get_byte(),
'sql_state': None}
if marker == tds_base.TDS_INFO_TOKEN:
msg['priv_msg_type'] = 0
elif marker == tds_base.TDS_ERROR_TOKEN:
msg['priv_msg_type'] = 1
else:
logger.error('tds_process_msg() called with unknown marker "{0}"'.format(marker))
msg['message'] = r.read_ucs2(r.get_smallint())
# server name
msg['server'] = r.read_ucs2(r.get_byte())
# stored proc name if available
msg['proc_name'] = r.read_ucs2(r.get_byte())
msg['line_number'] = r.get_int() if tds_base.IS_TDS72_PLUS(self) else r.get_smallint()
# in case extended error data is sent, we just try to discard it
# special case
self.messages.append(msg) | python | def process_msg(self, marker):
""" Reads and processes ERROR/INFO streams
Stream formats:
- ERROR: http://msdn.microsoft.com/en-us/library/dd304156.aspx
- INFO: http://msdn.microsoft.com/en-us/library/dd303398.aspx
:param marker: TDS_ERROR_TOKEN or TDS_INFO_TOKEN
"""
self.log_response_message('got ERROR/INFO message')
r = self._reader
r.get_smallint() # size
msg = {'marker': marker, 'msgno': r.get_int(), 'state': r.get_byte(), 'severity': r.get_byte(),
'sql_state': None}
if marker == tds_base.TDS_INFO_TOKEN:
msg['priv_msg_type'] = 0
elif marker == tds_base.TDS_ERROR_TOKEN:
msg['priv_msg_type'] = 1
else:
logger.error('tds_process_msg() called with unknown marker "{0}"'.format(marker))
msg['message'] = r.read_ucs2(r.get_smallint())
# server name
msg['server'] = r.read_ucs2(r.get_byte())
# stored proc name if available
msg['proc_name'] = r.read_ucs2(r.get_byte())
msg['line_number'] = r.get_int() if tds_base.IS_TDS72_PLUS(self) else r.get_smallint()
# in case extended error data is sent, we just try to discard it
# special case
self.messages.append(msg) | Reads and processes ERROR/INFO streams
Stream formats:
- ERROR: http://msdn.microsoft.com/en-us/library/dd304156.aspx
- INFO: http://msdn.microsoft.com/en-us/library/dd303398.aspx
:param marker: TDS_ERROR_TOKEN or TDS_INFO_TOKEN | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L596-L626 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.process_row | def process_row(self):
""" Reads and handles ROW stream.
This stream contains list of values of one returned row.
Stream format url: http://msdn.microsoft.com/en-us/library/dd357254.aspx
"""
self.log_response_message("got ROW message")
r = self._reader
info = self.res_info
info.row_count += 1
for i, curcol in enumerate(info.columns):
curcol.value = self.row[i] = curcol.serializer.read(r) | python | def process_row(self):
""" Reads and handles ROW stream.
This stream contains list of values of one returned row.
Stream format url: http://msdn.microsoft.com/en-us/library/dd357254.aspx
"""
self.log_response_message("got ROW message")
r = self._reader
info = self.res_info
info.row_count += 1
for i, curcol in enumerate(info.columns):
curcol.value = self.row[i] = curcol.serializer.read(r) | Reads and handles ROW stream.
This stream contains list of values of one returned row.
Stream format url: http://msdn.microsoft.com/en-us/library/dd357254.aspx | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L628-L639 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.process_nbcrow | def process_nbcrow(self):
""" Reads and handles NBCROW stream.
This stream contains list of values of one returned row in a compressed way,
introduced in TDS 7.3.B
Stream format url: http://msdn.microsoft.com/en-us/library/dd304783.aspx
"""
self.log_response_message("got NBCROW message")
r = self._reader
info = self.res_info
if not info:
self.bad_stream('got row without info')
assert len(info.columns) > 0
info.row_count += 1
# reading bitarray for nulls, 1 represent null values for
# corresponding fields
nbc = readall(r, (len(info.columns) + 7) // 8)
for i, curcol in enumerate(info.columns):
if tds_base.my_ord(nbc[i // 8]) & (1 << (i % 8)):
value = None
else:
value = curcol.serializer.read(r)
self.row[i] = value | python | def process_nbcrow(self):
""" Reads and handles NBCROW stream.
This stream contains list of values of one returned row in a compressed way,
introduced in TDS 7.3.B
Stream format url: http://msdn.microsoft.com/en-us/library/dd304783.aspx
"""
self.log_response_message("got NBCROW message")
r = self._reader
info = self.res_info
if not info:
self.bad_stream('got row without info')
assert len(info.columns) > 0
info.row_count += 1
# reading bitarray for nulls, 1 represent null values for
# corresponding fields
nbc = readall(r, (len(info.columns) + 7) // 8)
for i, curcol in enumerate(info.columns):
if tds_base.my_ord(nbc[i // 8]) & (1 << (i % 8)):
value = None
else:
value = curcol.serializer.read(r)
self.row[i] = value | Reads and handles NBCROW stream.
This stream contains list of values of one returned row in a compressed way,
introduced in TDS 7.3.B
Stream format url: http://msdn.microsoft.com/en-us/library/dd304783.aspx | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L641-L664 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.process_end | def process_end(self, marker):
""" Reads and processes DONE/DONEINPROC/DONEPROC streams
Stream format urls:
- DONE: http://msdn.microsoft.com/en-us/library/dd340421.aspx
- DONEINPROC: http://msdn.microsoft.com/en-us/library/dd340553.aspx
- DONEPROC: http://msdn.microsoft.com/en-us/library/dd340753.aspx
:param marker: Can be TDS_DONE_TOKEN or TDS_DONEINPROC_TOKEN or TDS_DONEPROC_TOKEN
"""
code_to_str = {
tds_base.TDS_DONE_TOKEN: 'DONE',
tds_base.TDS_DONEINPROC_TOKEN: 'DONEINPROC',
tds_base.TDS_DONEPROC_TOKEN: 'DONEPROC',
}
self.end_marker = marker
self.more_rows = False
r = self._reader
status = r.get_usmallint()
r.get_usmallint() # cur_cmd
more_results = status & tds_base.TDS_DONE_MORE_RESULTS != 0
was_cancelled = status & tds_base.TDS_DONE_CANCELLED != 0
done_count_valid = status & tds_base.TDS_DONE_COUNT != 0
if self.res_info:
self.res_info.more_results = more_results
rows_affected = r.get_int8() if tds_base.IS_TDS72_PLUS(self) else r.get_int()
self.log_response_message("got {} message, more_res={}, cancelled={}, rows_affected={}".format(
code_to_str[marker], more_results, was_cancelled, rows_affected))
if was_cancelled or (not more_results and not self.in_cancel):
self.in_cancel = False
self.set_state(tds_base.TDS_IDLE)
if done_count_valid:
self.rows_affected = rows_affected
else:
self.rows_affected = -1
self.done_flags = status
if self.done_flags & tds_base.TDS_DONE_ERROR and not was_cancelled and not self.in_cancel:
self.raise_db_exception() | python | def process_end(self, marker):
""" Reads and processes DONE/DONEINPROC/DONEPROC streams
Stream format urls:
- DONE: http://msdn.microsoft.com/en-us/library/dd340421.aspx
- DONEINPROC: http://msdn.microsoft.com/en-us/library/dd340553.aspx
- DONEPROC: http://msdn.microsoft.com/en-us/library/dd340753.aspx
:param marker: Can be TDS_DONE_TOKEN or TDS_DONEINPROC_TOKEN or TDS_DONEPROC_TOKEN
"""
code_to_str = {
tds_base.TDS_DONE_TOKEN: 'DONE',
tds_base.TDS_DONEINPROC_TOKEN: 'DONEINPROC',
tds_base.TDS_DONEPROC_TOKEN: 'DONEPROC',
}
self.end_marker = marker
self.more_rows = False
r = self._reader
status = r.get_usmallint()
r.get_usmallint() # cur_cmd
more_results = status & tds_base.TDS_DONE_MORE_RESULTS != 0
was_cancelled = status & tds_base.TDS_DONE_CANCELLED != 0
done_count_valid = status & tds_base.TDS_DONE_COUNT != 0
if self.res_info:
self.res_info.more_results = more_results
rows_affected = r.get_int8() if tds_base.IS_TDS72_PLUS(self) else r.get_int()
self.log_response_message("got {} message, more_res={}, cancelled={}, rows_affected={}".format(
code_to_str[marker], more_results, was_cancelled, rows_affected))
if was_cancelled or (not more_results and not self.in_cancel):
self.in_cancel = False
self.set_state(tds_base.TDS_IDLE)
if done_count_valid:
self.rows_affected = rows_affected
else:
self.rows_affected = -1
self.done_flags = status
if self.done_flags & tds_base.TDS_DONE_ERROR and not was_cancelled and not self.in_cancel:
self.raise_db_exception() | Reads and processes DONE/DONEINPROC/DONEPROC streams
Stream format urls:
- DONE: http://msdn.microsoft.com/en-us/library/dd340421.aspx
- DONEINPROC: http://msdn.microsoft.com/en-us/library/dd340553.aspx
- DONEPROC: http://msdn.microsoft.com/en-us/library/dd340753.aspx
:param marker: Can be TDS_DONE_TOKEN or TDS_DONEINPROC_TOKEN or TDS_DONEPROC_TOKEN | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L675-L713 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.process_env_chg | def process_env_chg(self):
""" Reads and processes ENVCHANGE stream.
Stream info url: http://msdn.microsoft.com/en-us/library/dd303449.aspx
"""
self.log_response_message("got ENVCHANGE message")
r = self._reader
size = r.get_smallint()
type_id = r.get_byte()
if type_id == tds_base.TDS_ENV_SQLCOLLATION:
size = r.get_byte()
self.conn.collation = r.get_collation()
logger.info('switched collation to %s', self.conn.collation)
skipall(r, size - 5)
# discard old one
skipall(r, r.get_byte())
elif type_id == tds_base.TDS_ENV_BEGINTRANS:
size = r.get_byte()
assert size == 8
self.conn.tds72_transaction = r.get_uint8()
skipall(r, r.get_byte())
elif type_id == tds_base.TDS_ENV_COMMITTRANS or type_id == tds_base.TDS_ENV_ROLLBACKTRANS:
self.conn.tds72_transaction = 0
skipall(r, r.get_byte())
skipall(r, r.get_byte())
elif type_id == tds_base.TDS_ENV_PACKSIZE:
newval = r.read_ucs2(r.get_byte())
r.read_ucs2(r.get_byte())
new_block_size = int(newval)
if new_block_size >= 512:
# Is possible to have a shrink if server limits packet
# size more than what we specified
#
# Reallocate buffer if possible (strange values from server or out of memory) use older buffer */
self._writer.bufsize = new_block_size
elif type_id == tds_base.TDS_ENV_DATABASE:
newval = r.read_ucs2(r.get_byte())
logger.info('switched to database %s', newval)
r.read_ucs2(r.get_byte())
self.conn.env.database = newval
elif type_id == tds_base.TDS_ENV_LANG:
newval = r.read_ucs2(r.get_byte())
logger.info('switched language to %s', newval)
r.read_ucs2(r.get_byte())
self.conn.env.language = newval
elif type_id == tds_base.TDS_ENV_CHARSET:
newval = r.read_ucs2(r.get_byte())
logger.info('switched charset to %s', newval)
r.read_ucs2(r.get_byte())
self.conn.env.charset = newval
remap = {'iso_1': 'iso8859-1'}
self.conn.server_codec = codecs.lookup(remap.get(newval, newval))
elif type_id == tds_base.TDS_ENV_DB_MIRRORING_PARTNER:
newval = r.read_ucs2(r.get_byte())
logger.info('got mirroring partner %s', newval)
r.read_ucs2(r.get_byte())
elif type_id == tds_base.TDS_ENV_LCID:
lcid = int(r.read_ucs2(r.get_byte()))
logger.info('switched lcid to %s', lcid)
self.conn.server_codec = codecs.lookup(lcid2charset(lcid))
r.read_ucs2(r.get_byte())
elif type_id == tds_base.TDS_ENV_UNICODE_DATA_SORT_COMP_FLAGS:
old_comp_flags = r.read_ucs2(r.get_byte())
comp_flags = r.read_ucs2(r.get_byte())
self.conn.comp_flags = comp_flags
elif type_id == 20:
# routing
sz = r.get_usmallint()
protocol = r.get_byte()
protocol_property = r.get_usmallint()
alt_server = r.read_ucs2(r.get_usmallint())
logger.info('got routing info proto=%d proto_prop=%d alt_srv=%s', protocol, protocol_property, alt_server)
self.conn.route = {
'server': alt_server,
'port': protocol_property,
}
# OLDVALUE = 0x00, 0x00
r.get_usmallint()
else:
logger.warning("unknown env type: {0}, skipping".format(type_id))
# discard byte values, not still supported
skipall(r, size - 1) | python | def process_env_chg(self):
""" Reads and processes ENVCHANGE stream.
Stream info url: http://msdn.microsoft.com/en-us/library/dd303449.aspx
"""
self.log_response_message("got ENVCHANGE message")
r = self._reader
size = r.get_smallint()
type_id = r.get_byte()
if type_id == tds_base.TDS_ENV_SQLCOLLATION:
size = r.get_byte()
self.conn.collation = r.get_collation()
logger.info('switched collation to %s', self.conn.collation)
skipall(r, size - 5)
# discard old one
skipall(r, r.get_byte())
elif type_id == tds_base.TDS_ENV_BEGINTRANS:
size = r.get_byte()
assert size == 8
self.conn.tds72_transaction = r.get_uint8()
skipall(r, r.get_byte())
elif type_id == tds_base.TDS_ENV_COMMITTRANS or type_id == tds_base.TDS_ENV_ROLLBACKTRANS:
self.conn.tds72_transaction = 0
skipall(r, r.get_byte())
skipall(r, r.get_byte())
elif type_id == tds_base.TDS_ENV_PACKSIZE:
newval = r.read_ucs2(r.get_byte())
r.read_ucs2(r.get_byte())
new_block_size = int(newval)
if new_block_size >= 512:
# Is possible to have a shrink if server limits packet
# size more than what we specified
#
# Reallocate buffer if possible (strange values from server or out of memory) use older buffer */
self._writer.bufsize = new_block_size
elif type_id == tds_base.TDS_ENV_DATABASE:
newval = r.read_ucs2(r.get_byte())
logger.info('switched to database %s', newval)
r.read_ucs2(r.get_byte())
self.conn.env.database = newval
elif type_id == tds_base.TDS_ENV_LANG:
newval = r.read_ucs2(r.get_byte())
logger.info('switched language to %s', newval)
r.read_ucs2(r.get_byte())
self.conn.env.language = newval
elif type_id == tds_base.TDS_ENV_CHARSET:
newval = r.read_ucs2(r.get_byte())
logger.info('switched charset to %s', newval)
r.read_ucs2(r.get_byte())
self.conn.env.charset = newval
remap = {'iso_1': 'iso8859-1'}
self.conn.server_codec = codecs.lookup(remap.get(newval, newval))
elif type_id == tds_base.TDS_ENV_DB_MIRRORING_PARTNER:
newval = r.read_ucs2(r.get_byte())
logger.info('got mirroring partner %s', newval)
r.read_ucs2(r.get_byte())
elif type_id == tds_base.TDS_ENV_LCID:
lcid = int(r.read_ucs2(r.get_byte()))
logger.info('switched lcid to %s', lcid)
self.conn.server_codec = codecs.lookup(lcid2charset(lcid))
r.read_ucs2(r.get_byte())
elif type_id == tds_base.TDS_ENV_UNICODE_DATA_SORT_COMP_FLAGS:
old_comp_flags = r.read_ucs2(r.get_byte())
comp_flags = r.read_ucs2(r.get_byte())
self.conn.comp_flags = comp_flags
elif type_id == 20:
# routing
sz = r.get_usmallint()
protocol = r.get_byte()
protocol_property = r.get_usmallint()
alt_server = r.read_ucs2(r.get_usmallint())
logger.info('got routing info proto=%d proto_prop=%d alt_srv=%s', protocol, protocol_property, alt_server)
self.conn.route = {
'server': alt_server,
'port': protocol_property,
}
# OLDVALUE = 0x00, 0x00
r.get_usmallint()
else:
logger.warning("unknown env type: {0}, skipping".format(type_id))
# discard byte values, not still supported
skipall(r, size - 1) | Reads and processes ENVCHANGE stream.
Stream info url: http://msdn.microsoft.com/en-us/library/dd303449.aspx | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L715-L796 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.process_auth | def process_auth(self):
""" Reads and processes SSPI stream.
Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx
"""
r = self._reader
w = self._writer
pdu_size = r.get_smallint()
if not self.authentication:
raise tds_base.Error('Got unexpected token')
packet = self.authentication.handle_next(readall(r, pdu_size))
if packet:
w.write(packet)
w.flush() | python | def process_auth(self):
""" Reads and processes SSPI stream.
Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx
"""
r = self._reader
w = self._writer
pdu_size = r.get_smallint()
if not self.authentication:
raise tds_base.Error('Got unexpected token')
packet = self.authentication.handle_next(readall(r, pdu_size))
if packet:
w.write(packet)
w.flush() | Reads and processes SSPI stream.
Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L798-L811 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.set_state | def set_state(self, state):
""" Switches state of the TDS session.
It also does state transitions checks.
:param state: New state, one of TDS_PENDING/TDS_READING/TDS_IDLE/TDS_DEAD/TDS_QUERING
"""
prior_state = self.state
if state == prior_state:
return state
if state == tds_base.TDS_PENDING:
if prior_state in (tds_base.TDS_READING, tds_base.TDS_QUERYING):
self.state = tds_base.TDS_PENDING
else:
raise tds_base.InterfaceError('logic error: cannot chage query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
elif state == tds_base.TDS_READING:
# transition to READING are valid only from PENDING
if self.state != tds_base.TDS_PENDING:
raise tds_base.InterfaceError('logic error: cannot change query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
else:
self.state = state
elif state == tds_base.TDS_IDLE:
if prior_state == tds_base.TDS_DEAD:
raise tds_base.InterfaceError('logic error: cannot change query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
self.state = state
elif state == tds_base.TDS_DEAD:
self.state = state
elif state == tds_base.TDS_QUERYING:
if self.state == tds_base.TDS_DEAD:
raise tds_base.InterfaceError('logic error: cannot change query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
elif self.state != tds_base.TDS_IDLE:
raise tds_base.InterfaceError('logic error: cannot change query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
else:
self.rows_affected = tds_base.TDS_NO_COUNT
self.internal_sp_called = 0
self.state = state
else:
assert False
return self.state | python | def set_state(self, state):
""" Switches state of the TDS session.
It also does state transitions checks.
:param state: New state, one of TDS_PENDING/TDS_READING/TDS_IDLE/TDS_DEAD/TDS_QUERING
"""
prior_state = self.state
if state == prior_state:
return state
if state == tds_base.TDS_PENDING:
if prior_state in (tds_base.TDS_READING, tds_base.TDS_QUERYING):
self.state = tds_base.TDS_PENDING
else:
raise tds_base.InterfaceError('logic error: cannot chage query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
elif state == tds_base.TDS_READING:
# transition to READING are valid only from PENDING
if self.state != tds_base.TDS_PENDING:
raise tds_base.InterfaceError('logic error: cannot change query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
else:
self.state = state
elif state == tds_base.TDS_IDLE:
if prior_state == tds_base.TDS_DEAD:
raise tds_base.InterfaceError('logic error: cannot change query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
self.state = state
elif state == tds_base.TDS_DEAD:
self.state = state
elif state == tds_base.TDS_QUERYING:
if self.state == tds_base.TDS_DEAD:
raise tds_base.InterfaceError('logic error: cannot change query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
elif self.state != tds_base.TDS_IDLE:
raise tds_base.InterfaceError('logic error: cannot change query state from {0} to {1}'.
format(tds_base.state_names[prior_state], tds_base.state_names[state]))
else:
self.rows_affected = tds_base.TDS_NO_COUNT
self.internal_sp_called = 0
self.state = state
else:
assert False
return self.state | Switches state of the TDS session.
It also does state transitions checks.
:param state: New state, one of TDS_PENDING/TDS_READING/TDS_IDLE/TDS_DEAD/TDS_QUERING | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L844-L886 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.querying_context | def querying_context(self, packet_type):
""" Context manager for querying.
Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block,
and to TDS_PENDING if managed block succeeds and flushes buffer.
"""
if self.set_state(tds_base.TDS_QUERYING) != tds_base.TDS_QUERYING:
raise tds_base.Error("Couldn't switch to state")
self._writer.begin_packet(packet_type)
try:
yield
except:
if self.state != tds_base.TDS_DEAD:
self.set_state(tds_base.TDS_IDLE)
raise
else:
self.set_state(tds_base.TDS_PENDING)
self._writer.flush() | python | def querying_context(self, packet_type):
""" Context manager for querying.
Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block,
and to TDS_PENDING if managed block succeeds and flushes buffer.
"""
if self.set_state(tds_base.TDS_QUERYING) != tds_base.TDS_QUERYING:
raise tds_base.Error("Couldn't switch to state")
self._writer.begin_packet(packet_type)
try:
yield
except:
if self.state != tds_base.TDS_DEAD:
self.set_state(tds_base.TDS_IDLE)
raise
else:
self.set_state(tds_base.TDS_PENDING)
self._writer.flush() | Context manager for querying.
Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block,
and to TDS_PENDING if managed block succeeds and flushes buffer. | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L889-L906 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.make_param | def make_param(self, name, value):
""" Generates instance of :class:`Column` from value and name
Value can also be of a special types:
- An instance of :class:`Column`, in which case it is just returned.
- An instance of :class:`output`, in which case parameter will become
an output parameter.
- A singleton :var:`default`, in which case default value will be passed
into a stored proc.
:param name: Name of the parameter, will populate column_name property of returned column.
:param value: Value of the parameter, also used to guess the type of parameter.
:return: An instance of :class:`Column`
"""
if isinstance(value, tds_base.Column):
value.column_name = name
return value
column = tds_base.Column()
column.column_name = name
column.flags = 0
if isinstance(value, output):
column.flags |= tds_base.fByRefValue
if isinstance(value.type, six.string_types):
column.type = tds_types.sql_type_by_declaration(value.type)
elif value.type:
column.type = self.conn.type_inferrer.from_class(value.type)
value = value.value
if value is default:
column.flags |= tds_base.fDefaultValue
value = None
column.value = value
if column.type is None:
column.type = self.conn.type_inferrer.from_value(value)
return column | python | def make_param(self, name, value):
""" Generates instance of :class:`Column` from value and name
Value can also be of a special types:
- An instance of :class:`Column`, in which case it is just returned.
- An instance of :class:`output`, in which case parameter will become
an output parameter.
- A singleton :var:`default`, in which case default value will be passed
into a stored proc.
:param name: Name of the parameter, will populate column_name property of returned column.
:param value: Value of the parameter, also used to guess the type of parameter.
:return: An instance of :class:`Column`
"""
if isinstance(value, tds_base.Column):
value.column_name = name
return value
column = tds_base.Column()
column.column_name = name
column.flags = 0
if isinstance(value, output):
column.flags |= tds_base.fByRefValue
if isinstance(value.type, six.string_types):
column.type = tds_types.sql_type_by_declaration(value.type)
elif value.type:
column.type = self.conn.type_inferrer.from_class(value.type)
value = value.value
if value is default:
column.flags |= tds_base.fDefaultValue
value = None
column.value = value
if column.type is None:
column.type = self.conn.type_inferrer.from_value(value)
return column | Generates instance of :class:`Column` from value and name
Value can also be of a special types:
- An instance of :class:`Column`, in which case it is just returned.
- An instance of :class:`output`, in which case parameter will become
an output parameter.
- A singleton :var:`default`, in which case default value will be passed
into a stored proc.
:param name: Name of the parameter, will populate column_name property of returned column.
:param value: Value of the parameter, also used to guess the type of parameter.
:return: An instance of :class:`Column` | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L908-L945 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession._convert_params | def _convert_params(self, parameters):
""" Converts a dict of list of parameters into a list of :class:`Column` instances.
:param parameters: Can be a list of parameter values, or a dict of parameter names to values.
:return: A list of :class:`Column` instances.
"""
if isinstance(parameters, dict):
return [self.make_param(name, value)
for name, value in parameters.items()]
else:
params = []
for parameter in parameters:
params.append(self.make_param('', parameter))
return params | python | def _convert_params(self, parameters):
""" Converts a dict of list of parameters into a list of :class:`Column` instances.
:param parameters: Can be a list of parameter values, or a dict of parameter names to values.
:return: A list of :class:`Column` instances.
"""
if isinstance(parameters, dict):
return [self.make_param(name, value)
for name, value in parameters.items()]
else:
params = []
for parameter in parameters:
params.append(self.make_param('', parameter))
return params | Converts a dict of list of parameters into a list of :class:`Column` instances.
:param parameters: Can be a list of parameter values, or a dict of parameter names to values.
:return: A list of :class:`Column` instances. | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L947-L960 |
denisenkom/pytds | src/pytds/tds.py | _TdsSession.cancel_if_pending | def cancel_if_pending(self):
""" Cancels current pending request.
Does nothing if no request is pending, otherwise sends cancel request,
and waits for response.
"""
if self.state == tds_base.TDS_IDLE:
return
if not self.in_cancel:
self.put_cancel()
self.process_cancel() | python | def cancel_if_pending(self):
""" Cancels current pending request.
Does nothing if no request is pending, otherwise sends cancel request,
and waits for response.
"""
if self.state == tds_base.TDS_IDLE:
return
if not self.in_cancel:
self.put_cancel()
self.process_cancel() | Cancels current pending request.
Does nothing if no request is pending, otherwise sends cancel request,
and waits for response. | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L962-L972 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.