# Path: swfconduit/event.py
# class Event( object ):
#     id = 0
#     timestamp = None
# 
#     def __init__( self ):
#         self.id         = getrandbits(29) # Size of an AMF3 integer field
#         self.timestamp  = datetime.now()
#         pass
# 
#     def fire( self, server, session ):
#         """ Perform the event's task """
#         pass
# 
#     # Tried this for AS3 readObject problem. May need in future
#     #def __readamf__( self, input ):
#     #    self.timestamp = input.readObject()
#     #    self.payload   = input.readObject()
#     #
#     #def __writeamf__( self, output ):
#     #    output.writeObject( self.timestamp )
#     #    output.writeObject( self.payload )
# 
#     def reply( self, cls, *args ):
#         """ Create a reply with the given class. Will set the reply's id field appropriately """
#         reply = cls(*args)
#         reply.id = self.id
#         return reply
# 
# Path: swfconduit/server.py
# class Server( twisted.internet.protocol.Factory ):
#     protocol        = swfconduit.protocol.Protocol
#     session         = Session
#     config          = {}
#     sessions        = {}
# 
#     # Prepare a callLater to override for testing
#     callLater   = reactor.callLater
# 
#     def __init__( self, cfg=None ):
#         """ Init a new Server with the given configuration """
#         self.config = cfg
# 
#     def openSession( self, protocol ):
#         """ Open a user session """
#         session = self.session( self, protocol )
#         self.sessions[ session.session_id ] = session
#         session.open()
#         return session
# 
#     def closeSession( self, session ):
#         """ A session is closing, clean up after it """
#         if ( session.session_id in self.sessions ):
#             del( self.sessions[ session.session_id ] )
#         if ( session.protocol.transport is not None ):
#             # Could be none in the case of tests
#             session.protocol.transport.loseConnection()
#         pass
# 
#     def fireEvent( self, event, session ):
#         """ Fire the event """
#         try:
#             #print event
#             return event.fire( self, session )
#         except Exception as e:
#             traceback.print_exc(file=sys.stdout)
#             # Send back an error message to the client
#             reply = event.reply( ErrorEvent, e )
#             session.sendEvent( reply )
# 
#     def sendGlobalEvent( self, event ):
#         """ Send an event to all active sessions """
#         pass
# 
# Path: swfconduit/loader.py
# class Loader( object ):
#     """ Load up a swfconduit 
# 
#     This class creates all the Twisted services needed to run the SwfConduit server.
#     """
# 
#     servers = []
#     """ The list of servers we made """
# 
#     def add_server( self, config ):
#         """Create the server from the given config
# 
#         Valid configuration keys are:
# 
#         * server    The swfconduit.server.Server instance to add.
#         * proto     The protocol this server uses. Currently only "tcp" is supported.
#         * port      The port this server should listen on.
#         """
#         # Start the appropriate listeners and set up connection handlers
#         if "package" in config: # package is deprecated and will be removed
#             module  = _get_mod( config["package"] )
#             cls = module.Server
#             # Init a new server
#             server = cls(config)
#         elif "server" in config:
#             assert isinstance( config['server'], swfconduit.server.Server )
#             server = config["server"]
#         self.servers.append( {
#             "port": config['port'],
#             "proto": config['proto'],
#             "server": server,
#         } )
# 
#     def add_services( self, service_parent ):
#         """ Add services to the given twisted service_parent.
# 
#         This method is called automatically by get_application().
#         """
# 
#         # Create the service to serve the socket policy
#         swfconduit.socketpolicy.add_service( service_parent, './socket-policy.xml' )
# 
#         for server in self.servers:
#             port    = int(server["port"])
#             proto   = server["proto"]
#             if "tcp" in proto:
#                 # Add a TCP listener to our server
#                 twisted.application.internet.TCPServer( port, server['server'] ).setServiceParent( service_parent )
# 
#     def load_from_config( self, filename ):
#         """ Load settings from the configuration file """
#         cfg = ConfigParser.SafeConfigParser()
#         cfg.readfp( open( filename ) )
# 
#         # Each section defines a plugin
#         for sect in cfg.sections():
#             # Collect all the configuration
#             config  = {}
#             for key, value in cfg.items( sect ):
#                 config[key] = value
#             self.add_server( config )
# 
#     def get_application( self ):
#         """ Get the twisted application with all the plugin services added.
# 
#         This should be the last thing you do in your twisted.tac file.
#         """
#         service_parent = twisted.application.service.MultiService()
# 
#         self.add_services( service_parent )
# 
#         application = twisted.application.service.Application( "SwfConduit" )
#         service_parent.setServiceParent( application )
#         return application


import os, sys, types
import pyamf
from swfconduit.event import Event
from swfconduit.server import Server
from swfconduit.loader import Loader


# Add SwfConduit lib directory
current_dir  = os.getcwd()
sys.path.append( os.path.normpath( os.path.join( current_dir, "..", ".." ) ) )

# Create our event class
class ChatEvent( Event ):
    # The nickname of the user sending the event
    nickname = ""
    # The message
    text = ""

    def fire( self, server, session ):
        # We recieved a chat event, send it to every other person
        print "CHAT {}> {}".format(self.nickname, self.text)

