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/
This commit is contained in:
Goffi 2018-04-02 19:44:50 +02:00
commit 80ef13612b
19 changed files with 42 additions and 269 deletions

View file

@ -0,0 +1,91 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.bridge.bridge_constructor import base_constructor
from xml.dom import minidom
import sys
class DbusXmlConstructor(base_constructor.Constructor):
"""Constructor for DBus XML syntaxt (used by Qt frontend)"""
def __init__(self, bridge_template, options):
base_constructor.Constructor.__init__(self, bridge_template, options)
self.template = "dbus_xml_template.xml"
self.core_dest = "org.goffi.sat.xml"
self.default_annotation = {'a{ss}': 'StringDict',
'a(sa{ss}as)': 'QList<Contact>',
'a{i(ss)}': 'HistoryT',
'a(sss)': 'QList<MenuT>',
'a{sa{s(sia{ss})}}': 'PresenceStatusT',
}
def generateCoreSide(self):
try:
doc = minidom.parse(self.getTemplatePath(self.template))
interface_elt = doc.getElementsByTagName('interface')[0]
except IOError:
print ("Can't access template")
sys.exit(1)
except IndexError:
print ("Template error")
sys.exit(1)
sections = self.bridge_template.sections()
sections.sort()
for section in sections:
function = self.getValues(section)
print ("Adding %s %s" % (section, function["type"]))
new_elt = doc.createElement('method' if function["type"] == 'method' else 'signal')
new_elt.setAttribute('name', section)
idx = 0
args_doc = self.getArgumentsDoc(section)
for arg in self.argumentsParser(function['sig_in'] or ''):
arg_elt = doc.createElement('arg')
arg_elt.setAttribute('name', args_doc[idx][0] if idx in args_doc else "arg_%i" % idx)
arg_elt.setAttribute('type', arg)
_direction = 'in' if function["type"] == 'method' else 'out'
arg_elt.setAttribute('direction', _direction)
new_elt.appendChild(arg_elt)
if "annotation" in self.args.flags:
if arg in self.default_annotation:
annot_elt = doc.createElement("annotation")
annot_elt.setAttribute('name', "com.trolltech.QtDBus.QtTypeName.In%d" % idx)
annot_elt.setAttribute('value', self.default_annotation[arg])
new_elt.appendChild(annot_elt)
idx += 1
if function['sig_out']:
arg_elt = doc.createElement('arg')
arg_elt.setAttribute('type', function['sig_out'])
arg_elt.setAttribute('direction', 'out')
new_elt.appendChild(arg_elt)
if "annotation" in self.args.flags:
if function['sig_out'] in self.default_annotation:
annot_elt = doc.createElement("annotation")
annot_elt.setAttribute('name', "com.trolltech.QtDBus.QtTypeName.Out0")
annot_elt.setAttribute('value', self.default_annotation[function['sig_out']])
new_elt.appendChild(annot_elt)
interface_elt.appendChild(new_elt)
#now we write to final file
self.finalWrite(self.core_dest, [doc.toprettyxml()])

View file

@ -0,0 +1,4 @@
<node>
<interface name="org.goffi.SAT.core">
</interface>
</node>

View file

