comparison src/plugins/plugin_xep_0280.py @ 2099:ad88808591ef

plugin XEP-0280: Message Carbons first draft
author Goffi <goffi@goffi.org>
date Sun, 18 Dec 2016 20:21:31 +0100
parents
children 7de291c3cd0c
comparison
equal deleted inserted replaced
2098:e0066920a661 2099:ad88808591ef
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3
4 # SAT plugin for managing xep-0280
5 # Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 from sat.core.i18n import _, D_
21 from sat.core.log import getLogger
22 log = getLogger(__name__)
23 from sat.core import exceptions
24 from sat.core.constants import Const as C
25 from sat.core.xmpp import SatMessageProtocol
26 from twisted.words.protocols.jabber.error import StanzaError
27 from twisted.internet import defer
28 from wokkel import disco, iwokkel
29 from zope.interface import implements
30 try:
31 from twisted.words.protocols.xmlstream import XMPPHandler
32 except ImportError:
33 from wokkel.subprotocols import XMPPHandler
34
35
36 PARAM_CATEGORY = "Misc"
37 PARAM_NAME = "carbon"
38 PARAM_LABEL = D_(u"Message carbons")
39 NS_CARBONS = 'urn:xmpp:carbons:2'
40
41 PLUGIN_INFO = {
42 "name": "XEP-0280 Plugin",
43 "import_name": "XEP-0280",
44 "type": "XEP",
45 "protocols": ["XEP-0280"],
46 "dependencies": [],
47 "main": "XEP_0280",
48 "handler": "yes",
49 "description": _("""Implementation of Message Carbons""")
50 }
51
52
53 class XEP_0280(object):
54 # TODO: param is only checked at profile connection
55 # activate carbons on param change even after profile connection
56 # TODO: chat state notifications are not handled yet (and potentially other XEPs?)
57
58 params = """
59 <params>
60 <individual>
61 <category name="{category_name}" label="{category_label}">
62 <param name="{param_name}" label="{param_label}" value="true" type="bool" security="0" />
63 </category>
64 </individual>
65 </params>
66 """.format(
67 category_name = PARAM_CATEGORY,
68 category_label = D_(PARAM_CATEGORY),
69 param_name = PARAM_NAME,
70 param_label = PARAM_LABEL,
71 )
72
73 def __init__(self, host):
74 log.info(_("Plugin XEP_0280 initialization"))
75 self.host = host
76 host.memory.updateParams(self.params)
77 host.trigger.add("MessageReceived", self.messageReceivedTrigger, priority=1000)
78
79 def getHandler(self, profile):
80 return XEP_0280_handler()
81
82 @defer.inlineCallbacks
83 def profileConnected(self, profile):
84 """activate message carbons on connection if possible and activated in config"""
85 client = self.host.getClient(profile)
86 activate = self.host.memory.getParamA(PARAM_NAME, PARAM_CATEGORY, profile_key=profile)
87 if not activate:
88 log.info(_(u"Not activating message carbons as requested in params"))
89 return
90 try:
91 yield self.host.checkFeatures((NS_CARBONS,), profile=profile)
92 except exceptions.FeatureNotFound:
93 log.warning(_(u"server doesn't handle message carbons"))
94 else:
95 log.info(_(u"message carbons available, enabling it"))
96 iq_elt = client.IQ()
97 iq_elt.addElement((NS_CARBONS, 'enable'))
98 try:
99 yield iq_elt.send()
100 except StanzaError as e:
101 log.warning(u"Can't activate message carbons: {}".format(e))
102 else:
103 log.info(_(u"message carbons activated"))
104
105 def messageReceivedTrigger(self, client, message_elt, post_treat):
106 """get message and handle it if carbons namespace is present"""
107 carbons_elt = None
108 for e in message_elt.elements():
109 if e.uri == NS_CARBONS:
110 carbons_elt = e
111 break
112
113 if carbons_elt is None:
114 # this is not a message carbons,
115 # we continue normal behaviour
116 return True
117
118 if message_elt['from'] != client.jid.userhost():
119 log.warning(u"The message carbon received is not from our server, hack attempt?\n{xml}".format(
120 xml = message_elt.toXml(),
121 ))
122 return
123 forwarded_elt = next(carbons_elt.elements(C.NS_FORWARD, 'forwarded'))
124 cc_message_elt = next(forwarded_elt.elements(C.NS_CLIENT, 'message'))
125 if carbons_elt.name == 'received':
126 # on receive we replace the wrapping message with the CCed one
127 # and continue the normal behaviour
128 message_elt['from'] = cc_message_elt['from']
129 del message_elt.children[:]
130 for c in cc_message_elt.children:
131 message_elt.addChild(c)
132 return True
133 elif carbons_elt.name == 'sent':
134 # on send we parse the message and just add it to history
135 # and send it to frontends (without normal sending treatments)
136 mess_data = SatMessageProtocol.parseMessage(cc_message_elt, client)
137 if not mess_data['message'] and not mess_data['subject']:
138 return False
139 self.host.messageAddToHistory(mess_data, client)
140 self.host.messageSendToBridge(mess_data, client)
141 else:
142 log.warning(u"invalid message carbons received:\n{xml}".format(
143 xml = message_elt.toXml()))
144 return False
145
146
147 class XEP_0280_handler(XMPPHandler):
148 implements(iwokkel.IDisco)
149
150 def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
151 return [disco.DiscoFeature(NS_CARBONS)]
152
153 def getDiscoItems(self, requestor, target, nodeIdentifier=''):
154 return []