view src/bridge/DBus.py @ 238:83d2bc0abf2a

version, README, CHANGELOG and INSTALL updates
author Goffi <goffi@goffi.org>
date Wed, 12 Jan 2011 18:21:08 +0100
parents b1794cbb88e5
children c8406fe5e81e
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
import pdb
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 ###    

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='s')
    def connected(self, profile):
        debug("Connected signal")
    
    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='s')
    def disconnected(self, profile):
        debug("Disconnected signal")
    
    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='sa{ss}ass')
    def newContact(self, contact, attributes, groups, profile):
        debug("new contact signal (%s) sended (profile: %s)", contact, profile)

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='sssss')
    def newMessage(self, from_jid, msg, type, to, profile):
        debug("new message signal (from:%s msg:%s type:%s to:%s) sended", from_jid, msg, type, to)
     
    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ssss')
    def newAlert(self, msg, title, type, profile):
        debug("new alert signal (title:%s type:%s msg:%s profile:%s) sended", type, title, msg, profile)
     
    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ssia{ss}s')
    def presenceUpdate(self, entity, show, priority, statuses, profile):
        debug("presence update signal (from:%s show:%s priority:%d statuses:%s profile:%s) sended" , entity, show, priority, statuses, profile)

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='sss')
    def subscribe(self, type, entity, profile):
        debug("subscribe (type: [%s] from:[%s] profile:[%s])" , type, entity, profile)
    
    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ssss')
    def paramUpdate(self, name, value, category, profile):
        debug("param update signal: %s=%s in category %s (profile: %s)", name, value, category, profile)

    @dbus.service.signal(const_INT_PREFIX+const_COMM_SUFFIX,
                         signature='ss')
    def contactDeleted(self, entity, profile):
        debug("contact deleted signal: %s (profile: %s)", entity, profile)
    
    @dbus.service.signal(const_INT_PREFIX+const_REQ_SUFFIX,
                         signature='ssa{ss}')
    def askConfirmation(self, type, id, data):
        debug("asking for confirmation: id = [%s]  type = %s data = %s", id, type, data)

    @dbus.service.signal(const_INT_PREFIX+const_REQ_SUFFIX,
                         signature='ssa{ss}')
    def actionResult(self, type, id, data):
        debug("result of action: id = [%s]  type = %s data = %s", id, type, data)

    @dbus.service.signal(const_INT_PREFIX+const_REQ_SUFFIX,
                         signature='ssa{sa{ss}}')
    def actionResultExt(self, type, id, data):
        debug("extended result of action: id = [%s]  type = %s data = %s", id, type, data)
    
    @dbus.service.signal(const_INT_PREFIX+const_REQ_SUFFIX,
                         signature='sa{ss}')
    def updatedValue(self, name, value):
        debug("updated value: %s = %s", name, value)

    ### methods ###    

    
    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='', out_signature='s')
    def getVersion(self):
        return self.cb["getVersion"]()
    
    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='s', out_signature='s')
    def getProfileName(self, profile_key):
        return self.cb["getProfileName"](profile_key)
    
    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='', out_signature='as')
    def getProfilesList(self):
        info ('Profile list asked')
        return self.cb["getProfilesList"]()

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='s', out_signature='i')
    def createProfile(self, name):
        info ('Profile creation asked')
        return self.cb["createProfile"](unicode(name))

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='s', out_signature='i')
    def deleteProfile(self, name):
        info ('Profile deletion asked')
        return self.cb["deleteProfile"](str(name))

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

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

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='s', out_signature='')
    def disconnect(self, profile_key='@DEFAULT@'):
        info ("Disconnection asked")
        return self.cb["disconnect"](profile_key)
    
    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='', out_signature='b')
    def isConnected(self, profile_key='@DEFAULT@'):
        info ("Connection status asked")
        return self.cb["isConnected"](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"](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"](profile_key)

    @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"](profile_key)

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ssss', out_signature='')
    def sendMessage(self, to, message, type='chat', profile_key='@DEFAULT@'):
        debug("sendMessage...")
        print "sendtype=", type  #gof
        self.cb["sendMessage"](to, message, type, profile_key)

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

    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='sss', out_signature='')
    def subscription(self, type, entity, profile_key='@DEFAULT@'):
        self.cb["subscription"](type, entity, 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@'):
        self.cb["setParam"](unicode(name), unicode(value), unicode(category), profile_key)
        
    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='sss', out_signature='s')
    def getParamA(self, name, category="default", profile_key='@DEFAULT@'):
        return self.cb["getParamA"](name, category, profile_key = profile_key)


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

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

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

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

    @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("History asked for %s", to_jid)
        return self.cb["getHistory"](from_jid, to_jid, size)
    
    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ss', out_signature='')
    def addContact(self, entity, profile_key='@DEFAULT@'):
        debug("Subscription asked for %s (profile %s)", entity, profile_key)
        return self.cb["addContact"](entity, profile_key)
    
    @dbus.service.method(const_INT_PREFIX+const_COMM_SUFFIX,
                         in_signature='ss', out_signature='')
    def delContact(self, entity, profile_key='@DEFAULT@'):
        debug("Unsubscription asked for %s (profile %s)", entity, profile_key)
        return self.cb["delContact"](entity, profile_key)

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='sa{ss}s', out_signature='s')
    def launchAction(self, type, data, profile_key='@DEFAULT@'):
        return self.cb["launchAction"](type, data, profile_key)
    
    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='sba{ss}', out_signature='')
    def confirmationAnswer(self, id, accepted, data):
        debug("Answer for confirmation [%s]: %s", id, "Accepted" if accepted else "Refused")
        return self.cb["confirmationAnswer"](id, accepted, data)
    

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

    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='', out_signature='a(sss)')
    def getMenus(self):
        return self.cb["getMenus"]()
    
    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='sss', out_signature='s')
    def getMenuHelp(self, category, name, type="NORMAL"):
        return self.cb["getMenuHelp"](category, name, type)
    
    @dbus.service.method(const_INT_PREFIX+const_REQ_SUFFIX,
                         in_signature='ssss', out_signature='s')
    def callMenu(self, category, name, type, profile_key):
        return self.cb["callMenu"](category, name, type, profile_key)
    
    def __attribute_string(self, in_sign):
        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 Exception  #FIXME: create an exception here (unmanaged attribute type)

            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
                while (True): #we have a dict or a list of tuples
                    i+=1
                    if i>=len(in_sign):
                        raise Exception  #FIXME: create an exception here (the '}' is not presend)
                    if in_sign[i] == '}' or in_sign[i] == ')':
                        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')

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

    def newMessage(self, from_jid, msg, type='chat', to='', profile='@NONE@'):
        debug("sending message...")
        self.dbus_bridge.newMessage(from_jid, msg, type, to, profile)

    def newAlert(self, msg, title="", alert_type="INFO", profile='@NONE@'):
        self.dbus_bridge.newAlert(msg, title, alert_type, profile)
    
    def presenceUpdate(self, entity, show, priority, statuses, profile):
        debug("updating presence for %s",entity)
        self.dbus_bridge.presenceUpdate(entity, show, priority, statuses, profile)
    
    def roomJoined(self, room_id, room_service, room_nicks, user_nick, profile):
        self.dbus_bridge.roomJoined(room_id, room_service, room_nicks, user_nick, profile)

    def subscribe(self, sub_type, entity, profile):
        debug("subscribe request for %s",entity)
        self.dbus_bridge.subscribe(sub_type, entity, profile)

    def paramUpdate(self, name, value, category, profile):
        debug("updating param [%s] %s ", category, name)
        self.dbus_bridge.paramUpdate(name, value, category, profile)

    def contactDeleted(self, entity, profile):
        debug("sending contact deleted signal %s ", entity)
        self.dbus_bridge.contactDeleted(entity, profile)

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

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

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

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