@ -0,0 +1,97 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.bridge.bridge_constructor import base_constructor
class DbusConstructor(base_constructor.Constructor):
NAME = "dbus"
CORE_TEMPLATE = "dbus_core_template.py"
CORE_DEST = "dbus_bridge.py"
CORE_FORMATS = {
'signals': """\
@dbus.service.signal(const_INT_PREFIX+const_{category}_SUFFIX,
signature='{sig_in}')
def {name}(self, {args}):
{body}\n""",
'methods': """\
@dbus.service.method(const_INT_PREFIX+const_{category}_SUFFIX,
in_signature='{sig_in}', out_signature='{sig_out}',
async_callbacks={async_callbacks})
def {name}(self, {args}{async_comma}{async_args_def}):
{debug}return self._callback("{name}", {args_result}{async_comma}{async_args_call})\n""",
'signal_direct_calls': """\
def {name}(self, {args}):
self.dbus_bridge.{name}({args})\n""",
}
FRONTEND_TEMPLATE = "dbus_frontend_template.py"
FRONTEND_DEST = CORE_DEST
FRONTEND_FORMATS = {
'methods': """\
def {name}(self, {args}{async_comma}{async_args}):
{error_handler}{blocking_call}{debug}return {result}\n""",
}
def core_completion_signal(self, completion, function, default, arg_doc, async_):
completion['category'] = completion['category'].upper()
completion['body'] = "pass" if not self.args.debug else 'log.debug ("{}")'.format(completion['name'])
def core_completion_method(self, completion, function, default, arg_doc, async_):
completion.update({
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
'args_result': self.getArguments(function['sig_in'], name=arg_doc, unicode_protect=self.args.unicode),
'async_comma': ', ' if async_ and function['sig_in'] else '',
'async_args_def': 'callback=None, errback=None' if async_ else '',
'async_args_call': 'callback=callback, errback=errback' if async_ else '',
'async_callbacks': "('callback', 'errback')" if async_ else "None",
'category': completion['category'].upper(),
})
def frontend_completion_method(self, completion, function, default, arg_doc, async_):
completion.update({
# XXX: we can manage blocking call in the same way as async one: if callback is None the call will be blocking
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
'args_result': self.getArguments(function['sig_in'], name=arg_doc),
'async_args': 'callback=None, errback=None',
'async_comma': ', ' if function['sig_in'] else '',
'error_handler': """if callback is None:
error_handler = None
else:
if errback is None:
errback = log.error
error_handler = lambda err:errback(dbus_to_bridge_exception(err))
""",
})
if async_:
completion['blocking_call'] = ''
completion['async_args_result'] = 'timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler'
else:
# XXX: To have a blocking call, we must have not reply_handler, so we test if callback exists, and add reply_handler only in this case
completion['blocking_call'] = """kwargs={}
if callback is not None:
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
"""
completion['async_args_result'] = '**kwargs'
result = "self.db_%(category)s_iface.%(name)s(%(args_result)s%(async_comma)s%(async_args_result)s)" % completion
completion['result'] = ("unicode(%s)" if self.args.unicode and function['sig_out'] == 's' else "%s") % result

View file

@ -0,0 +1,246 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SAT: a jabber client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.core.i18n import _
import dbus
import dbus.service
import dbus.mainloop.glib
import inspect
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.internet.defer import Deferred
from sat.core.exceptions import BridgeInitError
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):
"""
@param twisted_error (Failure): instance of twisted Failure
@return: DBusException
"""
super(GenericException, self).__init__()
try:
# twisted_error.value is a class
class_ = twisted_error.value().__class__
except TypeError:
# twisted_error.value is an instance
class_ = twisted_error.value.__class__
message = twisted_error.getErrorMessage()
try:
self.args = (message, twisted_error.value.condition)
except AttributeError:
self.args = (message,)
self._dbus_error_name = '.'.join([const_ERROR_PREFIX, class_.__module__, class_.__name__])
class DbusObject(dbus.service.Object):
def __init__(self, bus, path):
dbus.service.Object.__init__(self, bus, path)
log.debug("Init DbusObject...")
self.cb = {}
def register_method(self, name, cb):
self.cb[name] = cb
def _callback(self, name, *args, **kwargs):
"""call the callback if it exists, raise an exception else
if the callback return a deferred, use async methods"""
if not name in self.cb:
raise MethodNotRegistered
if "callback" in kwargs:
#we must have errback too
if not "errback" in kwargs:
log.error("errback is missing in method call [%s]" % name)
raise InternalError
callback = kwargs.pop("callback")
errback = kwargs.pop("errback")
async = True
else:
async = False
result = self.cb[name](*args, **kwargs)
if async:
if not isinstance(result, Deferred):
log.error("Asynchronous method [%s] does not return a Deferred." % name)
raise AsyncNotDeferred
result.addCallback(lambda result: callback() if result is None else callback(result))
result.addErrback(lambda err: errback(GenericException(err)))
else:
if isinstance(result, Deferred):
log.error("Synchronous method [%s] return a Deferred." % name)
raise DeferredNotAsync
return result
### signals ###
@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
# already exist for plugins), probably missing some initialisation, need
# further investigations
pass
##SIGNALS_PART##
### methods ###
##METHODS_PART##
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']:
raise ParseError("Unmanaged attribute type [%c]" % in_sign[i])
attr.append("arg_%i" % idx)
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
opening_car = in_sign[i]
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):
raise ParseError("missing }")
if in_sign[i] == opening_car:
opening_count += 1
if in_sign[i] == closing_car:
opening_count -= 1
if opening_count == 0:
break
i += 1
return attr
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False):
"""Dynamically add a method to Dbus Bridge"""
inspect_args = inspect.getargspec(method)
_arguments = inspect_args.args
_defaults = list(inspect_args.defaults or [])
if inspect.ismethod(method):
#if we have a method, we don't want the first argument (usually 'self')
del(_arguments[0])
#first arguments are for the _callback method
arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback', 'errback=errback']) if async else _arguments))
if async:
_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):
_arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i]))
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
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,
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
def addSignal(self, name, int_suffix, signature, doc={}):
"""Dynamically add a signal to Dbus Bridge"""
attributes = ', '.join(self.__attributes(signature))
#TODO: use doc parameter to name attributes
#code = compile ('def '+name+' (self,'+attributes+'): log.debug ("'+name+' signal")', '<DBus bridge>','exec') #XXX: the log.debug is too annoying with xmllog
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))
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
class Bridge(object):
def __init__(self):
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
log.info("Init DBus...")
try:
self.session_bus = dbus.SessionBus()
except dbus.DBusException as e:
if e._dbus_error_name == 'org.freedesktop.DBus.Error.NotSupported':
log.error(_(u"D-Bus is not launched, please see README to see instructions on how to launch it"))
raise BridgeInitError
self.dbus_name = dbus.service.BusName(const_INT_PREFIX, self.session_bus)
self.dbus_bridge = DbusObject(self.session_bus, const_OBJ_PATH)
##SIGNAL_DIRECT_CALLS_PART##
def register_method(self, name, callback):
log.debug("registering DBus bridge method [%s]" % name)
self.dbus_bridge.register_method(name, callback)
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}):
"""Dynamically add a method to Dbus Bridge"""
#FIXME: doc parameter is kept only temporary, the time to remove it from calls
log.debug("Adding method [%s] to DBus bridge" % name)
self.dbus_bridge.addMethod(name, int_suffix, in_sign, out_sign, method, async)
self.register_method(name, method)
def addSignal(self, name, int_suffix, signature, doc={}):
self.dbus_bridge.addSignal(name, int_suffix, signature, doc)
setattr(Bridge, name, getattr(self.dbus_bridge, name))

