Mercurial > libervia-backend
diff sat/memory/disco.py @ 2624:56f94936df1e
code style reformatting using black
author | Goffi <goffi@goffi.org> |
---|---|
date | Wed, 27 Jun 2018 20:14:46 +0200 |
parents | e70023e84974 |
children | c3f59c1dcb0a |
line wrap: on
line diff
--- a/sat/memory/disco.py Wed Jun 27 07:51:29 2018 +0200 +++ b/sat/memory/disco.py Wed Jun 27 20:14:46 2018 +0200 @@ -20,6 +20,7 @@ from sat.core.i18n import _ from sat.core import exceptions from sat.core.log import getLogger + log = getLogger(__name__) from twisted.words.protocols.jabber import jid from twisted.words.protocols.jabber.error import StanzaError @@ -35,7 +36,8 @@ TIMEOUT = 15 -CAP_HASH_ERROR = 'ERROR' +CAP_HASH_ERROR = "ERROR" + class HashGenerationError(Exception): pass @@ -46,10 +48,10 @@ def __init__(self, identity, lang=None): assert isinstance(identity, disco.DiscoIdentity) - self.category = identity.category.encode('utf-8') - self.idType = identity.type.encode('utf-8') - self.name = identity.name.encode('utf-8') if identity.name else '' - self.lang = lang.encode('utf-8') if lang is not None else '' + self.category = identity.category.encode("utf-8") + self.idType = identity.type.encode("utf-8") + self.name = identity.name.encode("utf-8") if identity.name else "" + self.lang = lang.encode("utf-8") if lang is not None else "" def __str__(self): return "%s/%s/%s/%s" % (self.category, self.idType, self.lang, self.name) @@ -63,8 +65,8 @@ def __init__(self, persistent): self.hashes = { - CAP_HASH_ERROR: disco.DiscoInfo(), # used when we can't get disco infos - } + CAP_HASH_ERROR: disco.DiscoInfo() # used when we can't get disco infos + } self.persistent = persistent def __getitem__(self, key): @@ -86,12 +88,16 @@ element = xml_tools.ElementParser()(xml) disco_info = disco.DiscoInfo.fromElement(element) if not disco_info.features and not disco_info.identities: - log.warning(_(u"no feature/identity found in disco element (hash: {cap_hash}), ignoring: {xml}").format( - cap_hash=hash_, xml=xml)) + log.warning( + _( + u"no feature/identity found in disco element (hash: {cap_hash}), ignoring: {xml}" + ).format(cap_hash=hash_, xml=xml) + ) else: self.hashes[hash_] = disco_info log.info(u"Disco hashes loaded") + d = self.persistent.load() d.addCallback(fillHashes) return d @@ -110,7 +116,7 @@ return self.hashes.load() @defer.inlineCallbacks - def hasFeature(self, client, feature, jid_=None, node=u''): + def hasFeature(self, client, feature, jid_=None, node=u""): """Tell if an entity has the required feature @param feature: feature namespace @@ -122,7 +128,7 @@ defer.returnValue(feature in disco_infos.features) @defer.inlineCallbacks - def checkFeature(self, client, feature, jid_=None, node=u''): + def checkFeature(self, client, feature, jid_=None, node=u""): """Like hasFeature, but raise an exception is feature is not Found @param feature: feature namespace @@ -136,7 +142,7 @@ raise failure.Failure(exceptions.FeatureNotFound) @defer.inlineCallbacks - def checkFeatures(self, client, features, jid_=None, identity=None, node=u''): + def checkFeatures(self, client, features, jid_=None, identity=None, node=u""): """Like checkFeature, but check several features at once, and check also identity @param features(iterable[unicode]): features to check @@ -153,7 +159,7 @@ if identity is not None and identity not in disco_infos.identities: raise failure.Failure(exceptions.FeatureNotFound()) - def getInfos(self, client, jid_=None, node=u'', use_cache=True): + def getInfos(self, client, jid_=None, node=u"", use_cache=True): """get disco infos from jid_, filling capability hash if needed @param jid_: jid of the target, or None for profile's server @@ -167,14 +173,19 @@ if not use_cache: # we ignore cache, so we pretend we haven't found it raise KeyError - cap_hash = self.host.memory.getEntityData(jid_, [C.ENTITY_CAP_HASH], client.profile)[C.ENTITY_CAP_HASH] + cap_hash = self.host.memory.getEntityData( + jid_, [C.ENTITY_CAP_HASH], client.profile + )[C.ENTITY_CAP_HASH] except (KeyError, exceptions.UnknownEntityError): # capability hash is not available, we'll compute one def infosCb(disco_infos): cap_hash = self.generateHash(disco_infos) self.hashes[cap_hash] = disco_infos - self.host.memory.updateEntityData(jid_, C.ENTITY_CAP_HASH, cap_hash, profile_key=client.profile) + self.host.memory.updateEntityData( + jid_, C.ENTITY_CAP_HASH, cap_hash, profile_key=client.profile + ) return disco_infos + def infosEb(fail): if fail.check(defer.CancelledError): reason = u"request time-out" @@ -183,10 +194,17 @@ reason = unicode(fail.value) except AttributeError: reason = unicode(fail) - log.warning(u"Error while requesting disco infos from {jid}: {reason}".format(jid=jid_.full(), reason=reason)) - self.host.memory.updateEntityData(jid_, C.ENTITY_CAP_HASH, CAP_HASH_ERROR, profile_key=client.profile) + log.warning( + u"Error while requesting disco infos from {jid}: {reason}".format( + jid=jid_.full(), reason=reason + ) + ) + self.host.memory.updateEntityData( + jid_, C.ENTITY_CAP_HASH, CAP_HASH_ERROR, profile_key=client.profile + ) disco_infos = self.hashes[CAP_HASH_ERROR] return disco_infos + d = client.disco.requestInfo(jid_, nodeIdentifier=node) d.addCallback(infosCb) d.addErrback(infosEb) @@ -196,7 +214,7 @@ return defer.succeed(disco_infos) @defer.inlineCallbacks - def getItems(self, client, jid_=None, node=u'', use_cache=True): + def getItems(self, client, jid_=None, node=u"", use_cache=True): """get disco items from jid_, cache them for our own server @param jid_(jid.JID): jid of the target, or None for profile's server @@ -211,7 +229,9 @@ if jid_ == server_jid and not node: # we cache items only for our own server and if node is not set try: - items = self.host.memory.getEntityData(jid_, ["DISCO_ITEMS"], client.profile)["DISCO_ITEMS"] + items = self.host.memory.getEntityData( + jid_, ["DISCO_ITEMS"], client.profile + )["DISCO_ITEMS"] log.debug(u"[%s] disco items are in cache" % jid_.full()) if not use_cache: # we ignore cache, so we pretend we haven't found it @@ -219,22 +239,28 @@ except (KeyError, exceptions.UnknownEntityError): log.debug(u"Caching [%s] disco items" % jid_.full()) items = yield client.disco.requestItems(jid_, nodeIdentifier=node) - self.host.memory.updateEntityData(jid_, "DISCO_ITEMS", items, profile_key=client.profile) + self.host.memory.updateEntityData( + jid_, "DISCO_ITEMS", items, profile_key=client.profile + ) else: try: items = yield client.disco.requestItems(jid_, nodeIdentifier=node) except StanzaError as e: - log.warning(u"Error while requesting items for {jid}: {reason}" - .format(jid=jid_.full(), reason=e.condition)) + log.warning( + u"Error while requesting items for {jid}: {reason}".format( + jid=jid_.full(), reason=e.condition + ) + ) items = disco.DiscoItems() defer.returnValue(items) - def _infosEb(self, failure_, entity_jid): failure_.trap(StanzaError) - log.warning(_(u"Error while requesting [%(jid)s]: %(error)s") % {'jid': entity_jid.full(), - 'error': failure_.getErrorMessage()}) + log.warning( + _(u"Error while requesting [%(jid)s]: %(error)s") + % {"jid": entity_jid.full(), "error": failure_.getErrorMessage()} + ) def findServiceEntity(self, client, category, type_, jid_=None): """Helper method to find first available entity from findServiceEntities @@ -265,14 +291,18 @@ defers_list = [] for item in items: info_d = self.getInfos(client, item.entity) - info_d.addCallbacks(infosCb, self._infosEb, [item.entity], None, [item.entity]) + info_d.addCallbacks( + infosCb, self._infosEb, [item.entity], None, [item.entity] + ) defers_list.append(info_d) return defer.DeferredList(defers_list) d = self.getItems(client, jid_) d.addCallback(gotItems) d.addCallback(lambda dummy: found_entities) - reactor.callLater(TIMEOUT, d.cancel) # FIXME: one bad service make a general timeout + reactor.callLater( + TIMEOUT, d.cancel + ) # FIXME: one bad service make a general timeout return d def findFeaturesSet(self, client, features, identity=None, jid_=None): @@ -291,7 +321,7 @@ def infosCb(infos, entity): if entity is None: - log.warning(_(u'received an item without jid')) + log.warning(_(u"received an item without jid")) return if identity is not None and identity not in infos.identities: return @@ -309,7 +339,9 @@ d = self.getItems(client, jid_) d.addCallback(gotItems) d.addCallback(lambda dummy: found_entities) - reactor.callLater(TIMEOUT, d.cancel) # FIXME: one bad service make a general timeout + reactor.callLater( + TIMEOUT, d.cancel + ) # FIXME: one bad service make a general timeout return d def generateHash(self, services): @@ -320,25 +352,35 @@ """ s = [] - byte_identities = [ByteIdentity(service) for service in services if isinstance(service, disco.DiscoIdentity)] # FIXME: lang must be managed here + byte_identities = [ + ByteIdentity(service) + for service in services + if isinstance(service, disco.DiscoIdentity) + ] # FIXME: lang must be managed here byte_identities.sort(key=lambda i: i.lang) byte_identities.sort(key=lambda i: i.idType) byte_identities.sort(key=lambda i: i.category) for identity in byte_identities: s.append(str(identity)) - s.append('<') - byte_features = [service.encode('utf-8') for service in services if isinstance(service, disco.DiscoFeature)] + s.append("<") + byte_features = [ + service.encode("utf-8") + for service in services + if isinstance(service, disco.DiscoFeature) + ] byte_features.sort() # XXX: the default sort has the same behaviour as the requested RFC 4790 i;octet sort for feature in byte_features: s.append(feature) - s.append('<') - #TODO: manage XEP-0128 data form here - cap_hash = b64encode(sha1(''.join(s)).digest()) - log.debug(_(u'Capability hash generated: [%s]') % cap_hash) + s.append("<") + # TODO: manage XEP-0128 data form here + cap_hash = b64encode(sha1("".join(s)).digest()) + log.debug(_(u"Capability hash generated: [%s]") % cap_hash) return cap_hash @defer.inlineCallbacks - def _discoInfos(self, entity_jid_s, node=u'', use_cache=True, profile_key=C.PROF_KEY_NONE): + def _discoInfos( + self, entity_jid_s, node=u"", use_cache=True, profile_key=C.PROF_KEY_NONE + ): """ Discovery method for the bridge @param entity_jid_s: entity we want to discover @param use_cache(bool): if True, use cached data if available @@ -353,8 +395,8 @@ for form_type, form in disco_infos.extensions.items(): fields = [] for field in form.fieldList: - data = {'type': field.fieldType} - for attr in ('var', 'label', 'desc'): + data = {"type": field.fieldType} + for attr in ("var", "label", "desc"): value = getattr(field, attr) if value is not None: data[attr] = value @@ -364,9 +406,16 @@ extensions[form_type or ""] = fields - defer.returnValue((disco_infos.features, - [(cat, type_, name or '') for (cat, type_), name in disco_infos.identities.items()], - extensions)) + defer.returnValue( + ( + disco_infos.features, + [ + (cat, type_, name or "") + for (cat, type_), name in disco_infos.identities.items() + ], + extensions, + ) + ) def items2tuples(self, disco_items): """convert disco items to tuple of strings @@ -378,10 +427,12 @@ if not item.entity: log.warning(_(u"invalid item (no jid)")) continue - yield (item.entity.full(), item.nodeIdentifier or '', item.name or '') + yield (item.entity.full(), item.nodeIdentifier or "", item.name or "") @defer.inlineCallbacks - def _discoItems(self, entity_jid_s, node=u'', use_cache=True, profile_key=C.PROF_KEY_NONE): + def _discoItems( + self, entity_jid_s, node=u"", use_cache=True, profile_key=C.PROF_KEY_NONE + ): """ Discovery method for the bridge @param entity_jid_s: entity we want to discover