comparison sat/plugins/plugin_misc_file.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_misc_file.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 file tansfer
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.internet import defer
28 from twisted.words.protocols.jabber import jid
29 import os
30 import os.path
31
32
33 PLUGIN_INFO = {
34 C.PI_NAME: "File Tansfer",
35 C.PI_IMPORT_NAME: "FILE",
36 C.PI_TYPE: C.PLUG_TYPE_MISC,
37 C.PI_MODES: C.PLUG_MODE_BOTH,
38 C.PI_MAIN: "FilePlugin",
39 C.PI_HANDLER: "no",
40 C.PI_DESCRIPTION: _("""File Tansfer Management:
41 This plugin manage the various ways of sending a file, and choose the best one.""")
42 }
43
44
45 SENDING = D_(u'Please select a file to send to {peer}')
46 SENDING_TITLE = D_(u'File sending')
47 CONFIRM = D_(u'{peer} wants to send the file "{name}" to you:\n{desc}\n\nThe file has a size of {size_human}\n\nDo you accept ?')
48 CONFIRM_TITLE = D_(u'Confirm file transfer')
49 CONFIRM_OVERWRITE = D_(u'File {} already exists, are you sure you want to overwrite ?')
50 CONFIRM_OVERWRITE_TITLE = D_(u'File exists')
51 SECURITY_LIMIT = 30
52
53 PROGRESS_ID_KEY = 'progress_id'
54
55
56 class FilePlugin(object):
57 File=stream.SatFile
58
59 def __init__(self, host):
60 log.info(_("plugin File initialization"))
61 self.host = host
62 host.bridge.addMethod("fileSend", ".plugin", in_sign='ssssa{ss}s', out_sign='a{ss}', method=self._fileSend, async=True)
63 self._file_callbacks = []
64 host.importMenu((D_("Action"), D_("send file")), self._fileSendMenu, security_limit=10, help_string=D_("Send a file"), type_=C.MENU_SINGLE)
65
66 def _fileSend(self, peer_jid_s, filepath, name="", file_desc="", extra=None, profile=C.PROF_KEY_NONE):
67 client = self.host.getClient(profile)
68 return self.fileSend(client, jid.JID(peer_jid_s), filepath, name or None, file_desc or None, extra)
69
70 @defer.inlineCallbacks
71 def fileSend(self, client, peer_jid, filepath, filename=None, file_desc=None, extra=None):
72 """Send a file using best available method
73
74 @param peer_jid(jid.JID): jid of the destinee
75 @param filepath(str): absolute path to the file
76 @param filename(unicode, None): name to use, or None to find it from filepath
77 @param file_desc(unicode, None): description of the file
78 @param profile: %(doc_profile)s
79 @return (dict): action dictionary, with progress id in case of success, else xmlui message
80 """
81 if not os.path.isfile(filepath):
82 raise exceptions.DataError(u"The given path doesn't link to a file")
83 if not filename:
84 filename = os.path.basename(filepath) or '_'
85 for namespace, callback, priority, method_name in self._file_callbacks:
86 has_feature = yield self.host.hasFeature(client, namespace, peer_jid)
87 if has_feature:
88 log.info(u"{name} method will be used to send the file".format(name=method_name))
89 progress_id = yield callback(client, peer_jid, filepath, filename, file_desc, extra)
90 defer.returnValue({'progress': progress_id})
91 msg = u"Can't find any method to send file to {jid}".format(jid=peer_jid.full())
92 log.warning(msg)
93 defer.returnValue({'xmlui': xml_tools.note(u"Can't transfer file", msg, C.XMLUI_DATA_LVL_WARNING).toXml()})
94
95 def _onFileChoosed(self, client, peer_jid, data):
96 cancelled = C.bool(data.get("cancelled", C.BOOL_FALSE))
97 if cancelled:
98 return
99 path=data['path']
100 return self.fileSend(client, peer_jid, path)
101
102 def _fileSendMenu(self, data, profile):
103 """ XMLUI activated by menu: return file sending UI
104
105 @param profile: %(doc_profile)s
106 """
107 try:
108 jid_ = jid.JID(data['jid'])
109 except RuntimeError:
110 raise exceptions.DataError(_("Invalid JID"))
111
112 file_choosed_id = self.host.registerCallback(lambda data, profile: self._onFileChoosed(self.host.getClient(profile), jid_, data), with_data=True, one_shot=True)
113 xml_ui = xml_tools.XMLUI(
114 C.XMLUI_DIALOG,
115 dialog_opt = {
116 C.XMLUI_DATA_TYPE: C.XMLUI_DIALOG_FILE,
117 C.XMLUI_DATA_MESS: _(SENDING).format(peer=jid_.full())},
118 title = _(SENDING_TITLE),
119 submit_id = file_choosed_id)
120
121 return {'xmlui': xml_ui.toXml()}
122
123 def register(self, namespace, callback, priority=0, method_name=None):
124 """Register a fileSending method
125
126 @param namespace(unicode): XEP namespace
127 @param callback(callable): method to call (must have the same signature as [fileSend])
128 @param priority(int): pririoty of this method, the higher available will be used
129 @param method_name(unicode): short name for the method, namespace will be used if None
130 """
131 for data in self._file_callbacks:
132 if namespace == data[0]:
133 raise exceptions.ConflictError(u'A method with this namespace is already registered')
134 self._file_callbacks.append((namespace, callback, priority, method_name or namespace))
135 self._file_callbacks.sort(key=lambda data: data[2], reverse=True)
136
137 def unregister(self, namespace):
138 for idx, data in enumerate(self._file_callbacks):
139 if data[0] == namespace:
140 del [idx]
141 return
142 raise exceptions.NotFound(u"The namespace to unregister doesn't exist")
143
144 # Dialogs with user
145 # the overwrite check is done here
146
147 def openFileWrite(self, client, file_path, transfer_data, file_data, stream_object):
148 """create SatFile or FileStremaObject for the requested file and fill suitable data
149 """
150 if stream_object:
151 assert 'stream_object' not in transfer_data
152 transfer_data['stream_object'] = stream.FileStreamObject(
153 self.host,
154 client,
155 file_path,
156 mode='wb',
157 uid=file_data[PROGRESS_ID_KEY],
158 size=file_data['size'],
159 data_cb = file_data.get('data_cb'),
160 )
161 else:
162 assert 'file_obj' not in transfer_data
163 transfer_data['file_obj'] = stream.SatFile(
164 self.host,
165 client,
166 file_path,
167 mode='wb',
168 uid=file_data[PROGRESS_ID_KEY],
169 size=file_data['size'],
170 data_cb = file_data.get('data_cb'),
171 )
172
173 def _gotConfirmation(self, data, client, peer_jid, transfer_data, file_data, stream_object):
174 """Called when the permission and dest path have been received
175
176 @param peer_jid(jid.JID): jid of the file sender
177 @param transfer_data(dict): same as for [self.getDestDir]
178 @param file_data(dict): same as for [self.getDestDir]
179 @param stream_object(bool): same as for [self.getDestDir]
180 return (bool): True if copy is wanted and OK
181 False if user wants to cancel
182 if file exists ask confirmation and call again self._getDestDir if needed
183 """
184 if data.get('cancelled', False):
185 return False
186 path = data['path']
187 file_data['file_path'] = file_path = os.path.join(path, file_data['name'])
188 log.debug(u'destination file path set to {}'.format(file_path))
189
190 # we manage case where file already exists
191 if os.path.exists(file_path):
192 def check_overwrite(overwrite):
193 if overwrite:
194 self.openFileWrite(client, file_path, transfer_data, file_data, stream_object)
195 return True
196 else:
197 return self.getDestDir(client, peer_jid, transfer_data, file_data)
198
199 exists_d = xml_tools.deferConfirm(
200 self.host,
201 _(CONFIRM_OVERWRITE).format(file_path),
202 _(CONFIRM_OVERWRITE_TITLE),
203 action_extra={'meta_from_jid': peer_jid.full(),
204 'meta_type': C.META_TYPE_OVERWRITE,
205 'meta_progress_id': file_data[PROGRESS_ID_KEY]
206 },
207 security_limit=SECURITY_LIMIT,
208 profile=client.profile)
209 exists_d.addCallback(check_overwrite)
210 return exists_d
211
212 self.openFileWrite(client, file_path, transfer_data, file_data, stream_object)
213 return True
214
215 def getDestDir(self, client, peer_jid, transfer_data, file_data, stream_object=False):
216 """Request confirmation and destination dir to user
217
218 Overwrite confirmation is managed.
219 if transfer is confirmed, 'file_obj' is added to transfer_data
220 @param peer_jid(jid.JID): jid of the file sender
221 @param filename(unicode): name of the file
222 @param transfer_data(dict): data of the transfer session,
223 it will be only used to store the file_obj.
224 "file_obj" (or "stream_object") key *MUST NOT* exist before using getDestDir
225 @param file_data(dict): information about the file to be transfered
226 It MUST contain the following keys:
227 - peer_jid (jid.JID): other peer jid
228 - name (unicode): name of the file to trasnsfer
229 the name must not be empty or contain a "/" character
230 - size (int): size of the file
231 - desc (unicode): description of the file
232 - progress_id (unicode): id to use for progression
233 It *MUST NOT* contain the "peer" key
234 It may contain:
235 - data_cb (callable): method called on each data read/write
236 "file_path" will be added to this dict once destination selected
237 "size_human" will also be added with human readable file size
238 @param stream_object(bool): if True, a stream_object will be used instead of file_obj
239 a stream.FileStreamObject will be used
240 return (defer.Deferred): True if transfer is accepted
241 """
242 cont,ret_value = self.host.trigger.returnPoint("FILE_getDestDir", client, peer_jid, transfer_data, file_data, stream_object)
243 if not cont:
244 return ret_value
245 filename = file_data['name']
246 assert filename and not '/' in filename
247 assert PROGRESS_ID_KEY in file_data
248 # human readable size
249 file_data['size_human'] = u'{:.6n} Mio'.format(float(file_data['size'])/(1024**2))
250 d = xml_tools.deferDialog(self.host,
251 _(CONFIRM).format(peer=peer_jid.full(), **file_data),
252 _(CONFIRM_TITLE),
253 type_=C.XMLUI_DIALOG_FILE,
254 options={C.XMLUI_DATA_FILETYPE: C.XMLUI_DATA_FILETYPE_DIR},
255 action_extra={'meta_from_jid': peer_jid.full(),
256 'meta_type': C.META_TYPE_FILE,
257 'meta_progress_id': file_data[PROGRESS_ID_KEY]
258 },
259 security_limit=SECURITY_LIMIT,
260 profile=client.profile)
261 d.addCallback(self._gotConfirmation, client, peer_jid, transfer_data, file_data, stream_object)
262 return d