2184
|
1 #!/usr/bin/env python2 |
|
2 # -*- coding: utf-8 -*- |
|
3 |
|
4 # SAT plugin for file tansfer |
|
5 # Copyright (C) 2009-2016 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 import exceptions |
|
23 from sat.core.log import getLogger |
|
24 log = getLogger(__name__) |
|
25 import shortuuid |
|
26 from sat.tools import utils |
|
27 from twisted.internet import defer |
|
28 from twisted.words.protocols.jabber import jid |
|
29 from twisted.words.protocols.jabber import error |
|
30 from sat.memory import persistent |
|
31 from sat.tools import email as sat_email |
|
32 |
|
33 |
|
34 PLUGIN_INFO = { |
|
35 C.PI_NAME: "Invitations", |
|
36 C.PI_IMPORT_NAME: "INVITATIONS", |
|
37 C.PI_TYPE: C.PLUG_TYPE_MISC, |
|
38 C.PI_DEPENDENCIES: ['XEP-0077'], |
|
39 C.PI_MAIN: "InvitationsPlugin", |
|
40 C.PI_HANDLER: "no", |
|
41 C.PI_DESCRIPTION: _(u"""invitation of people without XMPP account""") |
|
42 } |
|
43 |
|
44 |
|
45 SUFFIX_MAX = 5 |
|
46 INVITEE_PROFILE_TPL = u"guest@@{uuid}" |
|
47 KEY_CREATED = u'created' |
|
48 KEY_LAST_CONNECTION = u'last_connection' |
|
49 EXTRA_RESERVED = {KEY_CREATED, u'jid_', u'jid', KEY_LAST_CONNECTION} |
|
50 DEFAULT_SUBJECT = D_(u"You have been invited by {host_name} to {app_name}") |
|
51 DEFAULT_BODY = D_(u"""Hello {name}! |
|
52 |
|
53 You have received an invitation from {host_name} to participate to "{app_name}". |
|
54 To join, you just have to click on the following URL: |
|
55 {url} |
|
56 |
|
57 Please note that this URL should not be shared with anybody! |
|
58 If you want more details on {app_name}, you can check {app_url}. |
|
59 |
|
60 Welcome! |
|
61 """) |
|
62 |
|
63 |
|
64 class InvitationsPlugin(object): |
|
65 |
|
66 def __init__(self, host): |
|
67 log.info(_(u"plugin Invitations initialization")) |
|
68 self.host = host |
|
69 self.invitations = persistent.LazyPersistentBinaryDict(u'invitations') |
|
70 host.bridge.addMethod("invitationCreate", ".plugin", in_sign='sssssssssa{ss}s', out_sign='(sa{ss})', |
|
71 method=self._createInvitation, |
|
72 async=True) |
|
73 def _createInvitation(self, jid_=u'', password=u'', name=u'', host_name=u'', email=u'', language=u'', url_template=u'', message_subject=u'', message_body=u'', extra=None, profile=u''): |
|
74 # XXX: we don't use **kwargs here to keep arguments name for introspection with D-Bus bridge |
|
75 |
|
76 if extra is None: |
|
77 extra = {} |
|
78 else: |
|
79 extra = {unicode(k): unicode(v) for k,v in extra.iteritems()} |
|
80 |
|
81 # we need to be sure that values are unicode, else they won't be pickled correctly with D-Bus |
|
82 kwargs = {"extra": extra} |
|
83 for key in ("jid_", "password", "name", "host_name", "email", "language", "url_template", "message_subject", "message_body", "profile"): |
|
84 value = locals()[key] |
|
85 if value: |
|
86 kwargs[key] = unicode(value) |
|
87 return self.createInvitation(**kwargs) |
|
88 |
|
89 @defer.inlineCallbacks |
|
90 def createInvitation(self, **kwargs): |
|
91 ur"""create an invitation |
|
92 |
|
93 this will create an XMPP account and a profile, and use a UUID to retrieve them. |
|
94 the profile is automatically generated in the form guest@@[UUID], this way they can be retrieved easily |
|
95 **kwargs: keywords arguments which can have the following keys, unset values are equivalent to None: |
|
96 jid_(jid.JID, None): jid to use for invitation, the jid will be created using XEP-0077 |
|
97 if the jid has no user part, an anonymous account will be used (no XMPP account created in this case) |
|
98 if None, automatically generate an account name (in the form "invitation-[UUID]@domain.tld") |
|
99 in case of conflict, a suffix number is added to the account until a free one if found (with a failure if SUFFIX_MAX is reached) |
|
100 password(unicode, None): password to use (will be used for XMPP account and profile) |
|
101 None to automatically generate one |
|
102 name(unicode, None): name of the invitee |
|
103 host_name(unicode, None): name of the host |
|
104 email(unicode, None): email to send the invitation to |
|
105 if None, no invitation email is sent, you can still associate email using extra |
|
106 if email is used, extra can't have "email" key |
|
107 language(unicode): language of the invitee (used notabily to translate the invitation) |
|
108 TODO: not used yet |
|
109 url_template(unicode, None): template to use to construct the invitation URL |
|
110 use {uuid} as a placeholder for identifier |
|
111 use None if you don't want to include URL (or if it is already specified in custom message) |
|
112 /!\ you must put full URL, don't forget https:// |
|
113 /!\ the URL will give access to the invitee account, you should warn in message to not publish it publicly |
|
114 message_subject(unicode, None): customised message body for t:o he invitation email |
|
115 None to use default subject |
|
116 uses the same substitution as for message_body |
|
117 message_body(unicode, None): customised message body for the invitation email |
|
118 None to use default body |
|
119 use {name} as a place holder for invitee name |
|
120 use {url} as a placeholder for the invitation url |
|
121 use {uuid} as a placeholder for the identifier |
|
122 use {app_name} as a placeholder for this software name |
|
123 use {app_url} as a placeholder for this software official website |
|
124 use {profile} as a placeholder for host's profile |
|
125 use {host_name} as a placeholder for host's name |
|
126 extra(dict, None): extra data to associate with the invitee |
|
127 some keys are reserved: |
|
128 - created (creation date) |
|
129 if email argument is used, "email" key can't be used |
|
130 profile(unicode, None): profile of the host (person who is inviting) |
|
131 @return (unicode, dict[unicode, unicode]): tuple with: |
|
132 - UUID associated with the invitee |
|
133 - filled extra dictionary, as saved in the databae |
|
134 """ |
|
135 ## initial checks |
|
136 extra = kwargs.pop('extra', {}) |
|
137 if set(kwargs).intersection(extra): |
|
138 raise exceptions.ValueError(_(u"You can't use following key(s) in both args and extra: {}").format( |
|
139 u', '.join(set(kwargs).intersection(extra)))) |
|
140 |
|
141 if EXTRA_RESERVED.intersection(extra): |
|
142 raise exceptions.ValueError(_(u"You can't use following key(s) in extra, they are reserved: {}").format( |
|
143 u', '.join(EXTRA_RESERVED.intersection(extra)))) |
|
144 |
|
145 ## uuid |
|
146 log.info(_(u"creating an invitation")) |
|
147 id_ = unicode(shortuuid.uuid()) |
|
148 |
|
149 ## XMPP account creation |
|
150 password = kwargs.pop(u'password', None) |
|
151 if password is None: |
|
152 password = utils.generatePassword() |
|
153 assert password |
|
154 # XXX: password is here saved in clear in database |
|
155 # it is needed for invitation as the same password is used for profile |
|
156 # and SàT need to be able to automatically open the profile with the uuid |
|
157 # FIXME: we could add an extra encryption key which would be used with the uuid |
|
158 # when the invitee is connecting (e.g. with URL). This key would not be saved |
|
159 # and could be used to encrypt profile password. |
|
160 extra[u'password'] = password |
|
161 |
|
162 jid_ = kwargs.pop(u'jid_', None) |
|
163 if not jid_: |
|
164 domain = self.host.memory.getConfig(None, 'xmpp_domain') |
|
165 if not domain: |
|
166 # TODO: fallback to profile's domain |
|
167 raise ValueError(_(u"You need to specify xmpp_domain in sat.conf")) |
|
168 jid_ = u"invitation-{uuid}@{domain}".format(uuid=id_, domain=domain) |
|
169 jid_ = jid.JID(jid_) |
|
170 if jid_.user: |
|
171 # we don't register account if there is no user as anonymous login is then used |
|
172 try: |
|
173 yield self.host.plugins['XEP-0077'].registerNewAccount(jid_, password) |
|
174 except error.StanzaError as e: |
|
175 prefix = jid_.user |
|
176 idx = 0 |
|
177 while e.condition == u'conflict': |
|
178 if idx >= SUFFIX_MAX: |
|
179 raise exceptions.ConflictError(_(u"Can't create XMPP account")) |
|
180 jid_.user = prefix + '_' + unicode(idx) |
|
181 log.info(_(u"requested jid already exists, trying with {}".format(jid_.full()))) |
|
182 try: |
|
183 yield self.host.plugins['XEP-0077'].registerNewAccount(jid_, password) |
|
184 except error.StanzaError as e: |
|
185 idx += 1 |
|
186 else: |
|
187 break |
|
188 if e.condition != u'conflict': |
|
189 raise e |
|
190 |
|
191 log.info(_(u"account {jid_} created").format(jid_=jid_.full())) |
|
192 |
|
193 ## profile creation |
|
194 extra['guest_profile'] = guest_profile = INVITEE_PROFILE_TPL.format(uuid=id_) |
|
195 # profile creation should not fail as we generate unique name ourselves |
|
196 yield self.host.memory.createProfile(guest_profile, password) |
|
197 yield self.host.memory.startSession(password, guest_profile) |
|
198 yield self.host.memory.setParam("JabberID", jid_.full(), "Connection", profile_key=guest_profile) |
|
199 yield self.host.memory.setParam("Password", password, "Connection", profile_key=guest_profile) |
|
200 |
|
201 ## email |
|
202 language = kwargs.pop(u'language', None) |
|
203 if language is not None: |
|
204 extra[u'language'] = language |
|
205 email = kwargs.pop(u'email', None) |
|
206 |
|
207 if email is not None: |
|
208 url_template = kwargs.pop(u'url_template', '') |
|
209 format_args = { |
|
210 u'uuid': id_, |
|
211 u'app_name': C.APP_NAME, |
|
212 u'app_url': C.APP_URL} |
|
213 |
|
214 name = kwargs.pop(u'name', None) |
|
215 if name is None: |
|
216 format_args[u'name'] = email |
|
217 else: |
|
218 format_args[u'name'] = extra[u'name'] = name |
|
219 |
|
220 profile = kwargs.pop(u'profile', None) |
|
221 if profile is None: |
|
222 format_args[u'profile'] = u'' |
|
223 else: |
|
224 format_args[u'profile'] = extra[u'profile'] = profile |
|
225 |
|
226 host_name = kwargs.pop(u'host_name', None) |
|
227 if host_name is None: |
|
228 format_args[u'host_name'] = profile or _(u"somebody") |
|
229 else: |
|
230 format_args[u'host_name'] = extra[u'host_name'] = host_name |
|
231 |
|
232 invite_url = url_template.format(**format_args) |
|
233 format_args[u'url'] = invite_url |
|
234 |
|
235 yield sat_email.sendEmail( |
|
236 self.host, |
|
237 [email], |
|
238 (kwargs.pop(u'message_subject', None) or DEFAULT_SUBJECT).format(**format_args), |
|
239 (kwargs.pop(u'message_body', None) or DEFAULT_BODY).format(**format_args), |
|
240 ) |
|
241 |
|
242 ## extra data saving |
|
243 self.invitations[id_] = extra |
|
244 |
|
245 if kwargs: |
|
246 log.warning(_(u"Not all arguments have been consumed: {}").format(kwargs)) |
|
247 |
|
248 defer.returnValue((id_, extra)) |