View file

@ -0,0 +1,139 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SAT communication bridge
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.core.i18n import _
from bridge_frontend import BridgeException
import dbus
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core.exceptions import BridgeExceptionNoService, BridgeInitError
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
import ast
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"
const_TIMEOUT = 120
def dbus_to_bridge_exception(dbus_e):
"""Convert a DBusException to a BridgeException.
@param dbus_e (DBusException)
@return: BridgeException
"""
full_name = dbus_e.get_dbus_name()
if full_name.startswith(const_ERROR_PREFIX):
name = dbus_e.get_dbus_name()[len(const_ERROR_PREFIX) + 1:]
else:
name = full_name
# XXX: dbus_e.args doesn't contain the original DBusException args, but we
# receive its serialized form in dbus_e.args[0]. From that we can rebuild
# the original arguments list thanks to ast.literal_eval (secure eval).
message = dbus_e.get_dbus_message() # similar to dbus_e.args[0]
try:
message, condition = ast.literal_eval(message)
except (SyntaxError, ValueError, TypeError):
condition = ''
return BridgeException(name, message, condition)
class Bridge(object):
def bridgeConnect(self, callback, errback):
try:
self.sessions_bus = dbus.SessionBus()
self.db_object = self.sessions_bus.get_object(const_INT_PREFIX,
const_OBJ_PATH)
self.db_core_iface = dbus.Interface(self.db_object,
dbus_interface=const_INT_PREFIX + const_CORE_SUFFIX)
self.db_plugin_iface = dbus.Interface(self.db_object,
dbus_interface=const_INT_PREFIX + const_PLUGIN_SUFFIX)
except dbus.exceptions.DBusException, e:
if e._dbus_error_name in ('org.freedesktop.DBus.Error.ServiceUnknown',
'org.freedesktop.DBus.Error.Spawn.ExecFailed'):
errback(BridgeExceptionNoService())
elif e._dbus_error_name == 'org.freedesktop.DBus.Error.NotSupported':
log.error(_(u"D-Bus is not launched, please see README to see instructions on how to launch it"))
errback(BridgeInitError)
else:
errback(e)
callback()
#props = self.db_core_iface.getProperties()
def register_signal(self, functionName, handler, iface="core"):
if iface == "core":
self.db_core_iface.connect_to_signal(functionName, handler)
elif iface == "plugin":
self.db_plugin_iface.connect_to_signal(functionName, handler)
else:
log.error(_('Unknown interface'))
def __getattribute__(self, name):
""" usual __getattribute__ if the method exists, else try to find a plugin method """
try:
return object.__getattribute__(self, name)
except AttributeError:
# The attribute is not found, we try the plugin proxy to find the requested method
def getPluginMethod(*args, **kwargs):
# We first check if we have an async call. We detect this in two ways:
# - if we have the 'callback' and 'errback' keyword arguments
# - or if the last two arguments are callable
async = False
args = list(args)
if kwargs:
if 'callback' in kwargs:
async = True
_callback = kwargs.pop('callback')
_errback = kwargs.pop('errback', lambda failure: log.error(unicode(failure)))
try:
args.append(kwargs.pop('profile'))
except KeyError:
try:
args.append(kwargs.pop('profile_key'))
except KeyError:
pass
# at this point, kwargs should be empty
if kwargs:
log.warnings(u"unexpected keyword arguments, they will be ignored: {}".format(kwargs))
elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]):
async = True
_errback = args.pop()
_callback = args.pop()
method = getattr(self.db_plugin_iface, name)
if async:
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = _callback
kwargs['error_handler'] = lambda err: _errback(dbus_to_bridge_exception(err))
return method(*args, **kwargs)
return getPluginMethod
##METHODS_PART##

