comparison sat/plugins/plugin_misc_upload.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_upload.py@0046283a285d
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 twisted.internet import defer
27 from twisted.words.protocols.jabber import jid
28 import os
29 import os.path
30
31
32 PLUGIN_INFO = {
33 C.PI_NAME: "File Upload",
34 C.PI_IMPORT_NAME: "UPLOAD",
35 C.PI_TYPE: C.PLUG_TYPE_MISC,
36 C.PI_MAIN: "UploadPlugin",
37 C.PI_HANDLER: "no",
38 C.PI_DESCRIPTION: _("""File upload management""")
39 }
40
41
42 UPLOADING = D_(u'Please select a file to upload')
43 UPLOADING_TITLE = D_(u'File upload')
44 BOOL_OPTIONS = ('ignore_tls_errors',)
45
46
47 class UploadPlugin(object):
48 # TODO: plugin unload
49
50 def __init__(self, host):
51 log.info(_("plugin Upload initialization"))
52 self.host = host
53 host.bridge.addMethod("fileUpload", ".plugin", in_sign='sssa{ss}s', out_sign='a{ss}', method=self._fileUpload, async=True)
54 self._upload_callbacks = []
55
56 def _fileUpload(self, filepath, filename, upload_jid_s='', options=None, profile=C.PROF_KEY_NONE):
57 client = self.host.getClient(profile)
58 upload_jid = jid.JID(upload_jid_s) if upload_jid_s else None
59 if options is None:
60 options = {}
61 # we convert values that are well-known booleans
62 for bool_option in BOOL_OPTIONS:
63 try:
64 options[bool_option] = C.bool(options[bool_option])
65 except KeyError:
66 pass
67
68 return self.fileUpload(client, filepath, filename or None, upload_jid, options or None)
69
70 def fileUpload(self, client, filepath, filename, upload_jid, options):
71 """Send a file using best available method
72
73 parameters are the same as for [upload]
74 @return (dict): action dictionary, with progress id in case of success, else xmlui message
75 """
76 def uploadCb(data):
77 progress_id, dummy = data
78 return {'progress': progress_id}
79
80 def uploadEb(fail):
81 msg = unicode(fail)
82 log.warning(msg)
83 return {'xmlui': xml_tools.note(u"Can't upload file", msg, C.XMLUI_DATA_LVL_WARNING).toXml()}
84
85 d = self.upload(client, filepath, filename, upload_jid, options)
86 d.addCallback(uploadCb)
87 d.addErrback(uploadEb)
88 return d
89
90 @defer.inlineCallbacks
91 def upload(self, client, filepath, filename=None, upload_jid=None, options=None):
92 """Send a file using best available method
93
94 @param filepath(str): absolute path to the file
95 @param filename(None, unicode): name to use for the upload
96 None to use basename of the path
97 @param upload_jid(jid.JID, None): upload capable entity jid,
98 or None to use autodetected, if possible
99 @param options(dict): option to use for the upload, may be:
100 - ignore_tls_errors(bool): True to ignore SSL/TLS certificate verification
101 used only if HTTPS transport is needed
102 @param profile: %(doc_profile)s
103 @return (tuple[unicode,D(unicode)]): progress_id and a Deferred which fire download URL
104 when upload is finished
105 """
106 if options is None:
107 options = {}
108 if not os.path.isfile(filepath):
109 raise exceptions.DataError(u"The given path doesn't link to a file")
110 for method_name, available_cb, upload_cb, priority in self._upload_callbacks:
111 try:
112 upload_jid = yield available_cb(upload_jid, client.profile)
113 except exceptions.NotFound:
114 continue # no entity managing this extension found
115
116 log.info(u"{name} method will be used to upload the file".format(name=method_name))
117 progress_id_d, download_d = yield upload_cb(filepath, filename, upload_jid, options, client.profile)
118 progress_id = yield progress_id_d
119 defer.returnValue((progress_id, download_d))
120
121 raise exceptions.NotFound(u"Can't find any method to upload a file")
122
123 def register(self, method_name, available_cb, upload_cb, priority=0):
124 """Register a fileUploading method
125
126 @param method_name(unicode): short name for the method, must be unique
127 @param available_cb(callable): method to call to check if this method is usable
128 the callback must take two arguments: upload_jid (can be None) and profile
129 the callback must return the first entity found (being upload_jid or one of its components)
130 exceptions.NotFound must be raised if no entity has been found
131 @param upload_cb(callable): method to upload a file
132 must have the same signature as [fileUpload]
133 must return a tuple with progress_id and a Deferred which fire download URL when
134 upload is finished
135 @param priority(int): pririoty of this method, the higher available will be used
136 """
137 assert method_name
138 for data in self._upload_callbacks:
139 if method_name == data[0]:
140 raise exceptions.ConflictError(u'A method with this name is already registered')
141 self._upload_callbacks.append((method_name, available_cb, upload_cb, priority))
142 self._upload_callbacks.sort(key=lambda data: data[3], reverse=True)
143
144 def unregister(self, method_name):
145 for idx, data in enumerate(self._upload_callbacks):
146 if data[0] == method_name:
147 del [idx]
148 return
149 raise exceptions.NotFound(u"The name to unregister doesn't exist")