comparison src/plugins/plugin_misc_upload.py @ 1640:d470affbe65c

plugin XEP-0363, upload: File upload (through HTTP upload only for now): - HTTP upload implementation - if the upload link is HTTPS, certificate is checked (can be disabled on demand) - file can be uploaded directly, or a put/get slot can be requested without actual upload. The later is mainly useful for distant frontends like Libervia - upload plugin manage different upload methods, in a similar way as file plugin - download url is sent in progressFinished metadata on successful upload
author Goffi <goffi@goffi.org>
date Sun, 22 Nov 2015 17:33:30 +0100
parents
children d17772b0fe22
comparison
equal deleted inserted replaced
1639:baac2e120600 1640:d470affbe65c
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # SAT plugin for file tansfer
5 # Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 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 "name": "File Upload",
34 "import_name": "UPLOAD",
35 "type": C.PLUG_TYPE_MISC,
36 "main": "UploadPlugin",
37 "handler": "no",
38 "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 upload_jid = jid.JID(upload_jid_s) if upload_jid_s else None
58 if options is None:
59 options = {}
60 # we convert values that are well-known booleans
61 for bool_option in BOOL_OPTIONS:
62 try:
63 options[bool_option] = C.bool(options[bool_option])
64 except KeyError:
65 pass
66
67 return self.fileUpload(filepath, filename or None, upload_jid, options or None, profile)
68
69 @defer.inlineCallbacks
70 def fileUpload(self, filepath, filename, upload_jid, options, profile=C.PROF_KEY_NONE):
71 """Send a file using best available method
72
73 @param filepath(str): absolute path to the file
74 @param filename(None, unicode): name to use for the upload
75 None to use basename of the path
76 @param upload_jid(jid.JID, None): upload capable entity jid,
77 or None to use autodetected, if possible
78 @param options(dict): option to use for the upload, may be:
79 - ignore-tls-errors(bool): True to ignore SSL/TLS certificate verification
80 used only if HTTPS transport is needed
81 @param profile: %(doc_profile)s
82 @return (dict): action dictionary, with progress id in case of success, else xmlui message
83 """
84 if not os.path.isfile(filepath):
85 raise exceptions.DataError(u"The given path doesn't link to a file")
86 for method_name, available_cb, upload_cb, priority in self._upload_callbacks:
87 try:
88 upload_jid = yield available_cb(upload_jid, profile)
89 except exceptions.NotFound:
90 continue # no entity managing this extension found
91 log.info(u"{name} method will be used to upload the file".format(name=method_name))
92 progress_id = yield defer.maybeDeferred(upload_cb, filepath, filename, upload_jid, options, profile)
93 defer.returnValue({'progress': progress_id})
94
95 # if we reach this point, no entity handling any known upload method has been found
96 msg = u"Can't find any method to upload a file"
97 log.warning(msg)
98 defer.returnValue({'xmlui': xml_tools.note(u"Can't upload file", msg, C.XMLUI_DATA_LVL_WARNING).toXml()})
99
100 def register(self, method_name, available_cb, upload_cb, priority=0):
101 """Register a fileUploading method
102
103 @param method_name(unicode): short name for the method, must be unique
104 @param available_cb(callable): method to call to check if this method is usable
105 the callback must take two arguments: upload_jid (can be None) and profile
106 the callback must return the first entity found (being upload_jid or one of its components)
107 exceptions.NotFound must be raised if no entity has been found
108 @param upload_cb(callable): method to upload a file (must have the same signature as [fileUpload])
109 @param priority(int): pririoty of this method, the higher available will be used
110 """
111 assert method_name
112 for data in self._upload_callbacks:
113 if method_name == data[0]:
114 raise exceptions.ConflictError(u'A method with this name is already registered')
115 self._upload_callbacks.append((method_name, available_cb, upload_cb, priority))
116 self._upload_callbacks.sort(key=lambda data: data[2], reverse=True)
117
118 def unregister(self, method_name):
119 for idx, data in enumerate(self._upload_callbacks):
120 if data[0] == method_name:
121 del [idx]
122 return
123 raise exceptions.NotFound(u"The name to unregister doesn't exist")