View file

@ -0,0 +1,85 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.bridge.bridge_constructor import base_constructor
# from textwraps import dedent
class EmbeddedConstructor(base_constructor.Constructor):
NAME = "embedded"
CORE_TEMPLATE = "embedded_template.py"
CORE_DEST = "embedded.py"
CORE_FORMATS = {
'methods': """\
def {name}(self, {args}{args_comma}callback=None, errback=None):
{ret_routine}
""",
'signals': """\
def {name}(self, {args}):
try:
cb = self._signals_cbs["{category}"]["{name}"]
except KeyError:
log.warning(u"ignoring signal {name}: no callback registered")
else:
cb({args_result})
"""
}
FRONTEND_TEMPLATE = "embedded_frontend_template.py"
FRONTEND_DEST = CORE_DEST
FRONTEND_FORMATS = {}
def core_completion_method(self, completion, function, default, arg_doc, async_):
completion.update({
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
'args_result': self.getArguments(function['sig_in'], name=arg_doc),
'args_comma': ', ' if function['sig_in'] else '',
})
if async_:
completion["cb_or_lambda"] = "callback" if function['sig_out'] else "lambda dummy: callback()"
completion["ret_routine"] = """\
d = self._methods_cbs["{name}"]({args_result})
if callback is not None:
d.addCallback({cb_or_lambda})
if errback is None:
d.addErrback(lambda failure_: log.error(failure_))
else:
d.addErrback(errback)
return d
""".format(**completion)
else:
completion['ret_or_nothing'] = 'ret' if function['sig_out'] else ''
completion["ret_routine"] = """\
try:
ret = self._methods_cbs["{name}"]({args_result})
except Exception as e:
if errback is not None:
errback(e)
else:
raise e
else:
if callback is None:
return ret
else:
callback({ret_or_nothing})""".format(**completion)
def core_completion_signal(self, completion, function, default, arg_doc, async_):
completion.update({
'args_result': self.getArguments(function['sig_in'], name=arg_doc),
})

View file

@ -0,0 +1,20 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.bridge.embedded import Bridge

View file

