view src/bridge/DBus.py @ 331:0a8eb0461f31

core: main SAT class now moved in its own module core.sat_main
author Goffi <goffi@goffi.org>
date Mon, 23 May 2011 21:32:28 +0200
parents 233e6fce0b49
children 953536246d9d
line wrap: on
line source

#!/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

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 ###    

    @dbus.service.signal(const_INT_PREFIX+const_REQ_SUFFIX,
                         signature='ssa{ss}')
    def actionResult(self, answer_type, id, data):
        debug ("actionResult")

    @dbus.service.signal(const_INT_PREFIX+const_REQ_SUFFIX,
                         signature='ssa{sa{ss}}')
    def actionResultExt(self, answer_type, id, data):
        debug ("actionResultExt")

    @dbus.service.signal(const_INT_PREFIX+const_REQ_SUFFIX,
                         signature='ssa{ss}')
    def askConfirmation(self, conf_type, id, data):
        debug ("askConfirmation")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='s')
    def connected(self, profile):
        debug ("connected")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ss')
    def connectionError(self, error_type, profile):
        debug ("connectionError")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ss')
    def contactDeleted(self, entity, profile):
        debug ("contactDeleted")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='s')
    def disconnected(self, profile):
        debug ("disconnected")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ssss')
    def newAlert(self, message, title, alert_type, profile):
        debug ("newAlert")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='sa{ss}ass')
    def newContact(self, contact, attributes, groups, profile):
        debug ("newContact")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='sssss')
    def newMessage(self, from_jid, message, mess_type, to_jid, profile):
        debug ("newMessage")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ssss')
    def paramUpdate(self, name, value, category, profile):
        debug ("paramUpdate")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ssia{ss}s')
    def presenceUpdate(self, entity, show, priority, statuses, profile):
        debug ("presenceUpdate")

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='sss')
    def subscribe(self, sub_type, entity, profile):
        debug ("subscribe")

    @dbus.service.signal(const_INT_PREFIX+const_REQ_SUFFIX,
                         signature='sa{ss}')
    def updatedValue(self, name, value):
        debug ("updatedValue")


    ### methods ###    
    
    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ss', out_signature='')
    def addContact(self, entity, profile_key="@DEFAULT@"):
        debug ("addContact")
        return self.cb["addContact"](unicode(entity), unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='ssss', out_signature='s')
    def callMenu(self, category, name, menu_type, profile_key):
        debug ("callMenu")
        return self.cb["callMenu"](unicode(category), unicode(name), unicode(menu_type), unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='sba{ss}', out_signature='')
    def confirmationAnswer(self, id, accepted, data):
        debug ("confirmationAnswer")
        return self.cb["confirmationAnswer"](unicode(id), accepted, data)

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='')
    def connect(self, profile_key="@DEFAULT@"):
        debug ("connect")
        return self.cb["connect"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='s', out_signature='i')
    def createProfile(self, profile):
        debug ("createProfile")
        return self.cb["createProfile"](unicode(profile))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ss', out_signature='')
    def delContact(self, entity, profile_key="@DEFAULT@"):
        debug ("delContact")
        return self.cb["delContact"](unicode(entity), unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='s', out_signature='i')
    def deleteProfile(self, profile):
        debug ("deleteProfile")
        return self.cb["deleteProfile"](unicode(profile))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='')
    def disconnect(self, profile_key="@DEFAULT@"):
        debug ("disconnect")
        return self.cb["disconnect"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='a(sa{ss}as)')
    def getContacts(self, profile_key="@DEFAULT@"):
        debug ("getContacts")
        return self.cb["getContacts"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ssi', out_signature='a{i(ss)}')
    def getHistory(self, from_jid, to_jid, size):
        debug ("getHistory")
        return self.cb["getHistory"](unicode(from_jid), unicode(to_jid), size)

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='sss', out_signature='s')
    def getMenuHelp(self, category, name, menu_type):
        debug ("getMenuHelp")
        return self.cb["getMenuHelp"](unicode(category), unicode(name), unicode(menu_type))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='', out_signature='a(sss)')
    def getMenus(self, ):
        debug ("getMenus")
        return self.cb["getMenus"]()

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ssss', out_signature='s')
    def getParamA(self, name, category, attribute="value", profile_key="@DEFAULT@"):
        debug ("getParamA")
        return self.cb["getParamA"](unicode(name), unicode(category), unicode(attribute), unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='s')
    def getParams(self, profile_key="@DEFAULT@"):
        debug ("getParams")
        return self.cb["getParams"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='', out_signature='as')
    def getParamsCategories(self, ):
        debug ("getParamsCategories")
        return self.cb["getParamsCategories"]()

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ss', out_signature='s')
    def getParamsForCategory(self, category, profile_key="@DEFAULT@"):
        debug ("getParamsForCategory")
        return self.cb["getParamsForCategory"](unicode(category), unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='s')
    def getParamsUI(self, profile_key="@DEFAULT@"):
        debug ("getParamsUI")
        return self.cb["getParamsUI"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='a{sa{s(sia{ss})}}')
    def getPresenceStatus(self, profile_key="@DEFAULT@"):
        debug ("getPresenceStatus")
        return self.cb["getPresenceStatus"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='s', out_signature='s')
    def getProfileName(self, profile_key="@DEFAULT@"):
        debug ("getProfileName")
        return self.cb["getProfileName"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='', out_signature='as')
    def getProfilesList(self, ):
        debug ("getProfilesList")
        return self.cb["getProfilesList"]()

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='s', out_signature='a{ss}')
    def getProgress(self, id):
        debug ("getProgress")
        return self.cb["getProgress"](unicode(id))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='', out_signature='s')
    def getVersion(self, ):
        debug ("getVersion")
        return self.cb["getVersion"]()

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='a{ss}')
    def getWaitingSub(self, profile_key="@DEFAULT@"):
        debug ("getWaitingSub")
        return self.cb["getWaitingSub"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='b')
    def isConnected(self, profile_key="@DEFAULT@"):
        debug ("isConnected")
        return self.cb["isConnected"](unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='sa{ss}s', out_signature='s')
    def launchAction(self, action_type, data, profile_key="@DEFAULT@"):
        debug ("launchAction")
        return self.cb["launchAction"](unicode(action_type), data, unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='sssi', out_signature='s')
    def registerNewAccount(self, login, password, host, port=5222):
        debug ("registerNewAccount")
        return self.cb["registerNewAccount"](unicode(login), unicode(password), unicode(host), port)

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='sssss', out_signature='')
    def sendMessage(self, to_jid, message, subject='', mess_type="chat", profile_key="@DEFAULT@"):
        debug ("sendMessage")
        return self.cb["sendMessage"](unicode(to_jid), unicode(message), unicode(subject), unicode(mess_type), unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ssss', out_signature='')
    def setParam(self, name, value, category, profile_key="@DEFAULT@"):
        debug ("setParam")
        return self.cb["setParam"](unicode(name), unicode(value), unicode(category), unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ssia{ss}s', out_signature='')
    def setPresence(self, to_jid='', show='', priority=0, statuses={}, profile_key="@DEFAULT@"):
        debug ("setPresence")
        return self.cb["setPresence"](unicode(to_jid), unicode(show), priority, statuses, unicode(profile_key))

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='sss', out_signature='')
    def subscription(self, sub_type, entity, profile_key="@DEFAULT@"):
        debug ("subscription")
        return self.cb["subscription"](unicode(sub_type), unicode(entity), 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']:
                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, async=False, doc={}):
        """Dynamically add a method to Dbus Bridge"""
        _attributes = self.__attributes(in_sign)

        if async:
            _attributes.extend(['callback','errback'])
        
        attributes = ', '.join(_attributes)

        code = compile ('def '+name+' (self,'+attributes+'): return self.cb["'+name+'"]('+attributes+')', '<DBus bridge>','exec')
        exec (code)
        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))

        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))
        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 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')

    def actionResult(self, answer_type, id, data):
        self.dbus_bridge.actionResult(answer_type, id, data)

    def actionResultExt(self, answer_type, id, data):
        self.dbus_bridge.actionResultExt(answer_type, id, data)

    def askConfirmation(self, conf_type, id, data):
        self.dbus_bridge.askConfirmation(conf_type, id, data)

    def connected(self, profile):
        self.dbus_bridge.connected(profile)

    def connectionError(self, error_type, profile):
        self.dbus_bridge.connectionError(error_type, profile)

    def contactDeleted(self, entity, profile):
        self.dbus_bridge.contactDeleted(entity, profile)

    def disconnected(self, profile):
        self.dbus_bridge.disconnected(profile)

    def newAlert(self, message, title, alert_type, profile):
        self.dbus_bridge.newAlert(message, title, alert_type, profile)

    def newContact(self, contact, attributes, groups, profile):
        self.dbus_bridge.newContact(contact, attributes, groups, profile)

    def newMessage(self, from_jid, message, mess_type, to_jid, profile):
        self.dbus_bridge.newMessage(from_jid, message, mess_type, to_jid, profile)

    def paramUpdate(self, name, value, category, profile):
        self.dbus_bridge.paramUpdate(name, value, category, profile)

    def presenceUpdate(self, entity, show, priority, statuses, profile):
        self.dbus_bridge.presenceUpdate(entity, show, priority, statuses, profile)

    def subscribe(self, sub_type, entity, profile):
        self.dbus_bridge.subscribe(sub_type, entity, profile)

    def updatedValue(self, name, value):
        self.dbus_bridge.updatedValue(name, value)


    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, async=False, doc={}):
        """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, async, doc)
        self.register(name, method)

    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))