[asterisk-scf-commits] asterisk-scf/examples.git branch "decorator" created.

Commits to the Asterisk SCF project code repositories asterisk-scf-commits at lists.digium.com
Mon Jun 27 15:53:34 CDT 2011


branch "decorator" has been created
        at  78575f161a3277d2653ca4afbb096d3549e4f3ef (commit)

- Log -----------------------------------------------------------------
commit 78575f161a3277d2653ca4afbb096d3549e4f3ef
Author: Mark Michelson <mmichelson at digium.com>
Date:   Mon Jun 27 15:49:36 2011 -0500

    Add initial Session_Decorator.py script

diff --git a/Session_Decorator.py b/Session_Decorator.py
new file mode 100755
index 0000000..d3b9b46
--- /dev/null
+++ b/Session_Decorator.py
@@ -0,0 +1,262 @@
+#!/usr/bin/env python
+
+#
+# Asterisk SCF -- An open-source communications framework.
+#
+# Copyright (C) 2011, Digium, Inc.
+#
+# See http://www.asterisk.org for more information about
+# the Asterisk SCF project. Please do not directly contact
+# any of the maintainers of this project for assistance;
+# the project provides a web site, mailing lists and IRC
+# channels for your use.
+#
+# This program is free software, distributed under the terms of
+# the GNU General Public License Version 2. See the LICENSE.txt file
+# at the top of the source tree.
+#
+
+import Ice, os, sys, getopt
+
+Ice.loadSlice("-I" + Ice.getSliceDir() + " -I" + os.environ["ASTSCF_HOME"] + " --all " + os.environ["ASTSCF_HOME"] + "/AsteriskSCF/SessionCommunications/SessionCommunicationsIf.ice")
+
+import AsteriskSCF.SessionCommunications.V1
+
+class SessionDecoratorCookie(AsteriskSCF.SessionCommunications.V1.SessionCookie):
+    def __init__(self):
+        pass
+
+# This is a decorator for the Session class. The idea for it is that
+# It contains within it a "real" session of some sort. We can add our
+# own augmentations around the "real" session's methods to do things
+# we'd like. In this example, all we do is print messages to indicate
+# things have happened, but it would be just as possible to do some
+# interesting manipulations.
+class SessionDecorator(AsteriskSCF.SessionCommunications.V1.Session):
+    def __init__(self, session, adapter):
+        self.session = session
+        self.adapter = adapter
+        self.sessionPrxID = None
+        self.cookies = []
+
+    def __del__(self):
+        if self.sessionPrxID:
+            try:
+                self.adapter.remove(self.sessionPrxID)
+            except:
+                print "Caught exception trying to remove session decorator from object adapter"
+
+    def setProxy(self, sessionPrxID):
+        print "setProxy"
+        self.sessionPrxID = sessionPrxID
+
+    def addListener(self, listener, current = None):
+        print "addListener"
+        return self.session.addListener(listener)
+
+    def setCookies(self, cookies, current = None):
+        print "setCookies"
+        for c in cookies:
+            if isinstance(c, SessionDecoratorCookie):
+                self.cookies.append(c)
+
+        self.session.setCookies(cookies)
+
+    def removeCookies(self, cookies, current = None):
+        print "removeCookies"
+        for c in cookies:
+            if isinstance(c, SessionDecoratorCookie):
+                self.cookies.remove(c)
+
+        self.session.removeCookies(cookies)
+
+    def getCookies(self, cookieTypes, current = None):
+        print "getCookies"
+        for c in cookieTypes:
+            if isinstance(c, SessionDecoratorCookie):
+                retCookies.extend(self.cookies)
+
+        retCookies.extend(self.session.getCookies(cookieTypes))
+        return retCookies
+
+    def indicate(self, event, current = None):
+        print "indicate"
+        try:
+            self.session.indicate(event)
+        except AsteriskSCF.SessionCommunications.V1.IndicationException:
+            raise
+
+    def getEndpoint(self, current = None):
+        print "getEndpoint"
+        return self.session.getEndpoint()
+
+    def getInfo(self, current = None):
+        print "getInfo"
+        return self.session.getInfo()
+
+    def getMediaSession(self, current = None):
+        print "getMediaSession"
+        return self.session.getMediaSession()
+
+    def removeListener(self, listener, current = None):
+        print "removeListener"
+        self.session.removeListener(listener)
+
+    def start(self, current = None):
+        print "start"
+        self.session.start()
+
+    def stop(self, response, current = None):
+        print "stop"
+        self.session.stop()
+
+    def getBridge(self, current = None):
+        print "getBridge"
+        try:
+            return self.session.getBridge()
+        except AsteriskSCF.SessionCommunications.V1.NotBridged:
+            raise
+
+    def setBridge(self, newBridge, listener, current=None):
+        print "setBridge"
+        return self.session.setBridge(newBridge, listener)
+
+    def removeBridge(self, listener, current=None):
+        print "removeBridge"
+        self.session.removeBridge(listener)
+
+class BridgeListener(AsteriskSCF.SessionCommunications.V1.BridgeListener):
+    def __init__(self, adapter):
+        self.adapter = adapter
+    def sessionsAdded(self, sessionBridge, sessions, current = None):
+        # When we see a session get added to the bridge, we want to replace that
+        # session with our decorator. The tricky part is that
+        # when we add the decorator to the bridge, we'll get notified of it. So we
+        # need to be sure that we don't try to do something silly like replace ourself
+        # with ourself.
+        print "Sessions added to bridge %s" % (sessionBridge.ice_getIdentity().name)
+        for s in sessions:
+            cookies = s.getCookies([SessionDecoratorCookie()])
+            if len(cookies) is 0:
+                # This is a session we did not add ourselves. We need to create our own session, add it
+                # to the bridge, and remove this session from the bridge.
+                decorator = SessionDecorator(s, self.adapter)
+                decorator.setCookies([SessionDecoratorCookie()])
+                sessionObjPrx = self.adapter.addWithUUID(decorator)
+                sessionPrx = AsteriskSCF.SessionCommunications.V1.SessionPrx.uncheckedCast(sessionObjPrx)
+                decorator.setProxy(sessionObjPrx.ice_getIdentity())
+                try:
+                    sessionBridge.replaceSession(s, [sessionPrx])
+                except Ice.Exception as ex:
+                    print "Exception while trying to do stuff with things: " + ex.what()
+    def sessionsRemoved(self, sessionBridge, sessions, current = None):
+        for s in sessions:
+            print "Session %s removed from bridge %s" % (s.ice_getIdentity().name, sessionBridge.ice_getIdentity().name)
+    def stopped(self, sessionBridge, current = None):
+        print "Bridge %s stopped" % (sessionBridge.ice_getIdentity().name)
+    def stopping(self, sessionBridge, current = None):
+        print "Bridge %s stopping" % (sessionBridge.ice_getIdentity().name)
+
+class DecoratorApp(Ice.Application):
+    def usage(self):
+        print "Usage: " + self.appName()
+        print "Listen to all sessions and bridges"
+        print ""
+        print "Options:"
+        print "-h, --help              Display help information"
+        print "-l, --locator=PROXY     Use specified proxy for Service locator"
+        print "                        Default: 'LocatorService:tcp -p 4411"
+        
+    def run(self, args):
+        
+        try:
+            opts, arguments = getopt.getopt(args[1:], "hl:", ["help", "locator="])
+        except getopt.GetoptError, err:
+            print str(err)
+            self.usage()
+            return -1
+
+        # The default value for the service locator is to assume it's running
+        # on the same machine on port 4411
+        serviceLocatorString = "LocatorService:tcp -p 4411"
+
+        for o, a in opts:
+            if o in ("-h", "--help"):
+                self.usage()
+                return -1
+            if o in ("-l", "--locator"):
+                serviceLocatorString = a
+
+        print "Starting " + self.appName()
+
+        # First thing we're going to do is create an object adapter.
+        adapter = self.communicator().createObjectAdapterWithEndpoints("ExampleDecorator", "default")
+
+        bridgeListenerObjPrx = adapter.addWithUUID(BridgeListener(adapter))
+        print "Added BridgeListener to our object adapter"
+
+        adapter.activate()
+        print "Activated our object adapter"
+
+        # Now we need to find the bridge manager. We use the service locator for this.
+        # First, we get a proxy to the service locator.
+        serviceLocator = AsteriskSCF.Core.Discovery.V1.ServiceLocatorPrx.checkedCast(self.communicator().stringToProxy(serviceLocatorString))
+        
+        if not serviceLocator:
+            print "Couldn't get the service locator"
+            return -1
+
+        # Next, we need to  populate the parameters for the service locator to be able
+        # to find the bridge manager.
+        serviceLocatorParams = AsteriskSCF.Core.Discovery.V1.ServiceLocatorParams()
+        serviceLocatorParams.category = AsteriskSCF.SessionCommunications.V1.BridgeServiceDiscoveryCategory
+
+        # Now we locate the bridge manager
+        try:
+            service = serviceLocator.locate(serviceLocatorParams)
+        except Ice.Exception as ex:
+            print "Exception while attempting to locate BridgeManager: " + ex.what()
+        self.bridgeManager = AsteriskSCF.SessionCommunications.V1.BridgeManagerPrx.checkedCast(service)
+
+        if not self.bridgeManager:
+            print "Couldn't get the bridge manager"
+            return -1
+
+        print "Acquired proxy to the BridgeManager"
+
+        # We add ourself as a default bridge listener. This means that we will automatically
+        # have ourself added as a listener to any bridge that gets created.
+        self.bridgeListenerPrx = AsteriskSCF.SessionCommunications.V1.BridgeListenerPrx.uncheckedCast(bridgeListenerObjPrx)
+        try:
+            self.bridgeManager.addDefaultBridgeListener(self.bridgeListenerPrx)
+        except Ice.Exception as ex:
+            print "Exception while attempting to add ourself as a DefaultBridgeListener: " + ex.what()
+
+        print "Added ourself as a default BridgeListener"
+
+        # We want to remove ourself as listeners when we terminate, so we need to hook into the
+        # termination signal. Ice.Application provides a nice way to do this.
+        self.callbackOnInterrupt()
+        # And now we wait...
+        self.communicator().waitForShutdown()
+
+        if self.interrupted():
+            print self.appName() + ": terminating"
+
+        return 0
+
+    def interruptCallback(self, sig):
+        # Ideally, we would keep track of all sessions and bridges we
+        # currently set up as listeners on and remove ourselves as listeners.
+        # For the sake of clarity and efficiency, we simply remove ourselves
+        # as a default bridge listener and a bridge manager listener.
+        print "Removing ourself as a default bridge listener"
+        try:
+            self.bridgeManager.removeDefaultBridgeListener(self.bridgeListenerPrx)
+        except Ice.Exception as ex:
+            print "Error trying to remove ourself as a default bridge listener: " + ex.what()
+
+        Ice.Application._destroyOnInterruptCallback(sig)
+
+app = DecoratorApp()
+sys.exit(app.main(sys.argv))

-----------------------------------------------------------------------


-- 
asterisk-scf/examples.git



More information about the asterisk-scf-commits mailing list