wcc_protocol.py :  » GUI » PmwContribD » PmwContribD-r2_0_2 » SampleApps » WhackyChat » Client » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » GUI » PmwContribD 
PmwContribD » PmwContribD r2_0_2 » SampleApps » WhackyChat » Client » wcc_protocol.py
#!/usr/bin/env python
#
# $Id: wcc_protocol.py,v 1.3 2001/11/03 11:05:22 doughellmann Exp $
#
# Copyright 2001 Doug Hellmann.
#
#
#                         All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of Doug
# Hellmann not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
#
# DOUG HELLMANN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
# NO EVENT SHALL DOUG HELLMANN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

"""Class to handle protocol for wacky server.

"""

__rcs_info__ = {
    #
    #  Creation Information
    #
    'module_name'  : '$RCSfile: wcc_protocol.py,v $',
    'rcs_id'       : '$Id: wcc_protocol.py,v 1.3 2001/11/03 11:05:22 doughellmann Exp $',
    'creator'      : 'Doug Hellmann <doug@hellfly.net>',
    'project'      : 'PmwContribD',
    'created'      : 'Sun, 27-May-2001 12:07:19 EDT',

    #
    #  Current Information
    #
    'author'       : '$Author: doughellmann $',
    'version'      : '$Revision: 1.3 $',
    'date'         : '$Date: 2001/11/03 11:05:22 $',
}

#
# Import system modules
#
import socket
import string
import time
import re
import select
import os
import sys


#
# Import Local modules
#


#
# Module
#


debug = 0

class WackyProtocolError(IOError):
    def __init__(self, server='Unknown server', *args):
        apply(IOError.__init__ , (self,) + args)
        return



    
