Fix pep8 support in src/bridge.

This commit is contained in:
Emmanuel Gil Peyrot 2013-01-18 17:55:35 +01:00
commit 60f648fdf4

View file

@ -19,7 +19,6 @@ You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from bridge import Bridge
import dbus
import dbus.service
@ -28,42 +27,49 @@ import inspect
from logging import debug, info, error
from twisted.internet.defer import Deferred
const_INT_PREFIX = "org.goffi.SAT" #Interface prefix
const_ERROR_PREFIX = const_INT_PREFIX+".error"
const_INT_PREFIX = "org.goffi.SAT" # Interface prefix
const_ERROR_PREFIX = const_INT_PREFIX + ".error"
const_OBJ_PATH = '/org/goffi/SAT/bridge'
const_CORE_SUFFIX = ".core"
const_PLUGIN_SUFFIX = ".plugin"
class ParseError(Exception):
pass
class MethodNotRegistered(dbus.DBusException):
_dbus_error_name = const_ERROR_PREFIX + ".MethodNotRegistered"
class InternalError(dbus.DBusException):
_dbus_error_name = const_ERROR_PREFIX + ".InternalError"
class AsyncNotDeferred(dbus.DBusException):
_dbus_error_name = const_ERROR_PREFIX + ".AsyncNotDeferred"
class DeferredNotAsync(dbus.DBusException):
_dbus_error_name = const_ERROR_PREFIX + ".DeferredNotAsync"
class GenericException(dbus.DBusException):
def __init__(self, twisted_error):
super(GenericException,self).__init__()
super(GenericException, self).__init__()
mess = twisted_error.getErrorMessage()
self._dbus_error_name = const_ERROR_PREFIX+"."+ (mess or str(twisted_error.__class__))
self._dbus_error_name = const_ERROR_PREFIX + "." + (mess or str(twisted_error.__class__))
class DbusObject(dbus.service.Object):
def __init__(self, bus, path):
dbus.service.Object.__init__(self, bus, path)
debug("Init DbusObject...")
self.cb={}
self.cb = {}
def register(self, name, cb):
self.cb[name]=cb
self.cb[name] = cb
def _callback(self, name, *args, **kwargs):
"""call the callback if it exists, raise an exception else
@ -86,17 +92,16 @@ class DbusObject(dbus.service.Object):
if not isinstance(result, Deferred):
error("Asynchronous method [%s] does not return a Deferred." % name)
raise AsyncNotDeferred
result.addCallback(lambda result: callback() if result==None else callback(result))
result.addErrback(lambda err:errback(GenericException(err)))
result.addCallback(lambda result: callback() if result is None else callback(result))
result.addErrback(lambda err: errback(GenericException(err)))
else:
if isinstance(result, Deferred):
error("Synchronous method [%s] return a Deferred." % name)
raise DeferredNotAsync
return result
### signals ###
@dbus.service.signal(const_INT_PREFIX+const_PLUGIN_SUFFIX,
@dbus.service.signal(const_INT_PREFIX + const_PLUGIN_SUFFIX,
signature='')
def dummySignal(self):
#FIXME: workaround for addSignal (doesn't work if one method doensn't
@ -174,7 +179,6 @@ class DbusObject(dbus.service.Object):
def subscribe(self, sub_type, entity_jid, profile):
pass
### methods ###
@dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
@ -411,41 +415,40 @@ class DbusObject(dbus.service.Object):
def updateContact(self, entity_jid, name, groups, profile_key="@DEFAULT@"):
return self._callback("updateContact", unicode(entity_jid), unicode(name), groups, unicode(profile_key))
def __attributes(self, in_sign):
"""Return arguments to user given a in_sign
@param in_sign: in_sign in the short form (using s,a,i,b etc)
@return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")"""
i=0
idx=0
attr=[]
while i<len(in_sign):
if in_sign[i] not in ['b','y','n','i','x','q','u','t','d','s','a']:
i = 0
idx = 0
attr = []
while i < len(in_sign):
if in_sign[i] not in ['b', 'y', 'n', 'i', 'x', 'q', 'u', 't', 'd', 's', 'a']:
raise ParseError("Unmanaged attribute type [%c]" % in_sign[i])
attr.append("arg_%i" % idx)
idx+=1
idx += 1
if in_sign[i] == 'a':
i+=1
if in_sign[i]!='{' and in_sign[i]!='(': #FIXME: must manage tuples out of arrays
i+=1
continue #we have a simple type for the array
i += 1
if in_sign[i] != '{' and in_sign[i] != '(': # FIXME: must manage tuples out of arrays
i += 1
continue # we have a simple type for the array
opening_car = in_sign[i]
assert(opening_car in ['{','('])
assert(opening_car in ['{', '('])
closing_car = '}' if opening_car == '{' else ')'
opening_count = 1
while (True): #we have a dict or a list of tuples
i+=1
if i>=len(in_sign):
while (True): # we have a dict or a list of tuples
i += 1
if i >= len(in_sign):
raise ParseError("missing }")
if in_sign[i] == opening_car:
opening_count+=1
opening_count += 1
if in_sign[i] == closing_car:
opening_count-=1
opening_count -= 1
if opening_count == 0:
break
i+=1
i += 1
return attr
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False):
@ -460,30 +463,29 @@ class DbusObject(dbus.service.Object):
del(_arguments[0])
#first arguments are for the _callback method
arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback','errback=errback']) if async else _arguments))
arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback', 'errback=errback']) if async else _arguments))
if async:
_arguments.extend(['callback','errback'])
_arguments.extend(['callback', 'errback'])
_defaults.extend([None, None])
#now we create a second list with default values
for i in range(1, len(_defaults)+1):
for i in range(1, len(_defaults) + 1):
_arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i]))
arguments_defaults = ', '.join(_arguments)
arguments_defaults = ', '.join(_arguments)
code = compile ('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' %
{'name':name, 'arguments_defaults':arguments_defaults, 'arguments_callback':arguments_callback}, '<DBus bridge>','exec')
exec (code) #FIXME: to the same thing in a cleaner way, without compile/exec
code = compile('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' %
{'name': name, 'arguments_defaults': arguments_defaults, 'arguments_callback': arguments_callback}, '<DBus bridge>', 'exec')
exec (code) # FIXME: to the same thing in a cleaner way, without compile/exec
method = locals()[name]
async_callbacks = ('callback', 'errback') if async else None
setattr(DbusObject, name, dbus.service.method(
const_INT_PREFIX+int_suffix, in_signature=in_sign, out_signature=out_sign,
const_INT_PREFIX + int_suffix, in_signature=in_sign, out_signature=out_sign,
async_callbacks=async_callbacks)(method))
function = getattr(self, name)
func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface]
func_table[function.__name__] = function #Needed for introspection
func_table[function.__name__] = function # Needed for introspection
def addSignal(self, name, int_suffix, signature, doc={}):
"""Dynamically add a signal to Dbus Bridge"""
@ -491,20 +493,21 @@ class DbusObject(dbus.service.Object):
#TODO: use doc parameter to name attributes
#code = compile ('def '+name+' (self,'+attributes+'): debug ("'+name+' signal")', '<DBus bridge>','exec') #XXX: the debug is too annoying with xmllog
code = compile ('def '+name+' (self,'+attributes+'): pass', '<DBus bridge>','exec')
code = compile('def ' + name + ' (self,' + attributes + '): pass', '<DBus bridge>', 'exec')
exec (code)
signal = locals()[name]
setattr(DbusObject, name, dbus.service.signal(
const_INT_PREFIX+int_suffix, signature=signature)(signal))
const_INT_PREFIX + int_suffix, signature=signature)(signal))
function = getattr(self, name)
func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface]
func_table[function.__name__] = function #Needed for introspection
func_table[function.__name__] = function # Needed for introspection
class DBusBridge(Bridge):
def __init__(self):
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
Bridge.__init__(self)
info ("Init DBus...")
info("Init DBus...")
self.session_bus = dbus.SessionBus()
self.dbus_name = dbus.service.BusName(const_INT_PREFIX, self.session_bus)
self.dbus_bridge = DbusObject(self.session_bus, const_OBJ_PATH)
@ -551,7 +554,6 @@ class DBusBridge(Bridge):
def subscribe(self, sub_type, entity_jid, profile):
self.dbus_bridge.subscribe(sub_type, entity_jid, profile)
def register(self, name, callback):
debug("registering DBus bridge method [%s]", name)
self.dbus_bridge.register(name, callback)
@ -565,4 +567,4 @@ class DBusBridge(Bridge):
def addSignal(self, name, int_suffix, signature, doc={}):
self.dbus_bridge.addSignal(name, int_suffix, signature, doc)
setattr(DBusBridge, name, getattr(self.dbus_bridge, name))
setattr(DBusBridge, name, getattr(self.dbus_bridge, name))