@ -0,0 +1,108 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
class _Bridge(object):
def __init__(self):
log.debug(u"Init embedded bridge...")
self._methods_cbs = {}
self._signals_cbs = {
"core": {},
"plugin": {}
}
def bridgeConnect(self, callback, errback):
callback()
def register_method(self, name, callback):
log.debug(u"registering embedded bridge method [{}]".format(name))
if name in self._methods_cbs:
raise exceptions.ConflictError(u"method {} is already regitered".format(name))
self._methods_cbs[name] = callback
def register_signal(self, functionName, handler, iface="core"):
iface_dict = self._signals_cbs[iface]
if functionName in iface_dict:
raise exceptions.ConflictError(u"signal {name} is already regitered for interface {iface}".format(name=functionName, iface=iface))
iface_dict[functionName] = handler
def call_method(self, name, out_sign, async_, args, kwargs):
callback = kwargs.pop("callback", None)
errback = kwargs.pop("errback", None)
if async_:
d = self._methods_cbs[name](*args, **kwargs)
if callback is not None:
d.addCallback(callback if out_sign else lambda dummy: callback())
if errback is None:
d.addErrback(lambda failure_: log.error(failure_))
else:
d.addErrback(errback)
return d
else:
try:
ret = self._methods_cbs[name](*args, **kwargs)
except Exception as e:
if errback is not None:
errback(e)
else:
raise e
else:
if callback is None:
return ret
else:
if out_sign:
callback(ret)
else:
callback()
def send_signal(self, name, args, kwargs):
try:
cb = self._signals_cbs["plugin"][name]
except KeyError:
log.debug(u"ignoring signal {}: no callback registered".format(name))
else:
cb(*args, **kwargs)
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}):
#FIXME: doc parameter is kept only temporary, the time to remove it from calls
log.debug("Adding method [{}] to embedded bridge".format(name))
self.register_method(name, method)
setattr(self.__class__, name, lambda self_, *args, **kwargs: self.call_method(name, out_sign, async, args, kwargs))
def addSignal(self, name, int_suffix, signature, doc={}):
setattr(self.__class__, name, lambda self_, *args, **kwargs: self.send_signal(name, args, kwargs))
## signals ##
##SIGNALS_PART##
## methods ##
##METHODS_PART##
# we want the same instance for both core and frontend
bridge = None
def Bridge():
global bridge
if bridge is None:
bridge = _Bridge()
return bridge

View file

@ -0,0 +1,153 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.bridge.bridge_constructor import base_constructor
import sys
from datetime import datetime
import re
class MediawikiConstructor(base_constructor.Constructor):
def __init__(self, bridge_template, options):
base_constructor.Constructor.__init__(self, bridge_template, options)
self.core_template = "mediawiki_template.tpl"
self.core_dest = "mediawiki.wiki"
def _addTextDecorations(self, text):
"""Add text decorations like coloration or shortcuts"""
def anchor_link(match):
link = match.group(1)
#we add anchor_link for [method_name] syntax:
if link in self.bridge_template.sections():
return "[[#%s|%s]]" % (link, link)
print ("WARNING: found an anchor link to an unknown method")
return link
return re.sub(r"\[(\w+)\]", anchor_link, text)
def _wikiParameter(self, name, sig_in):
"""Format parameters with the wiki syntax
@param name: name of the function
@param sig_in: signature in
@return: string of the formated parameters"""
arg_doc = self.getArgumentsDoc(name)
arg_default = self.getDefault(name)
args_str = self.getArguments(sig_in)
args = args_str.split(', ') if args_str else [] # ugly but it works :)
wiki = []
for i in range(len(args)):
if i in arg_doc:
name, doc = arg_doc[i]
doc = '\n:'.join(doc.rstrip('\n').split('\n'))
wiki.append("; %s: %s" % (name, self._addTextDecorations(doc)))
else:
wiki.append("; arg_%d: " % i)
if i in arg_default:
wiki.append(":''DEFAULT: %s''" % arg_default[i])
return "\n".join(wiki)
def _wikiReturn(self, name):
"""Format return doc with the wiki syntax
@param name: name of the function
"""
arg_doc = self.getArgumentsDoc(name)
wiki = []
if 'return' in arg_doc:
wiki.append('\n|-\n! scope=row | return value\n|')
wiki.append('<br />\n'.join(self._addTextDecorations(arg_doc['return']).rstrip('\n').split('\n')))
return "\n".join(wiki)
def generateCoreSide(self):
signals_part = []
methods_part = []
sections = self.bridge_template.sections()
sections.sort()
for section in sections:
function = self.getValues(section)
print ("Adding %s %s" % (section, function["type"]))
async_msg = """<br />'''This method is asynchronous'''"""
deprecated_msg = """<br />'''<font color="#FF0000">/!\ WARNING /!\ : This method is deprecated, please don't use it !</font>'''"""
signature_signal = \
"""\
! scope=row | signature
| %s
|-\
""" % function['sig_in']
signature_method = \
"""\
! scope=row | signature in
| %s
|-
! scope=row | signature out
| %s
|-\
""" % (function['sig_in'], function['sig_out'])
completion = {
'signature': signature_signal if function['type'] == "signal" else signature_method,
'sig_out': function['sig_out'] or '',
'category': function['category'],
'name': section,
'doc': self.getDoc(section) or "FIXME: No description available",
'async': async_msg if "async" in self.getFlags(section) else "",
'deprecated': deprecated_msg if "deprecated" in self.getFlags(section) else "",
'parameters': self._wikiParameter(section, function['sig_in']),
'return': self._wikiReturn(section) if function['type'] == 'method' else ''}
dest = signals_part if function['type'] == "signal" else methods_part
dest.append("""\
== %(name)s ==
''%(doc)s''
%(deprecated)s
%(async)s
{| class="wikitable" style="text-align:left; width:80%%;"
! scope=row | category
| %(category)s
|-
%(signature)s
! scope=row | parameters
|
%(parameters)s%(return)s
|}
""" % completion)
#at this point, signals_part, and methods_part should be filled,
#we just have to place them in the right part of the template
core_bridge = []
template_path = self.getTemplatePath(self.core_template)
try:
with open(template_path) as core_template:
for line in core_template:
if line.startswith('##SIGNALS_PART##'):
core_bridge.extend(signals_part)
elif line.startswith('##METHODS_PART##'):
core_bridge.extend(methods_part)
elif line.startswith('##TIMESTAMP##'):
core_bridge.append('Generated on %s' % datetime.now())
else:
core_bridge.append(line.replace('\n', ''))
except IOError:
print ("Can't open template file [%s]" % template_path)
sys.exit(1)
#now we write to final file
self.finalWrite(self.core_dest, core_bridge)

