Bridge constructor:
- moved constructor files in src/bridge/bridge_constructor - frontend side can now be generated
This commit is contained in:
parent
793e6d6c3d
commit
3b2fd57724
4 changed files with 500 additions and 310 deletions
342
src/bridge/bridge_constructor/bridge_contructor.py
Executable file
342
src/bridge/bridge_constructor/bridge_contructor.py
Executable file
|
|
@ -0,0 +1,342 @@
|
|||
#!/usr/bin/python
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
SAT: a jabber client
|
||||
Copyright (C) 2009, 2010, 2011 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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
|
||||
#consts
|
||||
NAME = u"bridge_constructor"
|
||||
VERSION="0.1.0"
|
||||
ABOUT = NAME+u""" v%s (c) Jérôme Poisson (aka Goffi) 2011
|
||||
|
||||
---
|
||||
"""+NAME+u""" Copyright (C) 2011 Jérôme Poisson (aka Goffi)
|
||||
This program comes with ABSOLUTELY NO WARRANTY;
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions.
|
||||
---
|
||||
|
||||
This script construct a SàT bridge using the given protocol
|
||||
"""
|
||||
MANAGED_PROTOCOLES=['dbus']
|
||||
DEFAULT_PROTOCOLE='dbus'
|
||||
|
||||
import sys
|
||||
import os
|
||||
from os import path
|
||||
from optparse import OptionParser
|
||||
from ConfigParser import SafeConfigParser as Parser
|
||||
from ConfigParser import NoOptionError
|
||||
import re
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
#Used when the signature parsing is going wrong (invalid signature ?)
|
||||
pass
|
||||
|
||||
class Constructor:
|
||||
|
||||
def __init__(self, bridge_template, options):
|
||||
self.bridge_template = bridge_template
|
||||
self.options = options
|
||||
|
||||
def getValues(self, name):
|
||||
"""Return values of a function in a dict
|
||||
@param name: Name of the function to get
|
||||
@return: dict, each key has the config value or None if the value is not set"""
|
||||
function={}
|
||||
for option in ['type','category','sig_in','sig_out','doc']:
|
||||
try:
|
||||
value = self.bridge_template.get(name, option)
|
||||
except NoOptionError:
|
||||
value = None
|
||||
function[option] = value
|
||||
return function
|
||||
|
||||
def getDefault(self, name):
|
||||
"""Return default values of a function in a dict
|
||||
@param name: Name of the function to get
|
||||
@return: dict, each key is the integer param number (no key if no default value)"""
|
||||
default_dict={}
|
||||
def_re = re.compile(r"param_(\d+)_default")
|
||||
|
||||
for option in self.bridge_template.options(name):
|
||||
if option == 'doc_return':
|
||||
default_dict['return'] = self.bridge_template.get(name, option)
|
||||
continue
|
||||
match = def_re.match(option)
|
||||
if match:
|
||||
try:
|
||||
idx = int(match.group(1))
|
||||
except ValueError:
|
||||
raise ParseError("Invalid value [%s] for parameter number" % match.group(1))
|
||||
default_dict[idx] = self.bridge_template.get(name, option)
|
||||
|
||||
return default_dict
|
||||
|
||||
def getArgumentsDoc(self, name):
|
||||
"""Return documentation of arguments
|
||||
@param name: Name of the function to get
|
||||
@return: dict, each key is the integer param number (no key if no argument doc), value is a tuple (name, doc)"""
|
||||
doc_dict={}
|
||||
option_re = re.compile(r"doc_param_(\d+)")
|
||||
value_re = re.compile(r"^(\w+): (.*)$", re.MULTILINE | re.DOTALL)
|
||||
for option in self.bridge_template.options(name):
|
||||
match = option_re.match(option)
|
||||
if match:
|
||||
try:
|
||||
idx = int(match.group(1))
|
||||
except ValueError:
|
||||
raise ParseError("Invalid value [%s] for parameter number" % match.group(1))
|
||||
value_match = value_re.match(self.bridge_template.get(name, option))
|
||||
if not value_match:
|
||||
raise ParseError("Invalid value for parameter doc [%i]" % idx)
|
||||
doc_dict[idx]=(value_match.group(1),value_match.group(2))
|
||||
return doc_dict
|
||||
|
||||
def getArguments(self, signature, name=None, default=None, unicode_protect=False):
|
||||
"""Return arguments to user given a signature
|
||||
@param signature: signature in the short form (using s,a,i,b etc)
|
||||
@param name: dictionary of arguments name like given by getArguments
|
||||
@param default: dictionary of default values, like given by getDefault
|
||||
@param unicode_protect: activate unicode protection on strings (return strings as unicode(str))
|
||||
@return: list of arguments that correspond to a signature (e.g.: "sss" return "arg1, arg2, arg3")"""
|
||||
i=0
|
||||
idx=0
|
||||
attr_string=[]
|
||||
while i<len(signature):
|
||||
if signature[i] not in ['b','y','n','i','x','q','u','t','d','s','a']:
|
||||
raise ParseError("Unmanaged attribute type [%c]" % signature[i])
|
||||
|
||||
attr_string.append(("unicode(%(name)s)%(default)s" if (unicode_protect and signature[i]=='s') else "%(name)s%(default)s") % {
|
||||
'name':name[idx][0] if (name and name.has_key(idx)) else "arg_%i" % idx,
|
||||
'default':"="+default[idx] if (default and default.has_key(idx)) else ''
|
||||
}) #give arg_1, arg2, etc or name1, name2=default, etc. \
|
||||
#give unicode(arg_1), unicode(arg_2), etc. if unicode_protect is set and arg is a string
|
||||
idx+=1
|
||||
|
||||
if signature[i] == 'a':
|
||||
i+=1
|
||||
if signature[i]!='{' and signature[i]!='(': #FIXME: must manage tuples out of arrays
|
||||
i+=1
|
||||
continue #we have a simple type for the array
|
||||
opening_car = signature[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(signature):
|
||||
raise ParseError("missing }")
|
||||
if signature[i] == opening_car:
|
||||
opening_count+=1
|
||||
if signature[i] == closing_car:
|
||||
opening_count-=1
|
||||
if opening_count == 0:
|
||||
break
|
||||
i+=1
|
||||
return ", ".join(attr_string)
|
||||
|
||||
def generateCoreSide(self):
|
||||
"""create the constructor in SàT core side (backend)"""
|
||||
raise NotImplementedError
|
||||
|
||||
class DbusConstructor(Constructor):
|
||||
|
||||
def __init__(self, bridge_template, options):
|
||||
Constructor.__init__(self, bridge_template, options)
|
||||
self.core_template="dbus_core_template.py"
|
||||
self.frontend_template="dbus_frontend_template.py"
|
||||
self.frontend_dest = self.core_dest="DBus.py"
|
||||
|
||||
def generateCoreSide(self):
|
||||
signals_part = []
|
||||
methods_part = []
|
||||
direct_calls = []
|
||||
sections = self.bridge_template.sections()
|
||||
sections.sort()
|
||||
for section in sections:
|
||||
function = self.getValues(section)
|
||||
print ("Adding %s %s" % (section, function["type"]))
|
||||
default = self.getDefault(section)
|
||||
arg_doc = self.getArgumentsDoc(section)
|
||||
completion = {
|
||||
'sig_in':function['sig_in'] or '',
|
||||
'sig_out':function['sig_out'] or '',
|
||||
'category':'REQ' if function['category'] == 'request' else 'COMM',
|
||||
'name':section,
|
||||
'args':self.getArguments(function['sig_in'], name=arg_doc, default=default )
|
||||
}
|
||||
|
||||
if function["type"] == "signal":
|
||||
completion['body'] = "pass" if not self.options.debug else 'debug ("%s")' % section
|
||||
signals_part.append("""\
|
||||
@dbus.service.signal(const_INT_PREFIX+const_%(category)s_SUFFIX,
|
||||
signature='%(sig_in)s')
|
||||
def %(name)s(self, %(args)s):
|
||||
%(body)s
|
||||
""" % completion)
|
||||
direct_calls.append("""\
|
||||
def %(name)s(self, %(args)s):
|
||||
self.dbus_bridge.%(name)s(%(args)s)
|
||||
""" % completion)
|
||||
|
||||
elif function["type"] == "method":
|
||||
completion['debug'] = "" if not self.options.debug else 'debug ("%s")\n%s' % (section,8*' ')
|
||||
completion['args_result'] = self.getArguments(function['sig_in'], name=arg_doc, unicode_protect=self.options.unicode)
|
||||
methods_part.append("""\
|
||||
@dbus.service.method(const_INT_PREFIX+const_%(category)s_SUFFIX,
|
||||
in_signature='%(sig_in)s', out_signature='%(sig_out)s')
|
||||
def %(name)s(self, %(args)s):
|
||||
%(debug)sreturn self.cb["%(name)s"](%(args_result)s)
|
||||
""" % completion)
|
||||
|
||||
#at this point, signals_part, methods_part and direct_calls should be filled,
|
||||
#we just have to place them in the right part of the template
|
||||
core_bridge = []
|
||||
try:
|
||||
with open(self.core_template) 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('##DIRECT_CALLS##'):
|
||||
core_bridge.extend(direct_calls)
|
||||
else:
|
||||
core_bridge.append(line.replace('\n',''))
|
||||
except IOError:
|
||||
print ("Can't open template file [%s]" % self.core_template)
|
||||
sys.exit(1)
|
||||
|
||||
#now we write to final file
|
||||
if os.path.exists(self.core_dest) and not self.options.force:
|
||||
print ("The destination file [%s] already exists ! Use --force to overwrite it" % self.core_dest)
|
||||
try:
|
||||
with open(self.core_dest,'w') as dest_file:
|
||||
dest_file.write('\n'.join(core_bridge))
|
||||
except IOError:
|
||||
print ("Can't open destination file [%s]" % self.core_dest)
|
||||
|
||||
def generateFrontendSide(self):
|
||||
methods_part = []
|
||||
sections = self.bridge_template.sections()
|
||||
sections.sort()
|
||||
for section in sections:
|
||||
function = self.getValues(section)
|
||||
print ("Adding %s %s" % (section, function["type"]))
|
||||
default = self.getDefault(section)
|
||||
arg_doc = self.getArgumentsDoc(section)
|
||||
completion = {
|
||||
'sig_in':function['sig_in'] or '',
|
||||
'sig_out':function['sig_out'] or '',
|
||||
'category':'req' if function['category'] == 'request' else 'comm',
|
||||
'name':section,
|
||||
'args':self.getArguments(function['sig_in'], name=arg_doc, default=default )
|
||||
}
|
||||
|
||||
if function["type"] == "method":
|
||||
completion['debug'] = "" if not self.options.debug else 'debug ("%s")\n%s' % (section,8*' ')
|
||||
completion['args_result'] = self.getArguments(function['sig_in'], name=arg_doc)
|
||||
methods_part.append("""\
|
||||
def %(name)s(self, %(args)s):
|
||||
%(debug)sreturn self.db_%(category)s_iface.%(name)s(%(args_result)s)
|
||||
""" % completion)
|
||||
|
||||
#at this point, methods_part should be filled,
|
||||
#we just have to place it in the right part of the template
|
||||
frontend_bridge = []
|
||||
try:
|
||||
with open(self.frontend_template) as frontend_template:
|
||||
for line in frontend_template:
|
||||
if line.startswith('##METHODS_PART##'):
|
||||
frontend_bridge.extend(methods_part)
|
||||
else:
|
||||
frontend_bridge.append(line.replace('\n',''))
|
||||
except IOError:
|
||||
print ("Can't open template file [%s]" % self.frontend_template)
|
||||
sys.exit(1)
|
||||
|
||||
#now we write to final file
|
||||
if os.path.exists(self.frontend_dest) and not self.options.force:
|
||||
print ("The destination file [%s] already exists ! Use --force to overwrite it" % self.frontend_dest)
|
||||
try:
|
||||
with open(self.frontend_dest,'w') as dest_file:
|
||||
dest_file.write('\n'.join(frontend_bridge))
|
||||
except IOError:
|
||||
print ("Can't open destination file [%s]" % self.frontend_dest)
|
||||
|
||||
|
||||
class ConstructorError(Exception):
|
||||
pass
|
||||
|
||||
class ConstructorFactory:
|
||||
def create(self, bridge_template, options):
|
||||
if options.protocole=='dbus':
|
||||
return DbusConstructor(bridge_template, options)
|
||||
|
||||
raise ConstructorError('Unknown constructor type')
|
||||
|
||||
class BridgeConstructor:
|
||||
def __init__(self):
|
||||
self.options = None
|
||||
|
||||
def check_options(self):
|
||||
"""Check command line options"""
|
||||
_usage="""
|
||||
%prog [options]
|
||||
|
||||
%prog --help for options list
|
||||
"""
|
||||
parser = OptionParser(usage=_usage,version=ABOUT % VERSION)
|
||||
|
||||
parser.add_option("-p", "--protocole", action="store", type="string", default=DEFAULT_PROTOCOLE,
|
||||
help="Generate bridge using PROTOCOLE (default: %s, possible values: [%s])" % (DEFAULT_PROTOCOLE, ", ".join(MANAGED_PROTOCOLES)))
|
||||
parser.add_option("-s", "--side", action="store", type="string", default="core",
|
||||
help="Which side of the bridge do you want to make ? (default: %default, possible values: [core, frontend])")
|
||||
parser.add_option("-t", "--template", action="store", type="string", default='bridge_template.ini',
|
||||
help="Use TEMPLATE to generate bridge (default: %default)")
|
||||
parser.add_option("-f", "--force", action="store_true", default=False,
|
||||
help=("Force overwritting of existing files"))
|
||||
parser.add_option("-d", "--debug", action="store_true", default=False,
|
||||
help=("Add debug information printing"))
|
||||
parser.add_option("--no_unicode", action="store_false", dest="unicode", default=True,
|
||||
help=("Remove unicode type protection from string results"))
|
||||
|
||||
|
||||
(self.options, args) = parser.parse_args()
|
||||
return args
|
||||
|
||||
def go(self):
|
||||
self.check_options()
|
||||
self.template = Parser()
|
||||
try:
|
||||
self.template.readfp(open(self.options.template))
|
||||
except IOError:
|
||||
print ("The template file doesn't exist or is not accessible")
|
||||
exit(1)
|
||||
constructor = ConstructorFactory().create(self.template, self.options)
|
||||
if self.options.side == "core":
|
||||
constructor.generateCoreSide()
|
||||
elif self.options.side == "frontend":
|
||||
constructor.generateFrontendSide()
|
||||
|
||||
if __name__ == "__main__":
|
||||
bc = BridgeConstructor()
|
||||
bc.go()
|
||||
468
src/bridge/bridge_constructor/bridge_template.ini
Normal file
468
src/bridge/bridge_constructor/bridge_template.ini
Normal file
|
|
@ -0,0 +1,468 @@
|
|||
[DEFAULT]
|
||||
doc_profile=profile: Name of the profile.
|
||||
doc_profile_key=profile_key: Profile key which can be either a magic (eg: @DEFAULT@) or the name of an existing profile.
|
||||
|
||||
;signals
|
||||
|
||||
[connected]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=s
|
||||
doc=Connection is done
|
||||
doc_param_0=%(doc_profile)s
|
||||
|
||||
[disconnected]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=s
|
||||
doc=Connection is finished or lost
|
||||
doc_param_0=%(doc_profile)s
|
||||
|
||||
[connection_error]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=ss
|
||||
doc=Something went wront with the connection
|
||||
doc_param_0=error_type: Why the connection got wrong, can be
|
||||
- AUTH_ERROR: Authentification error
|
||||
doc_param_1=%(doc_profile)s
|
||||
|
||||
[newContact]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=sa{ss}ass
|
||||
doc=New contact received in roster
|
||||
doc_param_0=contact: JID from who the message is comming
|
||||
doc_param_1=attributes: Dictionary of attributes where keys are:
|
||||
- name: name of the contact
|
||||
- to: "True" if the contact give its presence information to us
|
||||
- from: "True" if contact is registred to our presence information
|
||||
- ask: "True" is subscription is pending
|
||||
doc_param_2=groups: Roster's groups where the contact is
|
||||
doc_param_3=%(doc_profile)s
|
||||
|
||||
[newMessage]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=sssss
|
||||
doc=A message has been received
|
||||
doc_param_0=from_jid: JID where the message is comming from
|
||||
doc_param_1=message: Message itself
|
||||
doc_param_2=mess_type: Type of the message (cf RFC 3921 #2.1.1)
|
||||
doc_param_3=to_jid: JID where the message must be sent
|
||||
doc_param_4=%(doc_profile)s
|
||||
|
||||
[newAlert]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=ssss
|
||||
doc=A new alert happened
|
||||
doc_param_0=message: Body of the alert
|
||||
doc_param_1=title: Title of the alert
|
||||
doc_param_2=alert_type: Type of the alert, can be:
|
||||
- INFO: Informative message
|
||||
- ERROR: something went wrong
|
||||
doc_param_3=%(doc_profile)s
|
||||
|
||||
[presenceUpdate]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=ssia{ss}s
|
||||
doc=Somebody changed his presence informations.
|
||||
doc_param_0=entity: JID from which we have presence informations
|
||||
doc_param_1=show: availability status (see RFC 3921 #2.2.2.1)
|
||||
doc_param_2=priority: Priority level of the ressource (see RFC 3921 #2.2.2.3)
|
||||
doc_param_3=statuses: Natural language description of the availability status (see RFC 3921 #2.2.2.2)
|
||||
doc_param_4=%(doc_profile)s
|
||||
|
||||
[subscribe]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=sss
|
||||
doc=Somebody wants to be added in roster
|
||||
doc_param_0=sub_type: Subscription states (see RFC 3921 #9)
|
||||
doc_param_1=entity: JID from which the subscription is coming
|
||||
doc_param_2=%(doc_profile)s
|
||||
|
||||
[paramUpdate]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=ssss
|
||||
doc=A parameter has been changed
|
||||
doc_param_0=name: Name of the updated parameter
|
||||
doc_param_1=value: New value of the parameter
|
||||
doc_param_2=category: Category of the updated parameter
|
||||
doc_param_3=%(doc_profile)s
|
||||
|
||||
[contactDeleted]
|
||||
type=signal
|
||||
category=communication
|
||||
sig_in=ss
|
||||
doc=A contact has been supressed from roster
|
||||
doc_param_0=entity: JID of the contact removed from roster
|
||||
doc_param_1=%(doc_profile)s
|
||||
|
||||
[askConfirmation]
|
||||
type=signal
|
||||
category=request
|
||||
sig_in=ssa{ss}
|
||||
doc=A confirmation is needed for an action
|
||||
doc_param_0=conf_type: Type of the confirmation, can be:
|
||||
- YES/NO: A question which need a yes or no answer
|
||||
- FILE_TRANSFERT: A confirmation is needed before transfering a file
|
||||
doc_param_1=id: Id of the confirmation query
|
||||
doc_param_2=data: conf_type dependent data
|
||||
|
||||
[actionResult]
|
||||
type=signal
|
||||
category=request
|
||||
sig_in=ssa{ss}
|
||||
doc=Requested result of an action
|
||||
doc_param_0=answer_type: Type of the answer, can be:
|
||||
- SUPPRESS: The action is managed, the id MUST be removed from queue
|
||||
- XMLUI: A SàT XMLUI interface is sent
|
||||
- ERROR: Something went wrong when doing the action
|
||||
- RESULT: General result, interpretation depend of the action
|
||||
doc_param_1=id: Id of the action
|
||||
doc_param_2=data: answer_type specific data
|
||||
|
||||
[actionResultExt]
|
||||
type=signal
|
||||
category=request
|
||||
sig_in=ssa{sa{ss}}
|
||||
doc=Requested result of an action (Extended)
|
||||
doc_param_0=answer_type: Same as for [actionResult] but with the following additional one:
|
||||
- DICT_DICT: As RESULT, but returned as a dictionary of dictionary
|
||||
doc_param_1=id: Id of the action
|
||||
doc_param_2=data: answer_type specific data
|
||||
|
||||
[updatedValue]
|
||||
type=signal
|
||||
category=request
|
||||
sig_in=sa{ss}
|
||||
doc=A value has been updated
|
||||
doc_param_0=name: Name of the updated value
|
||||
doc_param_1=value: New value
|
||||
|
||||
;methods
|
||||
|
||||
[getVersion]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=
|
||||
sig_out=s
|
||||
doc=Get "Salut à Toi" version
|
||||
|
||||
[getProfileName]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=s
|
||||
sig_out=s
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Get real profile name from profile key
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
|
||||
[getProfilesList]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=
|
||||
sig_out=as
|
||||
doc=Get all profiles
|
||||
|
||||
[createProfile]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=s
|
||||
sig_out=i
|
||||
doc=Create a new profile
|
||||
doc_param_0=%(doc_profile)s
|
||||
doc_return=status of the creation:
|
||||
- 0: Profile created
|
||||
- 1: The profile name already exists
|
||||
|
||||
[deleteProfile]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=s
|
||||
sig_out=i
|
||||
doc=Delete a profile
|
||||
doc_param_0=%(doc_profile)s
|
||||
doc_return=status of the deletion:
|
||||
- 0: Profile deleted
|
||||
- 1: The profile doesn't exists
|
||||
|
||||
[registerNewAccount]
|
||||
deprecated=
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=sssi
|
||||
sig_out=s
|
||||
param_3_default=5222
|
||||
doc=Register a new account on a given server
|
||||
doc_param_0=login: login of the account
|
||||
doc_param_1=password: password of the account
|
||||
doc_param_2=host: host of the server to register to
|
||||
doc_param_3=port: port of the server to register to
|
||||
|
||||
[connect]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=s
|
||||
sig_out=
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Connect a profile
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
|
||||
[disconnect]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=s
|
||||
sig_out=
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Disconnect a profile
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
|
||||
[isConnected]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=s
|
||||
sig_out=b
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Tell if a profile is connected
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
|
||||
[getContacts]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=s
|
||||
sig_out=a(sa{ss}as)
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Return informations about all contacts
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
doc_return=array of tuples with the following values:
|
||||
- JID of the contact
|
||||
- list of attributes as in [newContact]
|
||||
- groups where the contact is
|
||||
|
||||
[getPresenceStatus]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=s
|
||||
sig_out=a{sa{s(sia{ss})}}
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Return presence informations of all contacts
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
doc_return=Dict of presence with bare JID of contact as key, and value as follow:
|
||||
A dict where key is the resource and the value is a tuple with (show, priority, statuses) as for [presenceUpdate]
|
||||
|
||||
[getWaitingSub]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=s
|
||||
sig_out=a{ss}
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Get subscription requests in queue
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
doc_return=Dict where contact JID is the key, and value is the subscription type
|
||||
|
||||
[sendMessage]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=sssss
|
||||
sig_out=
|
||||
param_2_default=''
|
||||
param_3_default="chat"
|
||||
param_4_default="@DEFAULT@"
|
||||
doc=Send a message
|
||||
doc_param_0=to_jid: JID of the recipient
|
||||
doc_param_1=message: body of the message
|
||||
doc_param_2=subject: Subject of the message ('' if no subject)
|
||||
doc_param_3=mess_type: Type of the message (cf RFC 3921 #2.1.1)
|
||||
doc_param_4=%(doc_profile_key)s
|
||||
|
||||
[setPresence]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=ssia{ss}s
|
||||
sig_out=
|
||||
param_0_default=''
|
||||
param_1_default=''
|
||||
param_2_default=0
|
||||
param_3_default={}
|
||||
param_4_default="@DEFAULT@"
|
||||
doc=Set presence information for the profile
|
||||
doc_param_0=to_jid: the JID to who we send the presence data (emtpy string for broadcast)
|
||||
doc_param_1=show: as for [presenceUpdate]
|
||||
doc_param_2=priority: as for [presenceUpdate]
|
||||
doc_param_3=statuses: as for [presenceUpdate]
|
||||
doc_param_4=%(doc_profile_key)s
|
||||
|
||||
[subscription]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=sss
|
||||
sig_out=
|
||||
param_2_default="@DEFAULT@"
|
||||
doc=Send subscription request/answer to a contact
|
||||
doc_param_0=sub_type: as for [subscribe]
|
||||
doc_param_1=entity: as for [subscribe]
|
||||
doc_param_2=%(doc_profile_key)s
|
||||
|
||||
[setParam]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=ssss
|
||||
sig_out=
|
||||
param_3_default="@DEFAULT@"
|
||||
doc=Change a parameter
|
||||
doc_param_0=name: Name of the parameter to change
|
||||
doc_param_1=value: New Value of the parameter
|
||||
doc_param_2=category: Category of the parameter to change
|
||||
doc_param_3=%(doc_profile_key)s
|
||||
|
||||
[getParamA]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=sss
|
||||
sig_out=s
|
||||
param_2_default="@DEFAULT@"
|
||||
doc=Helper method to get a parameter's attribute
|
||||
doc_param_0=name: as for [setParam]
|
||||
doc_param_1=category: as for [setParam]
|
||||
doc_param_2=%(doc_profile_key)s
|
||||
|
||||
[getParamsUI]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=s
|
||||
sig_out=s
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Return a SàT XMLUI for parameters
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
|
||||
[getParams]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=s
|
||||
sig_out=s
|
||||
param_0_default="@DEFAULT@"
|
||||
doc=Return XML of parameters
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
|
||||
[getParamsForCategory]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=ss
|
||||
sig_out=s
|
||||
param_1_default="@DEFAULT@"
|
||||
doc=Return a xml of all params in a category
|
||||
doc_param_0=category: Category to get
|
||||
doc_param_1=%(doc_profile_key)s
|
||||
|
||||
[getParamsCategories]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=
|
||||
sig_out=as
|
||||
doc=Get all categories currently existing in parameters
|
||||
doc_return=list of categories
|
||||
|
||||
[getHistory]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=ssi
|
||||
sig_out=a{i(ss)}
|
||||
doc=Get history of a communication between two entities
|
||||
doc_param_0=from_jid: source JID
|
||||
doc_param_1=to_jid: dest JID
|
||||
doc_param_2=size: size of the history (0 for the whole history)
|
||||
doc_return=Dict where key is timestamp (seconds this the Epoch), and value is a tuple (from_jid, to_jid)
|
||||
|
||||
[addContact]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=ss
|
||||
sig_out=
|
||||
param_1_default="@DEFAULT@"
|
||||
doc=Add a contact to profile's roster
|
||||
doc_param_0=entity: JID to add to roster
|
||||
doc_param_1=%(doc_profile_key)s
|
||||
|
||||
[delContact]
|
||||
type=method
|
||||
category=communication
|
||||
sig_in=ss
|
||||
sig_out=
|
||||
param_1_default="@DEFAULT@"
|
||||
doc=Remove a contact from profile's roster
|
||||
doc_param_0=entity: JID to remove from roster
|
||||
doc_param_1=%(doc_profile_key)s
|
||||
|
||||
[launchAction]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=sa{ss}s
|
||||
sig_out=s
|
||||
param_2_default="@DEFAULT@"
|
||||
doc=Launch a specific action
|
||||
doc_param_0=action_type: type of the action which can be:
|
||||
- button: A button is pushed
|
||||
doc_param_1=data: action_type dependant data
|
||||
doc_param_2=%(doc_profile_key)s
|
||||
|
||||
[confirmationAnswer]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=sba{ss}
|
||||
sig_out=
|
||||
doc=Give answer to a confirmation request
|
||||
doc_param_0=id: id of the confirmation request
|
||||
doc_param_1=accepted: True if the action is confirmed
|
||||
doc_param_2=data: action specific data
|
||||
|
||||
[getProgress]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=s
|
||||
sig_out=a{ss}
|
||||
doc=Get progress information for an action
|
||||
doc_param_0=id: id of the progression status
|
||||
doc_return=dict with progress information:
|
||||
- position: current position
|
||||
- size: end position
|
||||
|
||||
[getMenus]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=
|
||||
sig_out=a(sss)
|
||||
doc=Get all additional menus
|
||||
doc_return=list of tuple with the following value:
|
||||
- category: Category of the menu
|
||||
- name: Name of the menu
|
||||
- menu_type: Type which can be:
|
||||
* NORMAL: Classical application menu
|
||||
|
||||
[getMenuHelp]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=sss
|
||||
sig_out=s
|
||||
param_2="NORMAL"
|
||||
doc=Get help information for a menu
|
||||
doc_param_0=category: Category of the menu
|
||||
doc_param_1=name: Name of the menu
|
||||
doc_param_2=menu_type: Type of the menu as in [getMenus] return value
|
||||
doc_return=Help string
|
||||
|
||||
[callMenu]
|
||||
type=method
|
||||
category=request
|
||||
sig_in=ssss
|
||||
sig_out=s
|
||||
doc=Execute action associated with a menu
|
||||
doc_param_0=category: as in [getMenuHelp]
|
||||
doc_param_1=name: as in [getMenuHelp]
|
||||
doc_param_2=menu_type: as in [getMenuHelp]
|
||||
doc_param_3=%(doc_profile_key)s
|
||||
doc_return=return an actionId or the empty string if something went wrong
|
||||
133
src/bridge/bridge_constructor/dbus_core_template.py
Normal file
133
src/bridge/bridge_constructor/dbus_core_template.py
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
#!/usr/bin/python
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
SAT: a jabber client
|
||||
Copyright (C) 2009, 2010, 2011 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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
|
||||
from bridge import Bridge
|
||||
import dbus
|
||||
import dbus.service
|
||||
import dbus.mainloop.glib
|
||||
from logging import debug, info, error
|
||||
|
||||
const_INT_PREFIX = "org.goffi.SAT" #Interface prefix
|
||||
const_COMM_SUFFIX = ".communication"
|
||||
const_REQ_SUFFIX = ".request"
|
||||
|
||||
class DbusObject(dbus.service.Object):
|
||||
|
||||
def __init__(self, bus, path):
|
||||
dbus.service.Object.__init__(self, bus, path)
|
||||
debug("Init DbusObject...")
|
||||
self.cb={}
|
||||
|
||||
def register(self, name, cb):
|
||||
self.cb[name]=cb
|
||||
|
||||
### signals ###
|
||||
|
||||
##SIGNALS_PART##
|
||||
|
||||
### methods ###
|
||||
|
||||
##METHODS_PART##
|
||||
|
||||
def __attribute_string(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_string=""
|
||||
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_string += ("" if idx==0 else ", ") + ("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_string
|
||||
|
||||
def addMethod(self, name, int_suffix, in_sign, out_sign):
|
||||
"""Dynamically add a method to Dbus Bridge"""
|
||||
#FIXME: Better way ???
|
||||
attributes = self.__attribute_string(in_sign)
|
||||
|
||||
code = compile ('def '+name+' (self,'+attributes+'): return self.cb["'+name+'"]('+attributes+')', '<DBus bridge>','exec')
|
||||
exec (code)
|
||||
method = locals()[name]
|
||||
setattr(DbusObject, name, dbus.service.method(
|
||||
const_INT_PREFIX+int_suffix, in_signature=in_sign, out_signature=out_sign)(method))
|
||||
|
||||
def addSignal(self, name, int_suffix, signature):
|
||||
"""Dynamically add a signal to Dbus Bridge"""
|
||||
#FIXME: Better way ???
|
||||
attributes = self.__attribute_string(signature)
|
||||
|
||||
code = compile ('def '+name+' (self,'+attributes+'): debug ("'+name+' signal")', '<DBus bridge>','exec')
|
||||
exec (code)
|
||||
signal = locals()[name]
|
||||
setattr(DbusObject, name, dbus.service.signal(
|
||||
const_INT_PREFIX+int_suffix, signature=signature)(signal))
|
||||
|
||||
class DBusBridge(Bridge):
|
||||
def __init__(self):
|
||||
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
|
||||
Bridge.__init__(self)
|
||||
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, '/org/goffi/SAT/bridge')
|
||||
|
||||
##DIRECT_CALLS##
|
||||
|
||||
def register(self, name, callback):
|
||||
debug("registering DBus bridge method [%s]", name)
|
||||
self.dbus_bridge.register(name, callback)
|
||||
|
||||
def addMethod(self, name, int_suffix, in_sign, out_sign, method):
|
||||
"""Dynamically add a method to Dbus Bridge"""
|
||||
print ("Adding method [%s] to DBus bridge" % name)
|
||||
self.dbus_bridge.addMethod(name, int_suffix, in_sign, out_sign)
|
||||
self.register(name, method)
|
||||
|
||||
def addSignal(self, name, int_suffix, signature):
|
||||
self.dbus_bridge.addSignal(name, int_suffix, signature)
|
||||
setattr(DBusBridge, name, getattr(self.dbus_bridge, name))
|
||||
|
||||
98
src/bridge/bridge_constructor/dbus_frontend_template.py
Normal file
98
src/bridge/bridge_constructor/dbus_frontend_template.py
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
#!/usr/bin/python
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
SAT communication bridge
|
||||
Copyright (C) 2009, 2010, 2011 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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from bridge_frontend import BridgeFrontend
|
||||
import dbus, dbus.glib
|
||||
|
||||
class BridgeExceptionNoService(Exception):
|
||||
pass
|
||||
|
||||
class DBusBridgeFrontend(BridgeFrontend):
|
||||
def __init__(self):
|
||||
try:
|
||||
self.sessions_bus = dbus.SessionBus()
|
||||
self.db_object = self.sessions_bus.get_object('org.goffi.SAT',
|
||||
'/org/goffi/SAT/bridge')
|
||||
self.db_comm_iface = dbus.Interface(self.db_object,
|
||||
dbus_interface='org.goffi.SAT.communication')
|
||||
self.db_req_iface = dbus.Interface(self.db_object,
|
||||
dbus_interface='org.goffi.SAT.request')
|
||||
except dbus.exceptions.DBusException,e:
|
||||
if e._dbus_error_name=='org.freedesktop.DBus.Error.ServiceUnknown':
|
||||
raise BridgeExceptionNoService
|
||||
else:
|
||||
raise e
|
||||
#props = self.db_comm_iface.getProperties()
|
||||
|
||||
def register(self, functionName, handler, iface="communication"):
|
||||
if iface == "communication":
|
||||
self.db_comm_iface.connect_to_signal(functionName, handler)
|
||||
elif iface == "request":
|
||||
self.db_req_iface.connect_to_signal(functionName, handler)
|
||||
|
||||
##METHODS_PART##
|
||||
|
||||
#methods from plugins
|
||||
def getRoomJoined(self, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.getRoomJoined(profile_key)
|
||||
|
||||
def getRoomSubjects(self, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.getRoomSubjects(profile_key)
|
||||
|
||||
def joinMUC(self, service, roomId, nick, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.joinMUC(service, roomId, nick, profile_key)
|
||||
|
||||
def tarotGameCreate(self, room_jid, players, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.tarotGameCreate(room_jid, players, profile_key)
|
||||
|
||||
def tarotGameReady(self, player, referee, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.tarotGameReady(player, referee, profile_key)
|
||||
|
||||
def tarotGameContratChoosed(self, player, referee, contrat, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.tarotGameContratChoosed(player, referee, contrat, profile_key)
|
||||
|
||||
def tarotGamePlayCards(self, player, referee, cards, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.tarotGamePlayCards(player, referee, cards, profile_key)
|
||||
|
||||
def sendFile(self, to, path, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.sendFile(to, path, profile_key)
|
||||
|
||||
def findGateways(self, target, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.findGateways(target, profile_key)
|
||||
|
||||
def getCard(self, target, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.getCard(target, profile_key)
|
||||
|
||||
def getCardCache(self, target):
|
||||
return self.db_comm_iface.getCardCache(target)
|
||||
|
||||
def getAvatarFile(self, hash):
|
||||
return self.db_comm_iface.getAvatarFile(hash)
|
||||
|
||||
def in_band_register(self, target, profile_key='@DEFAULT@'):
|
||||
return self.db_comm_iface.in_band_register(target, profile_key)
|
||||
|
||||
def gatewayRegister(self, action, target, data, profile_key='@DEFAULT@'):
|
||||
if data == None:
|
||||
data = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature
|
||||
return self.db_req_iface.gatewayRegister(action, target, data, profile_key)
|
||||
|
||||
|
||||
Loading…
Reference in a new issue