# Path: swfconduit/event.py
# class Event( object ):
#     id = 0
#     timestamp = None
# 
#     def __init__( self ):
#         self.id         = getrandbits(29) # Size of an AMF3 integer field
#         self.timestamp  = datetime.now()
#         pass
# 
#     def fire( self, server, session ):
#         """ Perform the event's task """
#         pass
# 
#     # Tried this for AS3 readObject problem. May need in future
#     #def __readamf__( self, input ):
#     #    self.timestamp = input.readObject()
#     #    self.payload   = input.readObject()
#     #
#     #def __writeamf__( self, output ):
#     #    output.writeObject( self.timestamp )
#     #    output.writeObject( self.payload )
# 
#     def reply( self, cls, *args ):
#         """ Create a reply with the given class. Will set the reply's id field appropriately """
#         reply = cls(*args)
#         reply.id = self.id
#         return reply
# 
# Path: swfconduit/server.py
# class Server( twisted.internet.protocol.Factory ):
#     protocol        = swfconduit.protocol.Protocol
#     session         = Session
#     config          = {}
#     sessions        = {}
# 
#     # Prepare a callLater to override for testing
#     callLater   = reactor.callLater
# 
#     def __init__( self, cfg=None ):
#         """ Init a new Server with the given configuration """
#         self.config = cfg
# 
#     def openSession( self, protocol ):
#         """ Open a user session """
#         session = self.session( self, protocol )
#         self.sessions[ session.session_id ] = session
#         session.open()
#         return session
# 
#     def closeSession( self, session ):
#         """ A session is closing, clean up after it """
#         if ( session.session_id in self.sessions ):
#             del( self.sessions[ session.session_id ] )
#         if ( session.protocol.transport is not None ):
#             # Could be none in the case of tests
#             session.protocol.transport.loseConnection()
#         pass
# 
#     def fireEvent( self, event, session ):
#         """ Fire the event """
#         try:
#             #print event
#             return event.fire( self, session )
#         except Exception as e:
#             traceback.print_exc(file=sys.stdout)
#             # Send back an error message to the client
#             reply = event.reply( ErrorEvent, e )
#             session.sendEvent( reply )
# 
#     def sendGlobalEvent( self, event ):
#         """ Send an event to all active sessions """
#         pass
# 
# Path: swfconduit/loader.py
# class Loader( object ):
#     """ Load up a swfconduit 
# 
#     This class creates all the Twisted services needed to run the SwfConduit server.
#     """
# 
#     servers = []
#     """ The list of servers we made """
# 
#     def add_server( self, config ):
#         """Create the server from the given config
# 
#         Valid configuration keys are:
# 
#         * server    The swfconduit.server.Server instance to add.
#         * proto     The protocol this server uses. Currently only "tcp" is supported.
#         * port      The port this server should listen on.
#         """
#         # Start the appropriate listeners and set up connection handlers
#         if "package" in config: # package is deprecated and will be removed
#             module  = _get_mod( config["package"] )
#             cls = module.Server
#             # Init a new server
#             server = cls(config)
#         elif "server" in config:
#             assert isinstance( config['server'], swfconduit.server.Server )
#             server = config["server"]
#         self.servers.append( {
#             "port": config['port'],
#             "proto": config['proto'],
#             "server": server,
#         } )
# 
#     def add_services( self, service_parent ):
#         """ Add services to the given twisted service_parent.
# 
#         This method is called automatically by get_application().
#         """
# 
#         # Create the service to serve the socket policy
#         swfconduit.socketpolicy.add_service( service_parent, './socket-policy.xml' )
# 
#         for server in self.servers:
#             port    = int(server["port"])
#             proto   = server["proto"]
#             if "tcp" in proto:
#                 # Add a TCP listener to our server
#                 twisted.application.internet.TCPServer( port, server['server'] ).setServiceParent( service_parent )
# 
#     def load_from_config( self, filename ):
#         """ Load settings from the configuration file """
#         cfg = ConfigParser.SafeConfigParser()
#         cfg.readfp( open( filename ) )
# 
#         # Each section defines a plugin
#         for sect in cfg.sections():
#             # Collect all the configuration
#             config  = {}
#             for key, value in cfg.items( sect ):
#                 config[key] = value
#             self.add_server( config )
# 
#     def get_application( self ):
#         """ Get the twisted application with all the plugin services added.
# 
#         This should be the last thing you do in your twisted.tac file.
#         """
#         service_parent = twisted.application.service.MultiService()
# 
#         self.add_services( service_parent )
# 
#         application = twisted.application.service.Application( "SwfConduit" )
#         service_parent.setServiceParent( application )
#         return application


# Path: examples/chat/chat.py
import os, sys, types
import pyamf
from swfconduit.event import Event
from swfconduit.server import Server
from swfconduit.loader import Loader



# Add SwfConduit lib directory
current_dir  = os.getcwd()
sys.path.append( os.path.normpath( os.path.join( current_dir, "..", ".." ) ) )

# Create our event class
class ChatEvent( Event ):
    # The nickname of the user sending the event
    nickname = ""
    # The message
    text = ""

    def fire( self, server, session ):
        # We recieved a chat event, send it to every other person
        print "CHAT {}> {}".format(self.nickname, self.text)

        for session_id in server.sessions: