comparison sat/plugins/plugin_xep_0096.py @ 2562:26edcf3a30eb

core, setup: huge cleaning: - moved directories from src and frontends/src to sat and sat_frontends, which is the recommanded naming convention - move twisted directory to root - removed all hacks from setup.py, and added missing dependencies, it is now clean - use https URL for website in setup.py - removed "Environment :: X11 Applications :: GTK", as wix is deprecated and removed - renamed sat.sh to sat and fixed its installation - added python_requires to specify Python version needed - replaced glib2reactor which use deprecated code by gtk3reactor sat can now be installed directly from virtualenv without using --system-site-packages anymore \o/
author Goffi <goffi@goffi.org>
date Mon, 02 Apr 2018 19:44:50 +0200
parents src/plugins/plugin_xep_0096.py@7ad5f2c4e34a
children 56f94936df1e
comparison
equal deleted inserted replaced
2561:bd30dc3ffe5a 2562:26edcf3a30eb
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3
4 # SAT plugin for managing xep-0096
5 # Copyright (C) 2009-2018 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.constants import Const as C
22 from sat.core.log import getLogger
23 log = getLogger(__name__)
24 from sat.core import exceptions
25 from sat.tools import xml_tools
26 from sat.tools import stream
27 from twisted.words.xish import domish
28 from twisted.words.protocols.jabber import jid
29 from twisted.words.protocols.jabber import error
30 import os
31
32
33 NS_SI_FT = "http://jabber.org/protocol/si/profile/file-transfer"
34 IQ_SET = '/iq[@type="set"]'
35 SI_PROFILE_NAME = "file-transfer"
36 SI_PROFILE = "http://jabber.org/protocol/si/profile/" + SI_PROFILE_NAME
37
38 PLUGIN_INFO = {
39 C.PI_NAME: "XEP-0096 Plugin",
40 C.PI_IMPORT_NAME: "XEP-0096",
41 C.PI_TYPE: "XEP",
42 C.PI_PROTOCOLS: ["XEP-0096"],
43 C.PI_DEPENDENCIES: ["XEP-0020", "XEP-0095", "XEP-0065", "XEP-0047", "FILE"],
44 C.PI_MAIN: "XEP_0096",
45 C.PI_HANDLER: "no",
46 C.PI_DESCRIPTION: _("""Implementation of SI File Transfer""")
47 }
48
49
50 class XEP_0096(object):
51 # TODO: call self._f.unregister when unloading order will be managing (i.e. when depenencies will be unloaded at the end)
52
53 def __init__(self, host):
54 log.info(_("Plugin XEP_0096 initialization"))
55 self.host = host
56 self.managed_stream_m = [self.host.plugins["XEP-0065"].NAMESPACE,
57 self.host.plugins["XEP-0047"].NAMESPACE] # Stream methods managed
58 self._f = self.host.plugins["FILE"]
59 self._f.register(NS_SI_FT, self.sendFile, priority=0, method_name=u"Stream Initiation")
60 self._si = self.host.plugins["XEP-0095"]
61 self._si.registerSIProfile(SI_PROFILE_NAME, self._transferRequest)
62 host.bridge.addMethod("siSendFile", ".plugin", in_sign='sssss', out_sign='s', method=self._sendFile)
63
64 def unload(self):
65 self._si.unregisterSIProfile(SI_PROFILE_NAME)
66
67 def _badRequest(self, client, iq_elt, message=None):
68 """Send a bad-request error
69
70 @param iq_elt(domish.Element): initial <IQ> element of the SI request
71 @param message(None, unicode): informational message to display in the logs
72 """
73 if message is not None:
74 log.warning(message)
75 self._si.sendError(client, iq_elt, 'bad-request')
76
77 def _parseRange(self, parent_elt, file_size):
78 """find and parse <range/> element
79
80 @param parent_elt(domish.Element): direct parent of the <range/> element
81 @return (tuple[bool, int, int]): a tuple with
82 - True if range is required
83 - range_offset
84 - range_length
85 """
86 try:
87 range_elt = parent_elt.elements(NS_SI_FT, 'range').next()
88 except StopIteration:
89 range_ = False
90 range_offset = None
91 range_length = None
92 else:
93 range_ = True
94
95 try:
96 range_offset = int(range_elt['offset'])
97 except KeyError:
98 range_offset = 0
99
100 try:
101 range_length = int(range_elt['length'])
102 except KeyError:
103 range_length = file_size
104
105 if range_offset != 0 or range_length != file_size:
106 raise NotImplementedError # FIXME
107
108 return range_, range_offset, range_length
109
110 def _transferRequest(self, client, iq_elt, si_id, si_mime_type, si_elt):
111 """Called when a file transfer is requested
112
113 @param iq_elt(domish.Element): initial <IQ> element of the SI request
114 @param si_id(unicode): Stream Initiation session id
115 @param si_mime_type("unicode"): Mime type of the file (or default "application/octet-stream" if unknown)
116 @param si_elt(domish.Element): request
117 """
118 log.info(_("XEP-0096 file transfer requested"))
119 peer_jid = jid.JID(iq_elt['from'])
120
121 try:
122 file_elt = si_elt.elements(NS_SI_FT, "file").next()
123 except StopIteration:
124 return self._badRequest(client, iq_elt, "No <file/> element found in SI File Transfer request")
125
126 try:
127 feature_elt = self.host.plugins["XEP-0020"].getFeatureElt(si_elt)
128 except exceptions.NotFound:
129 return self._badRequest(client, iq_elt, "No <feature/> element found in SI File Transfer request")
130
131 try:
132 filename = file_elt["name"]
133 file_size = int(file_elt["size"])
134 except (KeyError, ValueError):
135 return self._badRequest(client, iq_elt, "Malformed SI File Transfer request")
136
137 file_date = file_elt.getAttribute("date")
138 file_hash = file_elt.getAttribute("hash")
139
140 log.info(u"File proposed: name=[{name}] size={size}".format(name=filename, size=file_size))
141
142 try:
143 file_desc = unicode(file_elt.elements(NS_SI_FT, 'desc').next())
144 except StopIteration:
145 file_desc = ''
146
147 try:
148 range_, range_offset, range_length = self._parseRange(file_elt, file_size)
149 except ValueError:
150 return self._badRequest(client, iq_elt, "Malformed SI File Transfer request")
151
152 try:
153 stream_method = self.host.plugins["XEP-0020"].negotiate(feature_elt, 'stream-method', self.managed_stream_m, namespace=None)
154 except KeyError:
155 return self._badRequest(client, iq_elt, "No stream method found")
156
157 if stream_method:
158 if stream_method == self.host.plugins["XEP-0065"].NAMESPACE:
159 plugin = self.host.plugins["XEP-0065"]
160 elif stream_method == self.host.plugins["XEP-0047"].NAMESPACE:
161 plugin = self.host.plugins["XEP-0047"]
162 else:
163 log.error(u"Unknown stream method, this should not happen at this stage, cancelling transfer")
164 else:
165 log.warning(u"Can't find a valid stream method")
166 self._si.sendError(client, iq_elt, 'not-acceptable')
167 return
168
169 #if we are here, the transfer can start, we just need user's agreement
170 data = {"name": filename, "peer_jid": peer_jid, "size": file_size, "date": file_date, "hash": file_hash, "desc": file_desc,
171 "range": range_, "range_offset": range_offset, "range_length": range_length,
172 "si_id": si_id, "progress_id": si_id, "stream_method": stream_method, "stream_plugin": plugin}
173
174 d = self._f.getDestDir(client, peer_jid, data, data, stream_object=True)
175 d.addCallback(self.confirmationCb, client, iq_elt, data)
176
177 def confirmationCb(self, accepted, client, iq_elt, data):
178 """Called on confirmation answer
179
180 @param accepted(bool): True if file transfer is accepted
181 @param iq_elt(domish.Element): initial SI request
182 @param data(dict): session data
183 """
184 if not accepted:
185 log.info(u"File transfer declined")
186 self._si.sendError(client, iq_elt, 'forbidden')
187 return
188 # data, timeout, stream_method, failed_methods = client._xep_0096_waiting_for_approval[sid]
189 # can_range = data['can_range'] == "True"
190 # range_offset = 0
191 # if timeout.active():
192 # timeout.cancel()
193 # try:
194 # dest_path = frontend_data['dest_path']
195 # except KeyError:
196 # log.error(_('dest path not found in frontend_data'))
197 # del client._xep_0096_waiting_for_approval[sid]
198 # return
199 # if stream_method == self.host.plugins["XEP-0065"].NAMESPACE:
200 # plugin = self.host.plugins["XEP-0065"]
201 # elif stream_method == self.host.plugins["XEP-0047"].NAMESPACE:
202 # plugin = self.host.plugins["XEP-0047"]
203 # else:
204 # log.error(_("Unknown stream method, this should not happen at this stage, cancelling transfer"))
205 # del client._xep_0096_waiting_for_approval[sid]
206 # return
207
208 # file_obj = self._getFileObject(dest_path, can_range)
209 # range_offset = file_obj.tell()
210 d = data['stream_plugin'].createSession(client, data['stream_object'], data['peer_jid'], data['si_id'])
211 d.addCallback(self._transferCb, client, data)
212 d.addErrback(self._transferEb, client, data)
213
214 #we can send the iq result
215 feature_elt = self.host.plugins["XEP-0020"].chooseOption({'stream-method': data['stream_method']}, namespace=None)
216 misc_elts = []
217 misc_elts.append(domish.Element((SI_PROFILE, "file")))
218 # if can_range:
219 # range_elt = domish.Element((None, "range"))
220 # range_elt['offset'] = str(range_offset)
221 # #TODO: manage range length
222 # misc_elts.append(range_elt)
223 self._si.acceptStream(client, iq_elt, feature_elt, misc_elts)
224
225 def _transferCb(self, dummy, client, data):
226 """Called by the stream method when transfer successfuly finished
227
228 @param data: session data
229 """
230 #TODO: check hash
231 data['stream_object'].close()
232 log.info(u'Transfer {si_id} successfuly finished'.format(**data))
233
234 def _transferEb(self, failure, client, data):
235 """Called when something went wrong with the transfer
236
237 @param id: stream id
238 @param data: session data
239 """
240 log.warning(u'Transfer {si_id} failed: {reason}'.format(reason=unicode(failure.value), **data))
241 data['stream_object'].close()
242
243 def _sendFile(self, peer_jid_s, filepath, name, desc, profile=C.PROF_KEY_NONE):
244 client = self.host.getClient(profile)
245 return self.sendFile(client, jid.JID(peer_jid_s), filepath, name or None, desc or None)
246
247 def sendFile(self, client, peer_jid, filepath, name=None, desc=None, extra=None):
248 """Send a file using XEP-0096
249
250 @param peer_jid(jid.JID): recipient
251 @param filepath(str): absolute path to the file to send
252 @param name(unicode): name of the file to send
253 name must not contain "/" characters
254 @param desc: description of the file
255 @param extra: not used here
256 @return: an unique id to identify the transfer
257 """
258 feature_elt = self.host.plugins["XEP-0020"].proposeFeatures({'stream-method': self.managed_stream_m}, namespace=None)
259
260 file_transfer_elts = []
261
262 statinfo = os.stat(filepath)
263 file_elt = domish.Element((SI_PROFILE, 'file'))
264 file_elt['name'] = name or os.path.basename(filepath)
265 assert '/' not in file_elt['name']
266 size = statinfo.st_size
267 file_elt['size'] = str(size)
268 if desc:
269 file_elt.addElement('desc', content=desc)
270 file_transfer_elts.append(file_elt)
271
272 file_transfer_elts.append(domish.Element((None, 'range')))
273
274 sid, offer_d = self._si.proposeStream(client, peer_jid, SI_PROFILE, feature_elt, file_transfer_elts)
275 args = [filepath, sid, size, client]
276 offer_d.addCallbacks(self._fileCb, self._fileEb, args, None, args)
277 return sid
278
279 def _fileCb(self, result_tuple, filepath, sid, size, client):
280 iq_elt, si_elt = result_tuple
281
282 try:
283 feature_elt = self.host.plugins["XEP-0020"].getFeatureElt(si_elt)
284 except exceptions.NotFound:
285 log.warning(u"No <feature/> element found in result while expected")
286 return
287
288 choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(feature_elt, namespace=None)
289 try:
290 stream_method = choosed_options["stream-method"]
291 except KeyError:
292 log.warning(u"No stream method choosed")
293 return
294
295 try:
296 file_elt = si_elt.elements(NS_SI_FT, "file").next()
297 except StopIteration:
298 pass
299 else:
300 range_, range_offset, range_length = self._parseRange(file_elt, size)
301
302 if stream_method == self.host.plugins["XEP-0065"].NAMESPACE:
303 plugin = self.host.plugins["XEP-0065"]
304 elif stream_method == self.host.plugins["XEP-0047"].NAMESPACE:
305 plugin = self.host.plugins["XEP-0047"]
306 else:
307 log.warning(u"Invalid stream method received")
308 return
309
310 stream_object = stream.FileStreamObject(self.host,
311 client,
312 filepath,
313 uid=sid,
314 size=size,
315 )
316 d = plugin.startStream(client, stream_object, jid.JID(iq_elt['from']), sid)
317 d.addCallback(self._sendCb, client, sid, stream_object)
318 d.addErrback(self._sendEb, client, sid, stream_object)
319
320 def _fileEb(self, failure, filepath, sid, size, client):
321 if failure.check(error.StanzaError):
322 stanza_err = failure.value
323 if stanza_err.code == '403' and stanza_err.condition == 'forbidden':
324 from_s = stanza_err.stanza['from']
325 log.info(u"File transfer refused by {}".format(from_s))
326 msg = D_(u"The contact {} has refused your file").format(from_s)
327 title = D_(u"File refused")
328 xml_tools.quickNote(self.host, client, msg, title, C.XMLUI_DATA_LVL_INFO)
329 else:
330 log.warning(_(u"Error during file transfer"))
331 msg = D_(u"Something went wrong during the file transfer session initialisation: {reason}").format(reason=unicode(stanza_err))
332 title = D_(u"File transfer error")
333 xml_tools.quickNote(self.host, client, msg, title, C.XMLUI_DATA_LVL_ERROR)
334 elif failure.check(exceptions.DataError):
335 log.warning(u'Invalid stanza received')
336 else:
337 log.error(u'Error while proposing stream: {}'.format(failure))
338
339 def _sendCb(self, dummy, client, sid, stream_object):
340 log.info(_(u'transfer {sid} successfuly finished [{profile}]').format(
341 sid=sid,
342 profile=client.profile))
343 stream_object.close()
344
345 def _sendEb(self, failure, client, sid, stream_object):
346 log.warning(_(u'transfer {sid} failed [{profile}]: {reason}').format(
347 sid=sid,
348 profile=client.profile,
349 reason=unicode(failure.value),
350 ))
351 stream_object.close()