File: chatclient.py

package info (click to toggle)
chatplus 0.1-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 204 kB
  • ctags: 156
  • sloc: python: 607; ansic: 397; xml: 190; makefile: 81; sh: 6
file content (344 lines) | stat: -rw-r--r-- 12,364 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/python

#~ JollyBOX chat+ client
#~ Copyright (C) 2006 Thomas Jollans
#~
#~ This program is free software; you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License version 2 as 
#~ published by the Free Software Foundation
#~
#~ 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, write to the Free Software
#~ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

def printwrapper ( str ):
	print str

# --- IMPORTS
from socket import *
import select
import sys
import time
import os
import re


# --- GLOBAL VARIABLES ---
# list of functions to be called in main loop
loopfuncz = []    

# --- CONSTANTS
TJC_DEFAULT_PORT = 4056

# --- CONSTANTS FOR ChatRoom ---
# passed on to 'info' callback
TJC_INFO_ROOMNAME = 0    # 'data' is the name of the room
TJC_INFO_CLIENTS = 1    # 'data' is a list containing the names of the connected clients ; can be used for ChatRoom.request_info
TJC_INFO_VERSION = 2    # 'data' is a string containing the server's version ; can be used for ChatRoom.request_info

# passed on to 'user_status' callback
TJC_USER_NEW = 0    # 'data' is the name of the user
TJC_USER_GONE = 1    # 'data' is the name of the user


