Skip to content
This repository has been archived by the owner on Jan 14, 2024. It is now read-only.

Refactor EntityCapsService to decouple XEP-0115-specifics from core #97

Merged
merged 5 commits into from
May 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions aioxmpp/entitycaps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@

In general, you will not need to use these classes directly, nor encounter
them, as the service filters them off the presence stanzas. If the filter is
not loaded, the :class:`Caps` instance is available at
not loaded, the :class:`Caps115` instance is available at
:attr:`.Presence.xep0115_caps`.

.. autoclass:: Caps
.. autoclass:: Caps115


"""
Expand Down
175 changes: 175 additions & 0 deletions aioxmpp/entitycaps/caps115.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
########################################################################
# File name: caps115.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
import base64
import collections
import hashlib
import pathlib
import urllib.parse

from xml.sax.saxutils import escape

from .common import AbstractKey, AbstractImplementation
from . import xso as caps_xso


def build_identities_string(identities):
identities = [
b"/".join([
escape(identity.category).encode("utf-8"),
escape(identity.type_).encode("utf-8"),
escape(str(identity.lang or "")).encode("utf-8"),
escape(identity.name or "").encode("utf-8"),
])
for identity in identities
]

if len(set(identities)) != len(identities):
raise ValueError("duplicate identity")

identities.sort()
identities.append(b"")
return b"<".join(identities)


def build_features_string(features):
features = list(escape(feature).encode("utf-8") for feature in features)

if len(set(features)) != len(features):
raise ValueError("duplicate feature")

features.sort()
features.append(b"")
return b"<".join(features)


def build_forms_string(forms):
types = set()
forms_list = []
for form in forms:
try:
form_types = set(
value
for field in form.fields.filter(attrs={"var": "FORM_TYPE"})
for value in field.values
)
except KeyError:
continue

if len(form_types) > 1:
raise ValueError("form with multiple types")
elif not form_types:
continue

type_ = escape(next(iter(form_types))).encode("utf-8")
if type_ in types:
raise ValueError("multiple forms of type {!r}".format(type_))
types.add(type_)
forms_list.append((type_, form))
forms_list.sort()

parts = []

for type_, form in forms_list:
parts.append(type_)

field_list = sorted(
(
(escape(field.var).encode("utf-8"), field.values)
for field in form.fields
if field.var != "FORM_TYPE"
),
key=lambda x: x[0]
)

for var, values in field_list:
parts.append(var)
parts.extend(sorted(
escape(value).encode("utf-8") for value in values
))

parts.append(b"")
return b"<".join(parts)


def hash_query(query, algo):
hashimpl = hashlib.new(algo)
hashimpl.update(
build_identities_string(query.identities)
)
hashimpl.update(
build_features_string(query.features)
)
hashimpl.update(
build_forms_string(query.exts)
)

return base64.b64encode(hashimpl.digest()).decode("ascii")


Key = collections.namedtuple("Key", ["algo", "node"])


class Key(Key, AbstractKey):
@property
def path(self):
quoted = urllib.parse.quote(self.node, safe="")
return (pathlib.Path("hashes") /
"{}_{}.xml".format(self.algo, quoted))

@property
def ver(self):
return self.node.rsplit("#", 1)[1]

def verify(self, query_response):
digest_b64 = hash_query(query_response, self.algo.replace("-", ""))
return self.ver == digest_b64


class Implementation(AbstractImplementation):
def __init__(self, node, **kwargs):
super().__init__(**kwargs)
self.__node = node

def extract_keys(self, obj):
caps = obj.xep0115_caps
if caps is None or caps.hash_ is None:
return

yield Key(caps.hash_, "{}#{}".format(caps.node, caps.ver))

def put_keys(self, keys, presence):
key, = keys

presence.xep0115_caps = caps_xso.Caps115(
self.__node,
key.ver,
key.algo,
)

def calculate_keys(self, query_response):
yield Key(
"sha-1",
"{}#{}".format(
self.__node,
hash_query(query_response, "sha1"),
)
)
105 changes: 105 additions & 0 deletions aioxmpp/entitycaps/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
########################################################################
# File name: common.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
import abc


class AbstractKey(metaclass=abc.ABCMeta):
@abc.abstractproperty
def path(self):
"""
Return the file system path relative to the root of a file-system based
caps database for this key.

The path includes all information of the key. Components of the path do
not exceed 255 codepoints and use only ASCII codepoints.

If it is not possible to create such a path, :class:`ValueError` is
raised.
"""

@abc.abstractmethod
def verify(self, query_response):
"""
Verify whether the cache key maches a piece of service discovery
information.

:param query_response: The full :xep:`30` disco#info query response.
:type query_response: :class:`~.disco.xso.InfoQuery`
:rtype: :class:`bool`
:return: true if the key matches and false otherwise.
"""


class AbstractImplementation(metaclass=abc.ABCMeta):
@abc.abstractmethod
def extract_keys(self, presence):
"""
Extract cache keys from a presence stanza.

:param presence: Presence stanza to extract cache keys from.
:type presence: :class:`aioxmpp.Presence`
:rtype: :class:`~collections.abc.Iterable` of :class:`AbstractKey`
:return: The cache keys from the presence stanza.

The resulting iterable may be empty if the presence stanza does not
carry any capabilities information with it.

The resulting iterable cannot be iterated over multiple times.
"""

@abc.abstractmethod
def put_keys(self, keys, presence):
"""
Insert cache keys into a presence stanza.

:param keys: An iterable of cache keys to insert.
:type keys: :class:`~collections.abc.Iterable` of :class:`AbstractKey`
objects
:param presence: The presence stanza into which the cache keys shall be
injected.
:type presence: :class:`aioxmpp.Presence`

The presence stanza is modified in-place.
"""

@abc.abstractmethod
def calculate_keys(self, query_response):
"""
Calculate the cache keys for a disco#info response.

:param query_response: The full :xep:`30` disco#info query response.
:type query_response: :class:`~.disco.xso.InfoQuery`
:rtype: :class:`~collections.abc.Iterable` of :class:`AbstractKey`
:return: An iterable of the cache keys for the disco#info response.

..

:param identities: The identities of the disco#info response.
:type identities: :class:`~collections.abc.Iterable` of
:class:`~.disco.xso.Identity`
:param features: The features of the disco#info response.
:type features: :class:`~collections.abc.Iterable` of
:class:`str`
:param features: The extensions of the disco#info response.
:type features: :class:`~collections.abc.Iterable` of
:class:`~.forms.xso.Data`
"""
Loading