View file

@ -0,0 +1,11 @@
[[Catégorie:Salut à Toi]]
[[Catégorie:documentation développeur]]
= Overview =
This is an autogenerated doc for SàT bridge's API
= Signals =
##SIGNALS_PART##
= Methods =
##METHODS_PART##
----
##TIMESTAMP##

View file

@ -0,0 +1,56 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SàT: a XMPP client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.bridge.bridge_constructor import base_constructor
class pbConstructor(base_constructor.Constructor):
NAME = "pb"
CORE_TEMPLATE = "pb_core_template.py"
CORE_DEST = "pb.py"
CORE_FORMATS = {
'signals': """\
def {name}(self, {args}):
{debug}self.sendSignal("{name}", {args_no_def})\n""",
}
FRONTEND_TEMPLATE = "pb_frontend_template.py"
FRONTEND_DEST = CORE_DEST
FRONTEND_FORMATS = {
'methods': """\
def {name}(self{args_comma}{args}, callback=None, errback=None):
{debug}d = self.root.callRemote("{name}"{args_comma}{args_no_def})
if callback is not None:
d.addCallback({callback})
if errback is None:
errback = self._generic_errback
d.addErrback(errback)\n""",
}
def core_completion_signal(self, completion, function, default, arg_doc, async_):
completion['args_no_def'] = self.getArguments(function['sig_in'], name=arg_doc)
completion['debug'] = "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' ')
def frontend_completion_method(self, completion, function, default, arg_doc, async_):
completion.update({
'args_comma': ', ' if function['sig_in'] else '',
'args_no_def': self.getArguments(function['sig_in'], name=arg_doc),
'callback': 'callback' if function['sig_out'] else 'lambda dummy: callback()',
'debug': "" if not self.args.debug else 'log.debug ("%s")\n%s' % (completion['name'], 8 * ' '),
})

View file