class ChatRoom:
    """A TjChat chat room"""
    
    # --- CONSTRCTOR ---
    
    def __init__ ( self, server, port, name ):
        # default callbacks
        self.__printfn = printwrapper
        self.__msgfn = self.__display_msg
        self.__userstatfn = self.__printuserstat
        self.__infofn = self.__printinfo
        self.__privarrivfn = self.__priv_arrives
        self.__privdepartfn = self.__priv_departs
        self.__shutdownfn = sys.exit
        
        self.__alive = True
        self.__buf = []
        self.__sock = socket(AF_INET, SOCK_STREAM)
        self.__printfn ( "-- socket initialized" )
        self.__sock.connect ( ( gethostbyname ( server ), port ) )
        self.__name = name
        self.__server = getfqdn ( server )
        self.__port = port

        self.__server_caps = []
        
        self.__name = name
        self.__proto = TjChatProtocol(self)
        self.__proto.send_name()
        print "--connected and sent initial info"
    
    # --- CALLBACKS ---
    
    def print_cb ( self, fn ):
        """callback prints text on preferred medium, equivalent to 'print'
        callback signature:
            def printfn ( text )"""
        self.__printfn = fn
        
    def msg_cb ( self, fn ):
        """notifies the arrival or departure of a standard message.
        callback signature:
            def msgfn ( author, message )"""
        self.__msgfn = fn
        
    def user_status_cb ( self, fn ):
        """notifies of a user-related event, e.g. a new user connecting.
        callback signature:
            def userstatfn ( type, data )
        where type is one of the TJC_USER_* constants. the type of data is denoted
        next to the constant definition."""
        self.__userstatfn = fn
    
    def info_cb ( self, fn ):
        """notifies the arrival of informational data.
        callback signature:
            def infofn ( type, data )
        where type is one of the TJC_INFO_* constants. the type of data is denoted
        next to the constant definition."""
        self.__infofn = fn
        
    def private_arriv_cb ( self, fn ):
        """notifies the arrival of a private message.
        callback signature:
            def privmsgfn ( author, message )"""
        self.__privarrivfn = fn
        
    def private_depart_cb ( self, fn ):
        """notifies the departure of a private message.
        callback signature:
            def privdepartfn ( recieptent, message )"""
        self.__privdepartfn = fn
        
    def shutdown_cb ( self, fn ):
        """called when the server closed the connection or the connection is not writable.
        callback signature:
            def privdepartfn ( )"""
        self.__shutdownfn = fn
        
    # --- FUNCTIONS FOR ChatRoom USAGE ---
    
    def main_iteration ( self ):
        if ( self.__alive ):
            r, w, ex = select.select ( [self.__sock], [self.__sock], [],0 )
            if r:
                self.__proto.parse ( r[0].recv(256) )
            if w and self.__buf:
                # workaround around bad protocol design
                # may fail on slow connexions
                time.sleep (0.1)
                
                writethis = self.__buf.pop()
                try:
                    w[0].send( writethis )
                except:
                    # write error. let's commit suicide !
                    self.disconnect()
                    self.__shutdownfn()
    
    def disconnect ( self ):
        self.__alive = False
        self.__sock.close ()
        
    def send_msg ( self, msg ):
        self.__proto.send_msg(msg)
        self.__msgfn ( self.__name, msg )
    
    def send_private_msg ( self, to, msg ):
        self.__proto.send_private_msg(to, msg)
        self.__privdepartfn ( to, msg )
    
    def request_info ( self, type ):
        if type == TJC_INFO_CLIENTS:
            self.__proto.send_special( "#client-list" )
        elif type == TJC_INFO_VERSION:
            self.__proto.send_special( "#server-version" )
    
    def get_name ( self ):
        return self.__name
    
    def get_server ( self ):
        return self.__server
    
    def get_port ( self ):
        return self.__port
    
    # --- INTERNAL FUNCTIONS ---
    
    def __handle_special ( self, code, string ):
        if code == "welcome_to_room":
            self.__infofn ( TJC_INFO_ROOMNAME, string )
        elif code == "new":
            self.__userstatfn ( TJC_USER_NEW, string )
        elif code == "hasleft":
            self.__userstatfn ( TJC_USER_GONE, string )
        elif code == "version":
            if '//' in string:
                ver, meta = string.split('//', 1)
            else:
                ver,meta = string,''
            self.__server_caps = meta.split()
            self.__infofn ( TJC_INFO_VERSION, str(ver) )
            # protocols ?
            if 'EXT:protocol' in self.__server_caps:
                self.__proto.send_special( ".protocol-list" )
                print "protocol list requested"
            else:
                print "protocols extension not supported. (%s)" % self.__server_caps
        elif code == "protocol-list":
            if 'chat+pr0' in string: #something we like and understand.
                self.__proto.send_special( ".protocol-set", "chat+pr0" )
                print "switching to chat+pr0"
            else:
                print string
        elif code == "protocol-ok":
            if string == "chat+pr0":
                self.__proto = ChatPlusProtocol0(self)
                print "switched to chat+pr0"
        elif code == "names":
            if not isinstance(string,list): string = [string]
            self.__infofn ( TJC_INFO_CLIENTS, string )
        elif code == "close":
            # the server is telling me to commit suicide.
            self.disconnect()
            self.__shutdownfn()
        else:
            self.__printfn ( "SPECIAL [ " + code + " ]   " + string )
        
    def __buffer ( self, str ):
        self.__buf.insert ( 0, str )
        
    # --- CALLBACK FALLBACKS
    
    def __display_msg ( self, author, msg ):
        self.__printfn ( "<" + author + ">   " + msg )
        
    def __printuserstat ( self, type, data ):
        if type == TJC_USER_NEW:
            self.__printfn ( "NEW USER: " + data )
        elif type == TJC_USER_GONE:
            self.__printfn ( "USER HAS LEFT: " + data )
        else:
            self.__printfn ( "USER STATUS INFO CODE " + str (type) + ": " + str (data ) )
            
    def __printinfo ( self, type, data ):
        if type == TJC_INFO_ROOMNAME:
            self.__printfn ( "WELCOME TO ROOM " + data )
        elif type == TJC_INFO_CLIENTS:
            self.__printfn ( "CONNECTED CLIENTS:" + ", ".join ( data ) )
        elif type == TJC_INFO_VERSION:
            self.__printfn ( "SERVER VERSION IS: " + data )
        else:
            self.__printfn ( "INFORMATION MSG CODE " + str (type) + ": " + str (data ) )
            
    def __priv_arrives ( self, author, msg ):
        self.__printfn ( "PRIVATE FROM " + author + ": " + msg )
        
    def __priv_departs ( self, recpt, msg ):
        self.__printfn ( "PRIVATE TO " + recpt + ": " + msg )