class WackyConnection:
    EOLN=chr(0x03)
    UNSOLICITED_MARKER='*'
    ERROR_MARKER='-'
    RESPONSE_MARKER='+'
    
    _MESSAGES = ( 'MOTD',
                  'MESG',
                  'CAST',
                  'UPDT',
                  'ERR',
                  )
    
    def __init__(self, hostname, port, userid, password):
        #
        # Get the socket to the server.
        #
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._sock.connect(hostname, port)
        self._from_file = self._sock.makefile('rb', 0)
        self._to_file = self._sock.makefile('wb', 0)
        #self._sock.setblocking(0)
        #
        # Create a queue to hold the unsolicited
        # messages we get from the server.
        #
        self._unsolicited_message_queue = []
        #
        # Keep up with the callbacks registered
        # for various unsolicited messages.
        #
        self._unsolicited_handlers = {}
        #
        # Create a read buffer for asynchronous reading
        #
        self._read_buffer = ''
        #
        # Try to log on as the user we claim to be
        #
        self.userid = userid
        self.password = password
        self._login()
        return

    ##
    ## IMPLEMENTATION METHODS
    ##
    def _login(self):
        """
        Will get USER> followed by PASS> from the server.
        Need to respond accordingly.  We don't wait for
        the prompt, though.  We just send our login info
        and then read past the EOLNs that we'll get back.
        """
        self._send(self.userid)
        response = self._readline()
        #response = self.poll()
        if debug: print 'USER response: "%s"' % response
        if response and response[0] == '-':
            # error
            raise WackyProtocolError(self, response[5:])
        self._send(self.password)
        response = self._readline()
        #response = self.poll()
        if debug: print 'PASS response: "%s"' % response
        if not response or (response[0] == '-'):
            # error
            raise WackyProtocolError(self, 'Password not accepted.', response)
        return

    def _readline(self):
        value=''
        value_is_returnable=0
        while not value_is_returnable:
            if debug >= 2: print 'reading...',
            newread = self._from_file.read(1)
            #newread = self._from_file.read(128)
            #try:
            #    newread = self._sock.recv(128)
            #except socket.error:
            #    newread = ''
            if debug >= 2: print ' [%s]' % newread
            if (not newread) or (newread == self.EOLN):
                #
                # Figure out if what we have should be
                # returned or just put in the unsolicited
                # queue.
                #
                if value and value[0] == self.UNSOLICITED_MARKER:
                    self._unsolicitedMessage(value)
                    value = ''
                    value_is_returnable = 0
                else:
                    value_is_returnable = 1
            else:
                value = value + newread
        if debug >= 2: print 'RESPONSE MESSAGE: "%s"' % value
        return value

    def poll(self):
        """
        Poll the server for new messages (check the incoming socket
        queue).  If there are any unsolicited messages for which
        handlers are registered, those handlers will be called.
        """
        got_whole_line=0
        while not got_whole_line:
            #sys.stderr.write(' <POLL> ')
            ins, outs, excepts = select.select( [ self._from_file ],
                                                [],
                                                [],
                                                0 )
            if not ins:
                break
            newread = self._from_file.read(1)
            #sys.stderr.write(newread)
            if (not newread) or (newread == self.EOLN):
                #
                # Figure out if what we have should be
                # returned or just put in the unsolicited
                # queue.
                #
                if (self._read_buffer and
                    self._read_buffer[0] == self.UNSOLICITED_MARKER):
                    #sys.stderr.write('\n')
                    self._unsolicitedMessage(self._read_buffer)
                    self._read_buffer = ''
                    got_whole_line = 1
                elif not newread:
                    break
                else:
                    if debug >= 2:
                        print 'UH OH, why did I see "%s" with "%s"?' \
                              % (self._read_buffer, newread)
                    self._read_buffer = self._read_buffer + newread
            else:
                self._read_buffer = self._read_buffer + newread
        #
        # Return pending messages that were not sent to a
        # handler function.
        #
        pending = self._unsolicited_message_queue
        self._unsolicited_message_queue = []
        return pending
        
    #
    # Parsing regular expressions
    #
    _patterns = (
        re.compile(
        r'\*MESG FROM (?P<type>USER|ADMIN) (?P<nick>\S+):(?P<uid>\S+) "(?P<msg>.*)"$',
        re.DOTALL | re.MULTILINE ),
        
        re.compile(
        r'\*CAST FROM (?P<type>USER|ADMIN) (?P<nick>\S+):(?P<uid>\S+) "(?P<msg>[^"]*)"',
        re.DOTALL | re.MULTILINE ),
        
        re.compile(r'\*MOTD (?P<motd>.*)', re.DOTALL | re.MULTILINE ),
        
        re.compile(
        r'\*UPDT (?P<command>USER)\s+(?P<nick>\S+):(?P<uid>\S+)\s+(?P<state>ONLINE|OFFLINE)',
        re.DOTALL | re.MULTILINE ),
        
        re.compile(
        r'\*UPDT (?P<command>DISP) (?P<nick>\S+):(?P<uid>\S+) (?P<state>ONLINE|OFFLINE|AWAY|NA|OCCUPIED|DND|PRIVACY)',
                   re.DOTALL | re.MULTILINE ),
        
        re.compile(r'\*UPDT (?P<command>DISP) (?P<nick>\S+):(?P<uid>\S+)',
                   re.DOTALL | re.MULTILINE ),
        re.compile(r'\*UPDT (?P<command>NICK) (?P<nick>\S+):(?P<uid>\S+)',
                   re.DOTALL | re.MULTILINE ),
        re.compile(r'\*UPDT (?P<command>SERV) (?P<subcommand>KICK) (?P<message>.*)',
                   re.DOTALL | re.MULTILINE ),
        re.compile(r'\*UPDT (?P<command>SERV) (?P<subcommand>DOWN) (?P<message>.*)',
                   re.DOTALL | re.MULTILINE ),
        re.compile(r'\*UPDT (?P<command>SERV) (?P<subcommand>DISCONNECT)',
                   re.DOTALL | re.MULTILINE ),

        re.compile(r'-ERR (?P<message>.*)', re.DOTALL | re.MULTILINE ),
        re.compile(r'-DISP (?P<message>.*)', re.DOTALL | re.MULTILINE ),
        re.compile(r'-MESG (?P<message>.*)', re.DOTALL | re.MULTILINE ),
        )
    
    def _parseUnsolicitedMessage(self, messageText):
        """
        Parse the unsolicited messages into tuples to be
        passed as arguments to their handlers.
        """
        parts = string.split(messageText)
        msg = parts[0][1:]
        if debug >= 2: print 'PARSING UNSOLICITED MESSAGE: "%s"' % msg
        args = None
        for pat in self._patterns:
            matchObj = pat.search(messageText)
            if matchObj:
                args = matchObj.groups()
                break
        if not args:
            raise ValueError('Could not match with re (%s)' \
                             % messageText)
        if debug >= 2: print 'MESSAGE ARGS ARE: "%s"' % str(args)
        return (msg, ) + args
    
    def _unsolicitedMessage(self, messageText):
        """
        This method is called whenever an unsolicited message arrives.
        These messages could be received at any time, including when
        we expect to see a response to a query we have made.
        """
        if debug: print 'UNSOLICITED MESSAGE: "%s"' % messageText
        parsed_message = self._parseUnsolicitedMessage(messageText)
        message_keyword = parsed_message[0]
        message_args = parsed_message[1:]
        if debug: print 'CHECKING KEYWORD: "%s"' % message_keyword
        if self._unsolicited_handlers.has_key(message_keyword):
            try:
                apply(self._unsolicited_handlers[message_keyword], message_args)
            except:
                print 'Could not handle "%s"' % messageText
                raise
        else:
            if debug: print 'STORING UNSOLICITED MESSAGE: "%s"' % messageText
            self._unsolicited_message_queue.append(parsed_message)
        return
    
    def _send(self, message):
        """
        Send a command message to the server in the right format.
        """
        transmission=str(message) + self.EOLN
        if debug: print 'SEND: "%s"' % str(transmission)
        try:
            self._to_file.write(str(message))
            self._to_file.write(self.EOLN)
            self._to_file.flush()
        except ValueError:
            pass
        return

    def __del__(self):
        self.quit()
        return

    ##
    ## METHODS THE USER MIGHT WANT TO CALL
    ##
    def registerMessageHandler(self, message, handler):
        """
        Let the user tell us how to handle certain messages.
        """
        if message not in self._MESSAGES:
            raise ValueError('Message (%s) must be one of :%s' \
                             % (message, self._MESSAGES))
        self._unsolicited_handlers[message] = handler
        return

    ##
    ## PROTOCOL METHODS
    ##
    def quit(self):
        """
        Disconnect from the server.
        """
        #print 'Quitting...'
        try:
            self._send('QUIT')
            self._to_file.close()
            self._from_file.close()
            self._sock.close()
        except AttributeError:
            pass
        except ValueError:
            pass
        return

    def stat(self):
        """
        Returns a list of users that are logged on to the
        system right now.
        """
        self._send('STAT')
        response = self._readline()
        if response and (response[0] == '+'):
            uservals=response[6:]
            recs=string.split(uservals, ',')
            reclist = map(lambda x: tuple(string.split(x, ':')), recs)
            reclist = filter(lambda x: len(x) > 1, reclist)
        elif response and response[0] == '-':
            # why would I ever get a negative response from stat?
            reclist = []
        else:
            # what?
            print 'STAT responded with "%s"' % response
            reclist = [ response ]
        return reclist

    def mesg(self, uid, message):
        """
        Send a message to a single user.
        """
        self._send('MESG %s %s' % (uid, message))
        response = self._readline()
        if not response or response[0] == '-':
            raise WackyProtocolError(self, 'MESG', uid, message, response)
        return

    def cast(self, message):
        """
        Broadcast a message to all users online.
        """
        self.mesg(0, message)
        return

    #
    # Alias cast to broadcast
    #
    broadcast = cast

    info_re = re.compile(
        r'\+INFO (?P<uid>\S+) (?P<nick>\S+) (?P<email>\S*) (?P<status>\S+)'
        )

    def info(self, uid):
        """
        Get information about a user.
        """
        self._send('INFO %s' % uid)
        response = self._readline()
        if response[0] == '-':
            raise WackyProtocolError(self, 'INFO', uid, response)
        #parts=string.split(response)
        matchObj = self.info_re.match(response)
        if not matchObj:
            raise WackyProtocolError(self, 'INFO', uid, response)
        parts = matchObj.groups()
        #print 'Match groups: ', parts
        return parts


    ##
    ## USER PREFERENCE COMMANDS
    ##
    def nick(self, nickname):
        """
        Set the nickname for the current user.
        """
        self._send('NICK %s' % nickname)
        response = self._readline()
        if response and response[0] == '-':
            raise WackyProtocolError(self, 'NICK', nickname, response)
        return

    def mail(self, email):
        """
        Set the email address for the current user.
        """
        self._send('MAIL %s' % email)
        response = self._readline()
        if response[0] == '-':
            raise WackyProtocolError(self, 'MAIL', email, response)
        return

    def passwd(self, newPassword):
        """
        Change the password for the current user.
        """
        self._send('PASS %s %s' % (self.password, newPassword))
        response = self._readline()
        if response[0] == '-':
            raise WackyProtocolError(self, 'PASS', response)
        else:
            self.password = newPassword
        return

    def disp(self, disposition):
        """
        Change user's disposition.  Can be one of
        (ONLINE|AWAY|NA|OCCUPIED|DND|PRIVACY).
        Currently only ONLINE and AWAY are supported.
        """
        self._send('DISP %s' % disposition)
        response = self._readline()
        if response[0] == '-':
            raise WackyProtocolError(self, 'DISP', disposition, response)
        return
    


    
