code style reformatting using black

This commit is contained in:
Goffi 2018-06-27 20:14:46 +02:00
commit 744cb0c503

View file

@ -21,6 +21,7 @@ from sat.core.i18n import _
from sat.core.constants import Const as C
from sat.core import exceptions
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.tools import xml_tools
from wokkel import disco, iwokkel
@ -43,24 +44,29 @@ PLUGIN_INFO = {
C.PI_PROTOCOLS: ["XEP-0231"],
C.PI_MAIN: "XEP_0231",
C.PI_HANDLER: "yes",
C.PI_DESCRIPTION: _("""Implementation of bits of binary (used for small images/files)""")
C.PI_DESCRIPTION: _(
"""Implementation of bits of binary (used for small images/files)"""
),
}
NS_BOB = u'urn:xmpp:bob'
NS_BOB = u"urn:xmpp:bob"
IQ_BOB_REQUEST = C.IQ_GET + '/data[@xmlns="' + NS_BOB + '"]'
class XEP_0231(object):
def __init__(self, host):
log.info(_(u"plugin Bits of Binary initialization"))
self.host = host
host.registerNamespace('bob', NS_BOB)
host.registerNamespace("bob", NS_BOB)
host.trigger.add("xhtml_post_treat", self.XHTMLTrigger)
host.bridge.addMethod("bobGetFile", ".plugin",
in_sign='sss', out_sign='s',
method=self._getFile,
async=True)
host.bridge.addMethod(
"bobGetFile",
".plugin",
in_sign="sss",
out_sign="s",
method=self._getFile,
async=True,
)
def dumpData(self, cache, data_elt, cid):
"""save file encoded in data_elt to cache
@ -70,21 +76,19 @@ class XEP_0231(object):
@param cid(unicode): content-id
@return(unicode): full path to dumped file
"""
# FIXME: is it needed to use a separate thread?
#  FIXME: is it needed to use a separate thread?
# probably not with the little data expected with BoB
try:
max_age = int(data_elt['max-age'])
max_age = int(data_elt["max-age"])
if max_age < 0:
raise ValueError
except (KeyError, ValueError):
log.warning(u'invalid max-age found')
log.warning(u"invalid max-age found")
max_age = None
with cache.cacheData(
PLUGIN_INFO[C.PI_IMPORT_NAME],
cid,
data_elt.getAttribute('type'),
max_age) as f:
PLUGIN_INFO[C.PI_IMPORT_NAME], cid, data_elt.getAttribute("type"), max_age
) as f:
file_path = f.name
f.write(base64.b64decode(str(data_elt)))
@ -95,15 +99,16 @@ class XEP_0231(object):
return XEP_0231_handler(self)
def _requestCb(self, iq_elt, cache, cid):
for data_elt in iq_elt.elements(NS_BOB, u'data'):
if data_elt.getAttribute('cid') == cid:
for data_elt in iq_elt.elements(NS_BOB, u"data"):
if data_elt.getAttribute("cid") == cid:
file_path = self.dumpData(cache, data_elt, cid)
return file_path
log.warning(u"invalid data stanza received, requested cid was not found:\n{iq_elt}\nrequested cid: {cid}".format(
iq_elt = iq_elt,
cid = cid
))
log.warning(
u"invalid data stanza received, requested cid was not found:\n{iq_elt}\nrequested cid: {cid}".format(
iq_elt=iq_elt, cid=cid
)
)
raise failure.Failure(exceptions.DataError("missing data"))
def _requestEb(self, failure_):
@ -122,39 +127,39 @@ class XEP_0231(object):
"""
if cache is None:
cache = client.cache
iq_elt = client.IQ('get')
iq_elt['to'] = to_jid.full()
data_elt = iq_elt.addElement((NS_BOB, 'data'))
data_elt['cid'] = cid
iq_elt = client.IQ("get")
iq_elt["to"] = to_jid.full()
data_elt = iq_elt.addElement((NS_BOB, "data"))
data_elt["cid"] = cid
d = iq_elt.send()
d.addCallback(self._requestCb, cache, cid)
d.addErrback(self._requestEb)
return d
def _setImgEltSrc(self, path, img_elt):
img_elt[u'src'] = u'file://{}'.format(path)
img_elt[u"src"] = u"file://{}".format(path)
def XHTMLTrigger(self, client, message_elt, body_elt, lang, treat_d):
for img_elt in xml_tools.findAll(body_elt, C.NS_XHTML, u'img'):
source = img_elt.getAttribute(u'src','')
if source.startswith(u'cid:'):
for img_elt in xml_tools.findAll(body_elt, C.NS_XHTML, u"img"):
source = img_elt.getAttribute(u"src", "")
if source.startswith(u"cid:"):
cid = source[4:]
file_path = client.cache.getFilePath(cid)
if file_path is not None:
# image is in cache, we change the url
img_elt[u'src'] = u'file://{}'.format(file_path)
#  image is in cache, we change the url
img_elt[u"src"] = u"file://{}".format(file_path)
continue
else:
# image is not in cache, is it given locally?
for data_elt in message_elt.elements(NS_BOB, u'data'):
if data_elt.getAttribute('cid') == cid:
for data_elt in message_elt.elements(NS_BOB, u"data"):
if data_elt.getAttribute("cid") == cid:
file_path = self.dumpData(client.cache, data_elt, cid)
img_elt[u'src'] = u'file://{}'.format(file_path)
img_elt[u"src"] = u"file://{}".format(file_path)
break
else:
# cid not found locally, we need to request it
# so we use the deferred
d = self.requestData(client, jid.JID(message_elt['from']), cid)
d = self.requestData(client, jid.JID(message_elt["from"]), cid)
d.addCallback(partial(self._setImgEltSrc, img_elt=img_elt))
treat_d.addCallback(lambda dummy: d)
@ -165,28 +170,28 @@ class XEP_0231(object):
# An access check should be implemented though.
iq_elt.handled = True
data_elt = next(iq_elt.elements(NS_BOB, 'data'))
data_elt = next(iq_elt.elements(NS_BOB, "data"))
try:
cid = data_elt[u'cid']
cid = data_elt[u"cid"]
except KeyError:
error_elt = jabber_error.StanzaError('not-acceptable').toResponse(iq_elt)
error_elt = jabber_error.StanzaError("not-acceptable").toResponse(iq_elt)
client.send(error_elt)
return
metadata = self.host.common_cache.getMetadata(cid)
if metadata is None:
error_elt = jabber_error.StanzaError('item-not-found').toResponse(iq_elt)
error_elt = jabber_error.StanzaError("item-not-found").toResponse(iq_elt)
client.send(error_elt)
return
with open(metadata['path']) as f:
with open(metadata["path"]) as f:
data = f.read()
result_elt = xmlstream.toResponse(iq_elt, 'result')
data_elt = result_elt.addElement((NS_BOB, 'data'), content = data.encode('base64'))
data_elt[u'cid'] = cid
data_elt[u'type'] = metadata[u'mime_type']
data_elt[u'max-age'] = unicode(int(max(0, metadata['eol'] - time.time())))
result_elt = xmlstream.toResponse(iq_elt, "result")
data_elt = result_elt.addElement((NS_BOB, "data"), content=data.encode("base64"))
data_elt[u"cid"] = cid
data_elt[u"type"] = metadata[u"mime_type"]
data_elt[u"max-age"] = unicode(int(max(0, metadata["eol"] - time.time())))
client.send(result_elt)
def _getFile(self, peer_jid_s, cid, profile):
@ -207,13 +212,13 @@ class XEP_0231(object):
"""
file_path = client.cache.getFilePath(cid)
if file_path is not None:
# file is in cache
#  file is in cache
return defer.succeed(file_path)
else:
# file not in cache, is it given locally?
if parent_elt is not None:
for data_elt in parent_elt.elements(NS_BOB, u'data'):
if data_elt.getAttribute('cid') == cid:
for data_elt in parent_elt.elements(NS_BOB, u"data"):
if data_elt.getAttribute("cid") == cid:
return defer.succeed(self.dumpData(client.cache, data_elt, cid))
# cid not found locally, we need to request it
@ -230,10 +235,12 @@ class XEP_0231_handler(xmlstream.XMPPHandler):
def connectionInitialized(self):
if self.parent.is_component:
self.xmlstream.addObserver(IQ_BOB_REQUEST, self.plugin_parent.onComponentRequest, client=self.parent)
self.xmlstream.addObserver(
IQ_BOB_REQUEST, self.plugin_parent.onComponentRequest, client=self.parent
)
def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
return [disco.DiscoFeature(NS_BOB)]
def getDiscoItems(self, requestor, target, nodeIdentifier=''):
def getDiscoItems(self, requestor, target, nodeIdentifier=""):
return []