class TjChatProtocol:
    def __init__(self, room):
        self.room = room

    def __buffer(self, str):
        self.room._ChatRoom__buffer(str.encode('utf-16-le'))

    def send_msg ( self, msg ):
        self.__buffer ( "$" + self.room._ChatRoom__name + ";" + msg + "$" )
    
    def send_private_msg ( self, to, msg ):
        self.__buffer ( "$" + self.room._ChatRoom__name + "~" + to + ";" + msg + "$")

    def send_special ( self, code, content = None ):
        if isinstance(content, basestring): code = code+';'+content
        if isinstance(content, list): code = code+';'+'~'.join(content)
        print repr("$@" + self.room._ChatRoom__name + ";" + code + "$")
        self.__buffer ( "$@" + self.room._ChatRoom__name + ";" + code + "$" )

    def send_name ( self ):
        self.__buffer ( "$" + self.room._ChatRoom__name + "$" )

    def parse ( self, string ):
        #time.sleep(.2)
        s = string.decode( "utf-16-le" ).strip()
        if len ( s ) == 0:
            # probably EOF. let's commit suicide !
            self.room.disconnect()
            self.room._ChatRoom__shutdownfn()
            return
        if s[0] == '$' and s[-1] == '$' : #check if valid
            if re.match(r'^\$@.+;.+\$\$@.+;.+\$$', s):
                ss = s.split('$$', 1)
                self.parse(s[0]+'$')
                self.parse('$'+s[1])
                return
            p1, p2 = s[1:][:-1].split(';', 1)
            if p1[0] == "~":
                self.room._ChatRoom__privarrivfn ( p1[1:], p2 )
                #self.__printfn ( "PRIV [" + p1 [1:]  + "]   " + p2 )
            elif p1[0] == "@":
                if '~' in p2:
                    p2 = p2.split('~')
                self.room._ChatRoom__handle_special (p1[1:], p2)
            else:
                self.room._ChatRoom__msgfn ( p1, p2 )

class ChatPlusProtocol0:
    def __init__(self, room):
        self.room = room
        self.old = ''

    def __buffer(self, str):
        self.room._ChatRoom__buffer(str.encode('utf-8'))

    def send_msg ( self, msg ):
        self.__buffer ( "MESSAGE;%s\x1e" % msg )
    
    def send_private_msg ( self, to, msg ):
        self.__buffer ( "PRIVATE;%s;%s\x1e" % (to,msg) )

    def send_special ( self, code, content = None ):
        if isinstance(content, basestring): code = code+';'+content
        if isinstance(content, list): code = code+';'+'\x1f'.join(content)
        self.__buffer ( "SPECIAL;%s\x1e" % code )

    def send_name ( self ):
        pass #not implemented in protocol

    def parse ( self, string ):
        s = string.decode( "utf-8" )
        if len ( s ) == 0:
            # probably EOF. let's commit suicide !
            self.room.disconnect()
            self.room._ChatRoom__shutdownfn()
            return

        strs = s.split('\x1e')
        strs[0] = self.old + strs[0] # get possible left-over chars from last time
        self.old = strs.pop()        # the last is empty if there was a terminating RS, otherwise it's incomplete.

        for s in strs:
            prts = s.split(';')
            if prts[0] == 'MESSAGE':
                self.room._ChatRoom__msgfn ( prts[1], ';'.join(prts[2:]) )
            elif prts[0] == 'PRIVATE':
                self.room._ChatRoom__privarrivfn ( prts[1], ';'.join(prts[2:]) )
            elif prts[0] == 'SPECIAL':
                data = ';'.join(prts[2:])
                if '\x1f' in data: data = data.split('\x1f')
                self.room._ChatRoom__handle_special (prts[1], data)


if __name__ == "__main__":
    print "to start the GTK+ GUI, run gtkchat.py; for other UIs, wait."
    sys.exit(1)