comparison src/bridge/dbus_bridge.py @ 2086:4633cfcbcccb

bridge (D-Bus): bad design fixes: - renamed outputed module to dbus_bridge (to avoid uppercase and conflict with dbus module) - class name is now Bridge for both frontend and core (make discovery/import more easy) - register renamed to register_method in core, and register_signal in frontend
author Goffi <goffi@goffi.org>
date Mon, 03 Oct 2016 21:15:39 +0200
parents src/bridge/DBus.py@da4097de5a95
children 9c861d07b5b6
comparison
equal deleted inserted replaced
2085:da4097de5a95 2086:4633cfcbcccb
1 #!/usr/bin/env python2
2 #-*- coding: utf-8 -*-
3
4 # SAT: a jabber client
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 _
21 import dbus
22 import dbus.service
23 import dbus.mainloop.glib
24 import inspect
25 from sat.core.log import getLogger
26 log = getLogger(__name__)
27 from twisted.internet.defer import Deferred
28 from sat.core.exceptions import BridgeInitError
29
30 const_INT_PREFIX = "org.goffi.SAT" # Interface prefix
31 const_ERROR_PREFIX = const_INT_PREFIX + ".error"
32 const_OBJ_PATH = '/org/goffi/SAT/bridge'
33 const_CORE_SUFFIX = ".core"
34 const_PLUGIN_SUFFIX = ".plugin"
35
36
37 class ParseError(Exception):
38 pass
39
40
41 class MethodNotRegistered(dbus.DBusException):
42 _dbus_error_name = const_ERROR_PREFIX + ".MethodNotRegistered"
43
44
45 class InternalError(dbus.DBusException):
46 _dbus_error_name = const_ERROR_PREFIX + ".InternalError"
47
48
49 class AsyncNotDeferred(dbus.DBusException):
50 _dbus_error_name = const_ERROR_PREFIX + ".AsyncNotDeferred"
51
52
53 class DeferredNotAsync(dbus.DBusException):
54 _dbus_error_name = const_ERROR_PREFIX + ".DeferredNotAsync"
55
56
57 class GenericException(dbus.DBusException):
58 def __init__(self, twisted_error):
59 """
60
61 @param twisted_error (Failure): instance of twisted Failure
62 @return: DBusException
63 """
64 super(GenericException, self).__init__()
65 try:
66 # twisted_error.value is a class
67 class_ = twisted_error.value().__class__
68 except TypeError:
69 # twisted_error.value is an instance
70 class_ = twisted_error.value.__class__
71 message = twisted_error.getErrorMessage()
72 try:
73 self.args = (message, twisted_error.value.condition)
74 except AttributeError:
75 self.args = (message,)
76 self._dbus_error_name = '.'.join([const_ERROR_PREFIX, class_.__module__, class_.__name__])
77
78
79 class DbusObject(dbus.service.Object):
80
81 def __init__(self, bus, path):
82 dbus.service.Object.__init__(self, bus, path)
83 log.debug("Init DbusObject...")
84 self.cb = {}
85
86 def register_method(self, name, cb):
87 self.cb[name] = cb
88
89 def _callback(self, name, *args, **kwargs):
90 """call the callback if it exists, raise an exception else
91 if the callback return a deferred, use async methods"""
92 if not name in self.cb:
93 raise MethodNotRegistered
94
95 if "callback" in kwargs:
96 #we must have errback too
97 if not "errback" in kwargs:
98 log.error("errback is missing in method call [%s]" % name)
99 raise InternalError
100 callback = kwargs.pop("callback")
101 errback = kwargs.pop("errback")
102 async = True
103 else:
104 async = False
105 result = self.cb[name](*args, **kwargs)
106 if async:
107 if not isinstance(result, Deferred):
108 log.error("Asynchronous method [%s] does not return a Deferred." % name)
109 raise AsyncNotDeferred
110 result.addCallback(lambda result: callback() if result is None else callback(result))
111 result.addErrback(lambda err: errback(GenericException(err)))
112 else:
113 if isinstance(result, Deferred):
114 log.error("Synchronous method [%s] return a Deferred." % name)
115 raise DeferredNotAsync
116 return result
117 ### signals ###
118
119 @dbus.service.signal(const_INT_PREFIX + const_PLUGIN_SUFFIX,
120 signature='')
121 def dummySignal(self):
122 #FIXME: workaround for addSignal (doesn't work if one method doensn't
123 # already exist for plugins), probably missing some initialisation, need
124 # further investigations
125 pass
126
127 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
128 signature='a{ss}sis')
129 def actionNew(self, action_data, id, security_limit, profile):
130 pass
131
132 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
133 signature='ss')
134 def connected(self, profile, jid_s):
135 pass
136
137 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
138 signature='ss')
139 def contactDeleted(self, entity_jid, profile):
140 pass
141
142 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
143 signature='s')
144 def disconnected(self, profile):
145 pass
146
147 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
148 signature='ssss')
149 def entityDataUpdated(self, jid, name, value, profile):
150 pass
151
152 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
153 signature='sdssa{ss}a{ss}sa{ss}s')
154 def messageNew(self, uid, timestamp, from_jid, to_jid, message, subject, mess_type, extra, profile):
155 pass
156
157 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
158 signature='sa{ss}ass')
159 def newContact(self, contact_jid, attributes, groups, profile):
160 pass
161
162 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
163 signature='ssss')
164 def paramUpdate(self, name, value, category, profile):
165 pass
166
167 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
168 signature='ssia{ss}s')
169 def presenceUpdate(self, entity_jid, show, priority, statuses, profile):
170 pass
171
172 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
173 signature='sss')
174 def progressError(self, id, error, profile):
175 pass
176
177 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
178 signature='sa{ss}s')
179 def progressFinished(self, id, metadata, profile):
180 pass
181
182 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
183 signature='sa{ss}s')
184 def progressStarted(self, id, metadata, profile):
185 pass
186
187 @dbus.service.signal(const_INT_PREFIX+const_CORE_SUFFIX,
188 signature='sss')
189 def subscribe(self, sub_type, entity_jid, profile):
190 pass
191
192 ### methods ###
193
194 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
195 in_signature='s', out_signature='a(a{ss}si)',
196 async_callbacks=None)
197 def actionsGet(self, profile_key="@DEFAULT@"):
198 return self._callback("actionsGet", unicode(profile_key))
199
200 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
201 in_signature='ss', out_signature='',
202 async_callbacks=None)
203 def addContact(self, entity_jid, profile_key="@DEFAULT@"):
204 return self._callback("addContact", unicode(entity_jid), unicode(profile_key))
205
206 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
207 in_signature='ss', out_signature='b',
208 async_callbacks=('callback', 'errback'))
209 def asyncConnect(self, profile_key="@DEFAULT@", password='', callback=None, errback=None):
210 return self._callback("asyncConnect", unicode(profile_key), unicode(password), callback=callback, errback=errback)
211
212 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
213 in_signature='ss', out_signature='',
214 async_callbacks=('callback', 'errback'))
215 def asyncCreateProfile(self, profile, password='', callback=None, errback=None):
216 return self._callback("asyncCreateProfile", unicode(profile), unicode(password), callback=callback, errback=errback)
217
218 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
219 in_signature='s', out_signature='',
220 async_callbacks=('callback', 'errback'))
221 def asyncDeleteProfile(self, profile, callback=None, errback=None):
222 return self._callback("asyncDeleteProfile", unicode(profile), callback=callback, errback=errback)
223
224 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
225 in_signature='sssis', out_signature='s',
226 async_callbacks=('callback', 'errback'))
227 def asyncGetParamA(self, name, category, attribute="value", security_limit=-1, profile_key="@DEFAULT@", callback=None, errback=None):
228 return self._callback("asyncGetParamA", unicode(name), unicode(category), unicode(attribute), security_limit, unicode(profile_key), callback=callback, errback=errback)
229
230 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
231 in_signature='sis', out_signature='a{ss}',
232 async_callbacks=('callback', 'errback'))
233 def asyncGetParamsValuesFromCategory(self, category, security_limit=-1, profile_key="@DEFAULT@", callback=None, errback=None):
234 return self._callback("asyncGetParamsValuesFromCategory", unicode(category), security_limit, unicode(profile_key), callback=callback, errback=errback)
235
236 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
237 in_signature='ss', out_signature='',
238 async_callbacks=('callback', 'errback'))
239 def delContact(self, entity_jid, profile_key="@DEFAULT@", callback=None, errback=None):
240 return self._callback("delContact", unicode(entity_jid), unicode(profile_key), callback=callback, errback=errback)
241
242 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
243 in_signature='ss', out_signature='(asa(sss)a{sa(a{ss}as)})',
244 async_callbacks=('callback', 'errback'))
245 def discoInfos(self, entity_jid, profile_key, callback=None, errback=None):
246 return self._callback("discoInfos", unicode(entity_jid), unicode(profile_key), callback=callback, errback=errback)
247
248 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
249 in_signature='ss', out_signature='a(sss)',
250 async_callbacks=('callback', 'errback'))
251 def discoItems(self, entity_jid, profile_key, callback=None, errback=None):
252 return self._callback("discoItems", unicode(entity_jid), unicode(profile_key), callback=callback, errback=errback)
253
254 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
255 in_signature='s', out_signature='',
256 async_callbacks=None)
257 def disconnect(self, profile_key="@DEFAULT@"):
258 return self._callback("disconnect", unicode(profile_key))
259
260 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
261 in_signature='ss', out_signature='s',
262 async_callbacks=None)
263 def getConfig(self, section, name):
264 return self._callback("getConfig", unicode(section), unicode(name))
265
266 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
267 in_signature='s', out_signature='a(sa{ss}as)',
268 async_callbacks=('callback', 'errback'))
269 def getContacts(self, profile_key="@DEFAULT@", callback=None, errback=None):
270 return self._callback("getContacts", unicode(profile_key), callback=callback, errback=errback)
271
272 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
273 in_signature='ss', out_signature='as',
274 async_callbacks=None)
275 def getContactsFromGroup(self, group, profile_key="@DEFAULT@"):
276 return self._callback("getContactsFromGroup", unicode(group), unicode(profile_key))
277
278 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
279 in_signature='asass', out_signature='a{sa{ss}}',
280 async_callbacks=None)
281 def getEntitiesData(self, jids, keys, profile):
282 return self._callback("getEntitiesData", jids, keys, unicode(profile))
283
284 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
285 in_signature='sass', out_signature='a{ss}',
286 async_callbacks=None)
287 def getEntityData(self, jid, keys, profile):
288 return self._callback("getEntityData", unicode(jid), keys, unicode(profile))
289
290 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
291 in_signature='s', out_signature='a{sa{ss}}',
292 async_callbacks=('callback', 'errback'))
293 def getFeatures(self, profile_key, callback=None, errback=None):
294 return self._callback("getFeatures", unicode(profile_key), callback=callback, errback=errback)
295
296 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
297 in_signature='ss', out_signature='s',
298 async_callbacks=None)
299 def getMainResource(self, contact_jid, profile_key="@DEFAULT@"):
300 return self._callback("getMainResource", unicode(contact_jid), unicode(profile_key))
301
302 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
303 in_signature='ss', out_signature='s',
304 async_callbacks=None)
305 def getMenuHelp(self, menu_id, language):
306 return self._callback("getMenuHelp", unicode(menu_id), unicode(language))
307
308 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
309 in_signature='si', out_signature='a(ssasasa{ss})',
310 async_callbacks=None)
311 def getMenus(self, language, security_limit):
312 return self._callback("getMenus", unicode(language), security_limit)
313
314 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
315 in_signature='ssss', out_signature='s',
316 async_callbacks=None)
317 def getParamA(self, name, category, attribute="value", profile_key="@DEFAULT@"):
318 return self._callback("getParamA", unicode(name), unicode(category), unicode(attribute), unicode(profile_key))
319
320 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
321 in_signature='', out_signature='as',
322 async_callbacks=None)
323 def getParamsCategories(self, ):
324 return self._callback("getParamsCategories", )
325
326 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
327 in_signature='iss', out_signature='s',
328 async_callbacks=('callback', 'errback'))
329 def getParamsUI(self, security_limit=-1, app='', profile_key="@DEFAULT@", callback=None, errback=None):
330 return self._callback("getParamsUI", security_limit, unicode(app), unicode(profile_key), callback=callback, errback=errback)
331
332 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
333 in_signature='s', out_signature='a{sa{s(sia{ss})}}',
334 async_callbacks=None)
335 def getPresenceStatuses(self, profile_key="@DEFAULT@"):
336 return self._callback("getPresenceStatuses", unicode(profile_key))
337
338 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
339 in_signature='s', out_signature='s',
340 async_callbacks=None)
341 def getProfileName(self, profile_key="@DEFAULT@"):
342 return self._callback("getProfileName", unicode(profile_key))
343
344 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
345 in_signature='', out_signature='as',
346 async_callbacks=None)
347 def getProfilesList(self, ):
348 return self._callback("getProfilesList", )
349
350 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
351 in_signature='', out_signature='',
352 async_callbacks=('callback', 'errback'))
353 def getReady(self, callback=None, errback=None):
354 return self._callback("getReady", callback=callback, errback=errback)
355
356 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
357 in_signature='', out_signature='s',
358 async_callbacks=None)
359 def getVersion(self, ):
360 return self._callback("getVersion", )
361
362 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
363 in_signature='s', out_signature='a{ss}',
364 async_callbacks=None)
365 def getWaitingSub(self, profile_key="@DEFAULT@"):
366 return self._callback("getWaitingSub", unicode(profile_key))
367
368 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
369 in_signature='ssiba{ss}s', out_signature='a(sdssa{ss}a{ss}sa{ss})',
370 async_callbacks=('callback', 'errback'))
371 def historyGet(self, from_jid, to_jid, limit, between=True, filters='', profile="@NONE@", callback=None, errback=None):
372 return self._callback("historyGet", unicode(from_jid), unicode(to_jid), limit, between, filters, unicode(profile), callback=callback, errback=errback)
373
374 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
375 in_signature='s', out_signature='b',
376 async_callbacks=None)
377 def isConnected(self, profile_key="@DEFAULT@"):
378 return self._callback("isConnected", unicode(profile_key))
379
380 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
381 in_signature='sa{ss}s', out_signature='a{ss}',
382 async_callbacks=('callback', 'errback'))
383 def launchAction(self, callback_id, data, profile_key="@DEFAULT@", callback=None, errback=None):
384 return self._callback("launchAction", unicode(callback_id), data, unicode(profile_key), callback=callback, errback=errback)
385
386 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
387 in_signature='s', out_signature='b',
388 async_callbacks=None)
389 def loadParamsTemplate(self, filename):
390 return self._callback("loadParamsTemplate", unicode(filename))
391
392 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
393 in_signature='sa{ss}a{ss}sa{ss}s', out_signature='',
394 async_callbacks=('callback', 'errback'))
395 def messageSend(self, to_jid, message, subject={}, mess_type="auto", extra={}, profile_key="@NONE@", callback=None, errback=None):
396 return self._callback("messageSend", unicode(to_jid), message, subject, unicode(mess_type), extra, unicode(profile_key), callback=callback, errback=errback)
397
398 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
399 in_signature='sis', out_signature='',
400 async_callbacks=None)
401 def paramsRegisterApp(self, xml, security_limit=-1, app=''):
402 return self._callback("paramsRegisterApp", unicode(xml), security_limit, unicode(app))
403
404 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
405 in_signature='s', out_signature='b',
406 async_callbacks=None)
407 def profileIsSessionStarted(self, profile_key="@DEFAULT@"):
408 return self._callback("profileIsSessionStarted", unicode(profile_key))
409
410 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
411 in_signature='s', out_signature='',
412 async_callbacks=None)
413 def profileSetDefault(self, profile):
414 return self._callback("profileSetDefault", unicode(profile))
415
416 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
417 in_signature='ss', out_signature='b',
418 async_callbacks=('callback', 'errback'))
419 def profileStartSession(self, password='', profile_key="@DEFAULT@", callback=None, errback=None):
420 return self._callback("profileStartSession", unicode(password), unicode(profile_key), callback=callback, errback=errback)
421
422 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
423 in_signature='ss', out_signature='a{ss}',
424 async_callbacks=None)
425 def progressGet(self, id, profile):
426 return self._callback("progressGet", unicode(id), unicode(profile))
427
428 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
429 in_signature='s', out_signature='a{sa{sa{ss}}}',
430 async_callbacks=None)
431 def progressGetAll(self, profile):
432 return self._callback("progressGetAll", unicode(profile))
433
434 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
435 in_signature='s', out_signature='a{sa{sa{ss}}}',
436 async_callbacks=None)
437 def progressGetAllMetadata(self, profile):
438 return self._callback("progressGetAllMetadata", unicode(profile))
439
440 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
441 in_signature='s', out_signature='b',
442 async_callbacks=None)
443 def saveParamsTemplate(self, filename):
444 return self._callback("saveParamsTemplate", unicode(filename))
445
446 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
447 in_signature='sssis', out_signature='',
448 async_callbacks=None)
449 def setParam(self, name, value, category, security_limit=-1, profile_key="@DEFAULT@"):
450 return self._callback("setParam", unicode(name), unicode(value), unicode(category), security_limit, unicode(profile_key))
451
452 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
453 in_signature='ssa{ss}s', out_signature='',
454 async_callbacks=None)
455 def setPresence(self, to_jid='', show='', statuses={}, profile_key="@DEFAULT@"):
456 return self._callback("setPresence", unicode(to_jid), unicode(show), statuses, unicode(profile_key))
457
458 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
459 in_signature='sss', out_signature='',
460 async_callbacks=None)
461 def subscription(self, sub_type, entity, profile_key="@DEFAULT@"):
462 return self._callback("subscription", unicode(sub_type), unicode(entity), unicode(profile_key))
463
464 @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
465 in_signature='ssass', out_signature='',
466 async_callbacks=('callback', 'errback'))
467 def updateContact(self, entity_jid, name, groups, profile_key="@DEFAULT@", callback=None, errback=None):
468 return self._callback("updateContact", unicode(entity_jid), unicode(name), groups, unicode(profile_key), callback=callback, errback=errback)
469
470 def __attributes(self, in_sign):
471 """Return arguments to user given a in_sign
472 @param in_sign: in_sign in the short form (using s,a,i,b etc)
473 @return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")"""
474 i = 0
475 idx = 0
476 attr = []
477 while i < len(in_sign):
478 if in_sign[i] not in ['b', 'y', 'n', 'i', 'x', 'q', 'u', 't', 'd', 's', 'a']:
479 raise ParseError("Unmanaged attribute type [%c]" % in_sign[i])
480
481 attr.append("arg_%i" % idx)
482 idx += 1
483
484 if in_sign[i] == 'a':
485 i += 1
486 if in_sign[i] != '{' and in_sign[i] != '(': # FIXME: must manage tuples out of arrays
487 i += 1
488 continue # we have a simple type for the array
489 opening_car = in_sign[i]
490 assert(opening_car in ['{', '('])
491 closing_car = '}' if opening_car == '{' else ')'
492 opening_count = 1
493 while (True): # we have a dict or a list of tuples
494 i += 1
495 if i >= len(in_sign):
496 raise ParseError("missing }")
497 if in_sign[i] == opening_car:
498 opening_count += 1
499 if in_sign[i] == closing_car:
500 opening_count -= 1
501 if opening_count == 0:
502 break
503 i += 1
504 return attr
505
506 def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False):
507 """Dynamically add a method to Dbus Bridge"""
508 inspect_args = inspect.getargspec(method)
509
510 _arguments = inspect_args.args
511 _defaults = list(inspect_args.defaults or [])
512
513 if inspect.ismethod(method):
514 #if we have a method, we don't want the first argument (usually 'self')
515 del(_arguments[0])
516
517 #first arguments are for the _callback method
518 arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback', 'errback=errback']) if async else _arguments))
519
520 if async:
521 _arguments.extend(['callback', 'errback'])
522 _defaults.extend([None, None])
523
524 #now we create a second list with default values
525 for i in range(1, len(_defaults) + 1):
526 _arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i]))
527
528 arguments_defaults = ', '.join(_arguments)
529
530 code = compile('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' %
531 {'name': name, 'arguments_defaults': arguments_defaults, 'arguments_callback': arguments_callback}, '<DBus bridge>', 'exec')
532 exec (code) # FIXME: to the same thing in a cleaner way, without compile/exec
533 method = locals()[name]
534 async_callbacks = ('callback', 'errback') if async else None
535 setattr(DbusObject, name, dbus.service.method(
536 const_INT_PREFIX + int_suffix, in_signature=in_sign, out_signature=out_sign,
537 async_callbacks=async_callbacks)(method))
538 function = getattr(self, name)
539 func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface]
540 func_table[function.__name__] = function # Needed for introspection
541
542 def addSignal(self, name, int_suffix, signature, doc={}):
543 """Dynamically add a signal to Dbus Bridge"""
544 attributes = ', '.join(self.__attributes(signature))
545 #TODO: use doc parameter to name attributes
546
547 #code = compile ('def '+name+' (self,'+attributes+'): log.debug ("'+name+' signal")', '<DBus bridge>','exec') #XXX: the log.debug is too annoying with xmllog
548 code = compile('def ' + name + ' (self,' + attributes + '): pass', '<DBus bridge>', 'exec')
549 exec (code)
550 signal = locals()[name]
551 setattr(DbusObject, name, dbus.service.signal(
552 const_INT_PREFIX + int_suffix, signature=signature)(signal))
553 function = getattr(self, name)
554 func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface]
555 func_table[function.__name__] = function # Needed for introspection
556
557
558 class Bridge(object):
559 def __init__(self):
560 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
561 log.info("Init DBus...")
562 try:
563 self.session_bus = dbus.SessionBus()
564 except dbus.DBusException as e:
565 if e._dbus_error_name == 'org.freedesktop.DBus.Error.NotSupported':
566 log.error(_(u"D-Bus is not launched, please see README to see instructions on how to launch it"))
567 raise BridgeInitError
568 self.dbus_name = dbus.service.BusName(const_INT_PREFIX, self.session_bus)
569 self.dbus_bridge = DbusObject(self.session_bus, const_OBJ_PATH)
570
571 def actionNew(self, action_data, id, security_limit, profile):
572 self.dbus_bridge.actionNew(action_data, id, security_limit, profile)
573
574 def connected(self, profile, jid_s):
575 self.dbus_bridge.connected(profile, jid_s)
576
577 def contactDeleted(self, entity_jid, profile):
578 self.dbus_bridge.contactDeleted(entity_jid, profile)
579
580 def disconnected(self, profile):
581 self.dbus_bridge.disconnected(profile)
582
583 def entityDataUpdated(self, jid, name, value, profile):
584 self.dbus_bridge.entityDataUpdated(jid, name, value, profile)
585
586 def messageNew(self, uid, timestamp, from_jid, to_jid, message, subject, mess_type, extra, profile):
587 self.dbus_bridge.messageNew(uid, timestamp, from_jid, to_jid, message, subject, mess_type, extra, profile)
588
589 def newContact(self, contact_jid, attributes, groups, profile):
590 self.dbus_bridge.newContact(contact_jid, attributes, groups, profile)
591
592 def paramUpdate(self, name, value, category, profile):
593 self.dbus_bridge.paramUpdate(name, value, category, profile)
594
595 def presenceUpdate(self, entity_jid, show, priority, statuses, profile):
596 self.dbus_bridge.presenceUpdate(entity_jid, show, priority, statuses, profile)
597
598 def progressError(self, id, error, profile):
599 self.dbus_bridge.progressError(id, error, profile)
600
601 def progressFinished(self, id, metadata, profile):
602 self.dbus_bridge.progressFinished(id, metadata, profile)
603
604 def progressStarted(self, id, metadata, profile):
605 self.dbus_bridge.progressStarted(id, metadata, profile)
606
607 def subscribe(self, sub_type, entity_jid, profile):
608 self.dbus_bridge.subscribe(sub_type, entity_jid, profile)
609
610 def register_method(self, name, callback):
611 log.debug("registering DBus bridge method [%s]" % name)
612 self.dbus_bridge.register_method(name, callback)
613
614 def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}):
615 """Dynamically add a method to Dbus Bridge"""
616 #FIXME: doc parameter is kept only temporary, the time to remove it from calls
617 log.debug("Adding method [%s] to DBus bridge" % name)
618 self.dbus_bridge.addMethod(name, int_suffix, in_sign, out_sign, method, async)
619 self.register_method(name, method)
620
621 def addSignal(self, name, int_suffix, signature, doc={}):
622 self.dbus_bridge.addSignal(name, int_suffix, signature, doc)
623 setattr(Bridge, name, getattr(self.dbus_bridge, name))