if __name__ == '__main__':

    stop_polling = 0
    
    def motd_handler(message):
        print 'test_handler(MOTD): %s' % message
        return

    def broadcast_handler(fromType, fromName, fromID, message):
        print 'test_handler(CAST): from %s[%s](%s): %s' \
              % (fromName, fromID, fromType, message)
        return

    def mesg_handler(fromType, fromName, fromID, message):
        print 'test_handler(MESG): from %s[%s](%s): %s' \
              % (fromName, fromID, fromType, message)
        return

    def updt_handler(*args):
        global stop_polling
        print 'test_handler(UPDT): ', args
        if args[0] == 'SERV' and args[1] in ('DISCONNECT', 'KICK'):
            stop_polling = 1
        return

    def err_handler(*args):
        global stop_polling
        print 'ERR: ', args
        stop_polling = 1
        raise apply(ValueError, args)
        return
    

    try:
        server = WackyConnection( hostname='localhost',
                                  port=2980,
                                  #userid=1002,
                                  userid=os.environ['WACKY_USER'],
                                  #password='doug',
                                  password=os.environ['WACKY_PASSWORD'],
                                  )
    except WackyProtocolError, msg:
        print 'There was an error: "%s"' % msg
        sys.exit(1)
        
    server.registerMessageHandler('MOTD', motd_handler)
    server.registerMessageHandler('CAST', broadcast_handler)
    server.registerMessageHandler('MESG', mesg_handler)
    server.registerMessageHandler('UPDT', updt_handler)
    server.registerMessageHandler('ERR', err_handler)
    
    users_online = server.stat()
    print 'User Status:'
    for moniker, uid, status in users_online:
        print '\t%s (%s) [ %s ]' % (moniker, uid, status)
    server.cast('test a broadcast message')
    try:
        server.mesg(1002, 'hi there\nline two')
    except WackyProtocolError, msg:
        pass
    print 'Check 1002'
    data = server.info(1002)
    print '\t', data
    print 'New mail address and nickname'
    server.mail('newaddress@server.com')
    server.nick('atnight')
    print '\t', server.info(1002)
    print 'Reset mail'
    server.mail('hellmann@gnncast.net')
    server.nick('Doug')
    print '\t', server.info(1002)
    print 'Change disposition'
    server.disp('AWAY')
    print '\t', server.info(1002)
    try:
        print 'Bad disposition setting'
        server.disp('DND')
        print '\t', server.info(1002)
    except WackyProtocolError, msg:
        print '\tException: %s' % msg
    print 'Back online'
    server.disp('ONLINE')
    print '\t', server.info(1002)
    print 'entering polling loop...'
    while not stop_polling:
        server.poll()
        time.sleep(2)
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.