comparison src/plugins/plugin_exp_pipe.py @ 401:b2caa2615c4c

jp roster name manegement + Pipe transfer - added experimental pipe transfer protocol (based on xep-0096) - jp now manage roster name to jid conversion (if an argument correspond to a roster name, it replace it with the corresponding jid) - jp now add last known resource of when a resource is needed but we have a bare jid (e.g. for file or pipe transfer)
author Goffi <goffi@goffi.org>
date Fri, 07 Oct 2011 00:25:15 +0200
parents
children cf005701624b
comparison
equal deleted inserted replaced
400:22788653ae8d 401:b2caa2615c4c
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 """
5 SAT plugin for managing pipes (experimental)
6 Copyright (C) 2009, 2010, 2011 Jérôme Poisson (goffi@goffi.org)
7
8 This program is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 """
21
22 from logging import debug, info, warning, error
23 from twisted.words.xish import domish
24 from twisted.internet import protocol
25 from twisted.words.protocols.jabber import client, jid
26 from twisted.words.protocols.jabber import error as jab_error
27 import os, os.path
28 from twisted.internet import reactor
29 import pdb
30
31 from zope.interface import implements
32
33 from wokkel import disco, iwokkel, data_form
34
35 IQ_SET = '/iq[@type="set"]'
36 PROFILE_NAME = "pipe-transfer"
37 PROFILE = "http://jabber.org/protocol/si/profile/" + PROFILE_NAME
38
39 PLUGIN_INFO = {
40 "name": "Pipe Plugin",
41 "import_name": "EXP-PIPE",
42 "type": "EXP",
43 "protocols": ["EXP-PIPE"],
44 "dependencies": ["XEP-0020", "XEP-0095", "XEP-0065", "XEP-0047"],
45 "main": "Exp_Pipe",
46 "handler": "no",
47 "description": _("""Implementation of SI Pipe Transfer""")
48 }
49
50 class Exp_Pipe():
51 """This is a modified version of XEP-0096 to work with named pipes instead of files"""
52
53 def __init__(self, host):
54 info(_("Plugin Pipe initialization"))
55 self.host = host
56 self._waiting_for_approval = {} #key = id, value = [transfer data, IdelayedCall Reactor timeout,
57 # current stream method, [failed stream methods], profile]
58 self.managed_stream_m = [self.host.plugins["XEP-0065"].NAMESPACE,
59 self.host.plugins["XEP-0047"].NAMESPACE] #Stream methods managed
60 self.host.plugins["XEP-0095"].registerSIProfile(PROFILE_NAME, self.transferRequest)
61 host.bridge.addMethod("pipeOut", ".plugin", in_sign='ssa{ss}s', out_sign='s', method=self.pipeOut)
62
63 def _kill_id(self, approval_id):
64 """Delete a waiting_for_approval id, called after timeout
65 @param approval_id: id of _waiting_for_approval"""
66 info(_("SI Pipe Transfer: TimeOut reached for id %s") % approval_id);
67 try:
68 del self._waiting_for_approval[approval_id]
69 except KeyError:
70 warning(_("kill id called on a non existant approval id"))
71
72 def transferRequest(self, iq_id, from_jid, si_id, si_mime_type, si_el, profile):
73 """Called when a pipe transfer is requested
74 @param iq_id: id of the iq request
75 @param from_jid: jid of the sender
76 @param si_id: Stream Initiation session id
77 @param si_mime_type: Mime type of the pipe (or default "application/octet-stream" if unknown)
78 @param si_el: domish.Element of the request
79 @param profile: %(doc_profile)s"""
80 info (_("EXP-PIPE file transfer requested"))
81 debug(si_el.toXml())
82 pipe_elts = filter(lambda elt: elt.name == 'pipe', si_el.elements())
83 feature_elts = self.host.plugins["XEP-0020"].getFeatureElt(si_el)
84
85 if not pipe_elts:
86 warning(_("No pipe element found"))
87 self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
88 return
89
90 if feature_elts:
91 feature_el = feature_elts[0]
92 form = data_form.Form.fromElement(feature_el.firstChildElement())
93 try:
94 stream_method = self.host.plugins["XEP-0020"].negociate(feature_el, 'stream-method',self.managed_stream_m)
95 except KeyError:
96 warning(_("No stream method found"))
97 self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
98 return
99 if not stream_method:
100 warning(_("Can't find a valid stream method"))
101 self.host.plugins["XEP-0095"].sendFailedError(iq_id, from_jid, profile)
102 return
103 else:
104 warning(_("No feature element found"))
105 self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
106 return
107
108 #if we are here, the transfer can start, we just need user's agreement
109 data={ "id": iq_id, "from":from_jid }
110 self._waiting_for_approval[si_id] = [data, reactor.callLater(300, self._kill_id, si_id), stream_method, [], profile]
111
112 self.host.askConfirmation(si_id, "PIPE_TRANSFER", data, self.confirmationCB)
113
114
115 def confirmationCB(self, sid, accepted, frontend_data):
116 """Called on confirmation answer
117 @param sid: file transfer session id
118 @param accepted: True if file transfer is accepted
119 @param frontend_data: data sent by frontend"""
120 data, timeout, stream_method, failed_methods, profile = self._waiting_for_approval[sid]
121 if accepted:
122 if timeout.active():
123 timeout.cancel()
124 try:
125 dest_path = frontend_data['dest_path']
126 except KeyError:
127 error(_('dest path not found in frontend_data'))
128 del(self._waiting_for_approval[sid])
129 return
130 if stream_method == self.host.plugins["XEP-0065"].NAMESPACE:
131 file_obj = open(dest_path, 'w+')
132 self.host.plugins["XEP-0065"].prepareToReceive(jid.JID(data['from']), sid, file_obj, None, self._transferSucceeded, self._transferFailed)
133 elif stream_method == self.host.plugins["XEP-0047"].NAMESPACE:
134 file_obj = open(dest_path, 'w+')
135 self.host.plugins["XEP-0047"].prepareToReceive(jid.JID(data['from']), sid, file_obj, None, self._transferSucceeded, self._transferFailed)
136 else:
137 error(_("Unknown stream method, this should not happen at this stage, cancelling transfer"))
138 del(self._waiting_for_approval[sid])
139 return
140
141 #we can send the iq result
142 feature_elt = self.host.plugins["XEP-0020"].chooseOption({'stream-method':stream_method})
143 misc_elts = []
144 misc_elts.append(domish.Element((PROFILE, "file")))
145 self.host.plugins["XEP-0095"].acceptStream(data["id"], data['from'], feature_elt, misc_elts, profile)
146 else:
147 debug (_("Transfer [%s] refused"), sid)
148 self.host.plugins["XEP-0095"].sendRejectedError (data["id"], data['from'], profile=profile)
149 del(self._waiting_for_approval[sid])
150
151 def _transferSucceeded(self, sid, file_obj, stream_method):
152 """Called by the stream method when transfer successfuly finished
153 @param id: stream id"""
154 file_obj.close()
155 info(_('Transfer %s successfuly finished') % sid)
156 del(self._waiting_for_approval[sid])
157
158 def _transferFailed(self, sid, file_obj, stream_method, reason):
159 """Called when something went wrong with the transfer
160 @param id: stream id
161 @param reason: can be TIMEOUT, IO_ERROR, PROTOCOL_ERROR"""
162 data, timeout, stream_method, failed_methods, profile = self._waiting_for_approval[sid]
163 warning(_('Transfer %(id)s failed with stream method %(s_method)s') % { 'id': sid,
164 's_method': stream_method })
165 filepath = file_obj.name
166 file_obj.close()
167 #TODO: session remenber (within a time limit) when a stream method fail, and avoid that stream method with full jid for the rest of the session
168 warning(_("All stream methods failed, can't transfer the file"))
169 del(self._waiting_for_approval[sid])
170
171 def pipeCb(self, profile, filepath, sid, IQ):
172 if IQ['type'] == "error":
173 stanza_err = jab_error.exceptionFromStanza(IQ)
174 if stanza_err.code == '403' and stanza_err.condition == 'forbidden':
175 debug(_("Pipe transfer refused by %s") % IQ['from'])
176 self.host.bridge.newAlert(_("The contact %s refused your pipe stream") % IQ['from'], _("Pipe stream refused"), "INFO", profile)
177 else:
178 warning(_("Error during pipe stream transfer with %s") % IQ['from'])
179 self.host.bridge.newAlert(_("Something went wrong during the pipe stream session intialisation with %s") % IQ['from'], _("Pipe stream error"), "ERROR", profile)
180 return
181
182 si_elt = IQ.firstChildElement()
183
184 if IQ['type'] != "result" or not si_elt or si_elt.name != "si":
185 error(_("Protocol error during file transfer"))
186 return
187
188 feature_elts = self.host.plugins["XEP-0020"].getFeatureElt(si_elt)
189 if not feature_elts:
190 warning(_("No feature element"))
191 return
192
193 choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(feature_elts[0])
194 try:
195 stream_method = choosed_options["stream-method"]
196 except KeyError:
197 warning(_("No stream method choosed"))
198 return
199
200 if stream_method == self.host.plugins["XEP-0065"].NAMESPACE:
201 #fd = os.open(filepath, os.O_RDONLY | os.O_NONBLOCK) #XXX: non blocking openingl cause issues with XEP-0065's FileSender
202 #file_obj = os.fdopen(fd, 'r')
203 file_obj = open(filepath, 'r') #XXX: we have to be sure that filepath is well opened, as reading can block it
204 self.host.plugins["XEP-0065"].startStream(file_obj, jid.JID(IQ['from']), sid, None, self.sendSuccessCb, self.sendFailureCb, None, profile)
205 elif stream_method == self.host.plugins["XEP-0047"].NAMESPACE:
206 #fd = os.open(filepath, os.O_RDONLY | os.O_NONBLOCK) #XXX: non blocking openingl cause issues with XEP-0065's FileSender
207 #file_obj = os.fdopen(fd, 'r')
208 file_obj = open(filepath, 'r') #XXX: we have to be sure that filepath is well opened, as reading can block it
209 self.host.plugins["XEP-0047"].startStream(file_obj, jid.JID(IQ['from']), sid, None, self.sendSuccessCb, self.sendFailureCb, None, profile)
210 else:
211 warning(_("Invalid stream method received"))
212
213 def pipeOut(self, to_jid, filepath, data={}, profile_key='@DEFAULT@'):
214 """send a file using EXP-PIPE
215 @to_jid: recipient
216 @filepath: absolute path to the named pipe to send
217 @data: dictionnary with the optional data
218 @param profile_key: %(doc_profile_key)s
219 @return: an unique id to identify the transfer
220 """
221 profile = self.host.memory.getProfileName(profile_key)
222 if not profile:
223 warning(_("Trying to send a file from an unknown profile"))
224 return ""
225 feature_elt = self.host.plugins["XEP-0020"].proposeFeatures({'stream-method': self.managed_stream_m})
226
227 pipe_transfer_elts = []
228
229 pipe_elt = domish.Element((PROFILE, 'pipe'))
230 pipe_transfer_elts.append(pipe_elt)
231
232 sid, offer = self.host.plugins["XEP-0095"].proposeStream(jid.JID(to_jid), PROFILE, feature_elt, pipe_transfer_elts, profile_key = profile)
233 offer.addCallback(self.pipeCb, profile, filepath, sid)
234 return sid
235
236 def sendSuccessCb(self, sid, file_obj, stream_method):
237 info(_('Transfer %s successfuly finished') % sid)
238 file_obj.close()
239
240 def sendFailureCb(self, sid, file_obj, stream_method, reason):
241 file_obj.close()
242 warning(_('Transfer %(id)s failed with stream method %(s_method)s') % { 'id': sid, "s_method": stream_method })