@ -0,0 +1,101 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SAT: a jabber client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.core.log import getLogger
log = getLogger(__name__)
from twisted.spread import jelly, pb
from twisted.internet import reactor
## jelly hack
# we monkey patch jelly to handle namedtuple
ori_jelly = jelly._Jellier.jelly
def fixed_jelly(self, obj):
"""this method fix handling of namedtuple"""
if isinstance(obj, tuple) and not obj is tuple:
obj = tuple(obj)
return ori_jelly(self, obj)
jelly._Jellier.jelly = fixed_jelly
class PBRoot(pb.Root):
def __init__(self):
self.signals_handlers = []
def remote_initBridge(self, signals_handler):
self.signals_handlers.append(signals_handler)
log.info(u"registered signal handler")
def sendSignalEb(self, failure, signal_name):
log.error(u"Error while sending signal {name}: {msg}".format(
name = signal_name,
msg = failure,
))
def sendSignal(self, name, args, kwargs):
to_remove = []
for handler in self.signals_handlers:
try:
d = handler.callRemote(name, *args, **kwargs)
except pb.DeadReferenceError:
to_remove.append(handler)
else:
d.addErrback(self.sendSignalEb, name)
if to_remove:
for handler in to_remove:
log.debug(u"Removing signal handler for dead frontend")
self.signals_handlers.remove(handler)
##METHODS_PART##
class Bridge(object):
def __init__(self):
log.info("Init Perspective Broker...")
self.root = PBRoot()
reactor.listenTCP(8789, pb.PBServerFactory(self.root))
def sendSignal(self, name, *args, **kwargs):
self.root.sendSignal(name, args, kwargs)
def remote_initBridge(self, signals_handler):
self.signals_handlers.append(signals_handler)
log.info(u"registered signal handler")
def register_method(self, name, callback):
log.debug("registering PB bridge method [%s]" % name)
setattr(self.root, "remote_"+name, callback)
# self.root.register_method(name, callback)
def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False, doc={}):
"""Dynamically add a method to PB Bridge"""
#FIXME: doc parameter is kept only temporary, the time to remove it from calls
log.debug("Adding method {name} to PB bridge".format(name=name))
self.register_method(name, method)
def addSignal(self, name, int_suffix, signature, doc={}):
log.debug("Adding signal {name} to PB bridge".format(name=name))
setattr(self, name, lambda *args, **kwargs: self.sendSignal(name, *args, **kwargs))
##SIGNALS_PART##

View file

@ -0,0 +1,127 @@
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
# SAT communication bridge
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# 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 sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
from twisted.spread import pb
from twisted.internet import reactor
class SignalsHandler(pb.Referenceable):
def __getattr__(self, name):
if name.startswith("remote_"):
log.debug(u"calling an unregistered signal: {name}".format(
name = name[7:]))
return lambda *args, **kwargs: None
else:
raise AttributeError(name)
def register_signal(self, name, handler, iface="core"):
log.debug("registering signal {name}".format(name=name))
method_name = "remote_" + name
try:
self.__getattribute__(self, method_name)
except AttributeError:
pass
else:
raise exceptions.InternalError(u"{name} signal handler has been registered twice".format(
name = method_name))
setattr(self, method_name, handler)
class Bridge(object):
def __init__(self):
self.signals_handler = SignalsHandler()
def __getattr__(self, name):
return lambda *args, **kwargs: self.call(name, args, kwargs)
def remoteCallback(self, result, callback):
"""call callback with argument or None
if result is not None not argument is used,
else result is used as argument
@param result: remote call result
@param callback(callable): method to call on result
"""
if result is None:
callback()
else:
callback(result)
def call(self, name, args, kwargs):
"""call a remote method
@param name(str): name of the bridge method
@param args(list): arguments
may contain callback and errback as last 2 items
@param kwargs(dict): keyword arguments
may contain callback and errback
"""
callback = errback = None
if kwargs:
try:
callback = kwargs.pop('callback')
except KeyError:
pass
try:
errback = kwargs.pop('errback')
except KeyError:
pass
elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]):
errback = args.pop()
callback = args.pop()
d = self.root.callRemote(name, *args, **kwargs)
if callback is not None:
d.addCallback(self.remoteCallback, callback)
if errback is not None:
d.addErrback(errback)
def _initBridgeEb(self, failure):
log.error(u"Can't init bridge: {msg}".format(msg=failure))
def _set_root(self, root):
"""set remote root object
bridge will then be initialised
"""
self.root = root
d = root.callRemote("initBridge", self.signals_handler)
d.addErrback(self._initBridgeEb)
return d
def _generic_errback(self, failure):
log.error(u"bridge failure: {}".format(failure))
def bridgeConnect(self, callback, errback):
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8789, factory)
d = factory.getRootObject()
d.addCallback(self._set_root)
d.addCallback(lambda dummy: callback())
d.addErrback(errback)
def register_signal(self, functionName, handler, iface="core"):
self.signals_handler.register_signal(functionName, handler, iface)
##METHODS_PART##